def test_get_form_url(self): """Test get_form_url().""" request = RequestFactory().get('/') # default https://ona.io url = get_form_url(request) self.assertEqual(url, 'https://ona.io') # with username https://ona.io/bob url = get_form_url(request, username='******') self.assertEqual(url, 'https://ona.io/bob') # with http protocol http://ona.io/bob url = get_form_url(request, username='******', protocol='http') self.assertEqual(url, 'http://ona.io/bob') # preview url http://ona.io/preview/bob url = get_form_url(request, username='******', protocol='http', preview=True) self.assertEqual(url, 'http://ona.io/preview/bob') # with form pk url http://ona.io/bob/1 url = get_form_url(request, username='******', xform_pk=1) self.assertEqual(url, 'https://ona.io/bob/1')
def test_get_enketo_single_submit_url(self, mocked): """Test get_single_submit_url. Ensures single submit url is being received. """ request = RequestFactory().get('/') mocked_response = { "single_url": "https://enketo.ona.io/single/::XZqoZ94y", "code": 200 } enketo_url = settings.ENKETO_URL + "/api/v2/survey/single/once" username = "******" server_url = get_form_url( request, username, settings.ENKETO_PROTOCOL, True, xform_pk=1) url = '{}?server_url={}&form_id={}'.format( enketo_url, server_url, "tag_team") mocked.get(url, json=mocked_response) response = get_enketo_single_submit_url( request, username, id_string="tag_team", xform_pk=1) self.assertEqual( response, 'https://enketo.ona.io/single/::XZqoZ94y')
def edit_data(request, username, id_string, data_id): """ Redirects to Enketo webform to edit a submission with the data_id. """ context = RequestContext(request) owner = User.objects.get(username__iexact=username) xform_kwargs = { 'id_string__iexact': id_string, 'user__username__iexact': username } xform = get_form(xform_kwargs) instance = get_object_or_404(Instance, pk=data_id, xform=xform) if not has_edit_permission(xform, owner, request, xform.shared): return HttpResponseForbidden(_(u'Not shared.')) if not hasattr(settings, 'ENKETO_URL'): return HttpResponseRedirect( reverse('form-show', kwargs={ 'username': username, 'id_string': id_string })) url = '%sdata/edit_url' % settings.ENKETO_URL # see commit 220f2dad0e for tmp file creation injected_xml = inject_instanceid(instance.xml, instance.uuid) return_url = request.build_absolute_uri( reverse('submission-instance', kwargs={ 'username': username, 'id_string': id_string }) + "#/" + text(instance.id)) form_url = get_form_url(request, username, settings.ENKETO_PROTOCOL) try: url = get_enketo_urls(form_url, xform.id_string, instance_xml=injected_xml, instance_id=instance.uuid, return_url=return_url) except EnketoError as e: context.message = { 'type': 'alert-error', 'text': u"Enketo error, reason: %s" % e } messages.add_message(request, messages.WARNING, _("Enketo error: enketo replied %s") % e, fail_silently=True) else: if url: url = url['edit_url'] context.enketo = url return HttpResponseRedirect(url) return HttpResponseRedirect( reverse('form-show', kwargs={ 'username': username, 'id_string': id_string }))
def _create_enketo_urls(request, xform): """ Generate enketo urls for a form :param request: :param xform: :return: enketo urls """ form_url = get_form_url(request, xform.user.username, settings.ENKETO_PROTOCOL, xform_pk=xform.pk, generate_consistent_urls=True) data = {} try: enketo_urls = get_enketo_urls(form_url, xform.id_string) offline_url = enketo_urls.get("offline_url") MetaData.enketo_url(xform, offline_url) data['offline_url'] = offline_url if 'preview_url' in enketo_urls: preview_url = enketo_urls.get("preview_url") MetaData.enketo_preview_url(xform, preview_url) data['preview_url'] = preview_url if 'single_url' in enketo_urls: single_url = enketo_urls.get("single_url") MetaData.enketo_single_submit_url(xform, single_url) data['single_url'] = single_url except ConnectionError as e: logging.exception("Connection Error: %s" % e) except EnketoError as e: logging.exception("Enketo Error: %s" % e.message) return data
def enketo(self, request, *args, **kwargs): self.object = self.get_object() data = {} if isinstance(self.object, XForm): raise ParseError(_(u"Data id not provided.")) elif (isinstance(self.object, Instance)): if request.user.has_perm("change_xform", self.object.xform): return_url = request.query_params.get('return_url') form_url = get_form_url(request, self.object.xform.user.username, xform_pk=self.object.xform.id) if not return_url: raise ParseError(_(u"return_url not provided.")) try: data = get_enketo_urls(form_url, self.object.xform.id_string, instance_id=self.object.uuid, instance_xml=self.object.xml, return_url=return_url) if "edit_url" in data: data["url"] = data.pop("edit_url") except EnketoError as e: raise ParseError(text(e)) else: raise PermissionDenied(_(u"You do not have edit permissions.")) self.etag_data = data return Response(data=data)
def test_get_enketo_single_submit_url(self, mocked): """Test get_single_submit_url. Ensures single submit url is being received. """ request = RequestFactory().get('/') mocked_response = { "single_url": "https://enketo.ona.io/single/::XZqoZ94y", "code": 200 } enketo_url = settings.ENKETO_URL + "/api/v2/survey/single/once" username = "******" server_url = get_form_url(request, username, settings.ENKETO_PROTOCOL, True, xform_pk=1) url = '{}?server_url={}&form_id={}'.format(enketo_url, server_url, "tag_team") mocked.get(url, json=mocked_response) response = get_enketo_single_submit_url(request, username, id_string="tag_team", xform_pk=1) self.assertEqual(response, 'https://enketo.ona.io/single/::XZqoZ94y')
def enketo(self, request, **kwargs): self.object = self.get_object() form_url = get_form_url( request, self.object.user.username, settings.ENKETO_PROTOCOL, xform_pk=self.object.pk) data = {'message': _(u"Enketo not properly configured.")} http_status = status.HTTP_400_BAD_REQUEST try: # pass default arguments to enketo_url to prepopulate form fields request_vars = request.GET defaults = generate_enketo_form_defaults( self.object, **request_vars) url = enketo_url(form_url, self.object.id_string, **defaults) preview_url = get_enketo_preview_url(request, self.object.user.username, self.object.id_string, xform_pk=self.object.pk) except EnketoError as e: data = {'message': _(u"Enketo error: %s" % e)} else: if url and preview_url: http_status = status.HTTP_200_OK data = {"enketo_url": url, "enketo_preview_url": preview_url} return Response(data, http_status)
def handle(self, *args, **options): request = HttpRequest() server_name = options.get('server_name') server_port = options.get('server_port') protocol = options.get('protocol') generate_consistent_urls = options.get('generate_consistent_urls') if not server_name or not server_port or not protocol: raise CommandError( 'please provide a server_name, a server_port and a protocol') if server_name not in ['ona.io', 'stage.ona.io', 'localhost']: raise CommandError('server name provided is not valid') if protocol not in ['http', 'https']: raise CommandError('protocol provided is not valid') # required for generation of enketo url request.META['HTTP_HOST'] = '%s:%s' % (server_name, server_port)\ if server_port != '80' else server_name # required for generation of enketo preview url request.META['SERVER_NAME'] = server_name request.META['SERVER_PORT'] = server_port resultset = MetaData.objects.filter( Q(data_type='enketo_url') | Q(data_type='enketo_preview_url')) for meta_data in resultset: username = meta_data.content_object.user.username id_string = meta_data.content_object.id_string data_type = meta_data.data_type data_value = meta_data.data_value xform = meta_data.content_object xform_pk = xform.pk with open('/tmp/enketo_url', 'a') as f: if data_type == 'enketo_url': form_url = get_form_url( request, username=username, id_string=id_string, xform_pk=xform_pk, generate_consistent_urls=generate_consistent_urls) _enketo_url = enketo_url(form_url, id_string) MetaData.enketo_url(xform, _enketo_url) elif data_type == 'enketo_preview_url': _enketo_preview_url = get_enketo_preview_url( request, id_string, username=username, xform_pk=xform_pk, generate_consistent_urls=generate_consistent_urls) MetaData.enketo_preview_url(xform, _enketo_preview_url) f.write('%s : %s \n' % (id_string, data_value)) self.stdout.write('%s: %s' % (data_type, meta_data.data_value)) self.stdout.write("enketo urls update complete!!")
def edit_data(request, username, id_string, data_id): """ Redirects to Enketo webform to edit a submission with the data_id. """ context = RequestContext(request) owner = User.objects.get(username__iexact=username) xform_kwargs = { 'id_string__iexact': id_string, 'user__username__iexact': username } xform = get_form(xform_kwargs) instance = get_object_or_404(Instance, pk=data_id, xform=xform) if not has_edit_permission(xform, owner, request, xform.shared): return HttpResponseForbidden(_(u'Not shared.')) if not hasattr(settings, 'ENKETO_URL'): return HttpResponseRedirect( reverse( 'form-show', kwargs={'username': username, 'id_string': id_string})) url = '%sdata/edit_url' % settings.ENKETO_URL # see commit 220f2dad0e for tmp file creation injected_xml = inject_instanceid(instance.xml, instance.uuid) return_url = request.build_absolute_uri( reverse( 'submission-instance', kwargs={'username': username, 'id_string': id_string}) + "#/" + text(instance.id)) form_url = get_form_url(request, username, settings.ENKETO_PROTOCOL) try: url = enketo_url( form_url, xform.id_string, instance_xml=injected_xml, instance_id=instance.uuid, return_url=return_url) except EnketoError as e: context.message = { 'type': 'alert-error', 'text': u"Enketo error, reason: %s" % e } messages.add_message( request, messages.WARNING, _("Enketo error: enketo replied %s") % e, fail_silently=True) else: if url: context.enketo = url return HttpResponseRedirect(url) return HttpResponseRedirect( reverse( 'form-show', kwargs={'username': username, 'id_string': id_string}))
def enter_data(request, username, id_string): """ Redirects to Enketo webform view. """ owner = get_object_or_404(User, username__iexact=username) xform = get_form({ 'user__username__iexact': username, 'id_string__iexact': id_string }) if not has_edit_permission(xform, owner, request, xform.shared): return HttpResponseForbidden(_(u'Not shared.')) form_url = get_form_url(request, username, settings.ENKETO_PROTOCOL) try: enketo_urls = get_enketo_urls(form_url, xform.id_string) url = enketo_urls.get('url') if not url: return HttpResponseRedirect( reverse('form-show', kwargs={ 'username': username, 'id_string': id_string })) return HttpResponseRedirect(url) except EnketoError as e: data = {} owner = User.objects.get(username__iexact=username) data['profile'], __ = UserProfile.objects.get_or_create(user=owner) data['xform'] = xform data['content_user'] = owner data['form_view'] = True data['message'] = { 'type': 'alert-error', 'text': u"Enketo error, reason: %s" % e } messages.add_message(request, messages.WARNING, _("Enketo error: enketo replied %s") % e, fail_silently=True) return render(request, "profile.html", data) return HttpResponseRedirect( reverse('form-show', kwargs={ 'username': username, 'id_string': id_string }))
def handle(self, *args, **options): request = HttpRequest() server_name = options.get('server_name') server_port = options.get('server_port') protocol = options.get('protocol') if not server_name or not server_port or not protocol: raise CommandError( 'please provide a server_name, a server_port and a protocol') if server_name not in ['ona.io', 'stage.ona.io', 'localhost']: raise CommandError('server name provided is not valid') if protocol not in ['http', 'https']: raise CommandError('protocol provided is not valid') # required for generation of enketo url request.META['HTTP_HOST'] = '%s:%s' % (server_name, server_port)\ if server_port != '80' else server_name # required for generation of enketo preview url request.META['SERVER_NAME'] = server_name request.META['SERVER_PORT'] = server_port resultset = MetaData.objects.filter( Q(data_type='enketo_url') | Q(data_type='enketo_preview_url')) for meta_data in resultset: username = meta_data.content_object.user.username id_string = meta_data.content_object.id_string data_type = meta_data.data_type data_value = meta_data.data_value xform = meta_data.content_object with open('/tmp/enketo_url', 'a') as f: if data_type == 'enketo_url': form_url = get_form_url( request, username, protocol=protocol, xform_pk=xform.pk) _enketo_url = enketo_url(form_url, id_string) MetaData.enketo_url(xform, _enketo_url) elif data_type == 'enketo_preview_url': _enketo_preview_url = get_enketo_preview_url( request, username, id_string, xform_pk=xform.pk) MetaData.enketo_preview_url(xform, _enketo_preview_url) f.write('%s : %s \n' % (id_string, data_value)) self.stdout.write('%s: %s' % (data_type, meta_data.data_value)) self.stdout.write("enketo urls update complete!!")
def test_get_form_url(self): """Test get_form_url().""" request = RequestFactory().get('/') # default https://ona.io url = get_form_url(request) self.assertEqual(url, 'https://ona.io') # with username https://ona.io/bob url = get_form_url(request, username='******') self.assertEqual(url, 'https://ona.io/bob') # with http protocol http://ona.io/bob url = get_form_url(request, username='******', protocol='http') self.assertEqual(url, 'http://ona.io/bob') # preview url http://ona.io/preview/bob url = get_form_url( request, username='******', protocol='http', preview=True) self.assertEqual(url, 'http://ona.io/preview/bob') # with form pk url http://ona.io/bob/1 url = get_form_url(request, username='******', xform_pk=1) self.assertEqual(url, 'https://ona.io/bob/1')
def _create_enketo_url(request, xform): """ Generate enketo url for a form :param request: :param xform: :return: enketo url """ form_url = get_form_url(request, xform.user.username, settings.ENKETO_PROTOCOL) url = "" try: url = enketo_url(form_url, xform.id_string) MetaData.enketo_url(xform, url) except ConnectionError, e: logging.exception("Connection Error: %s" % e.message)
def enter_data(request, username, id_string): """ Redirects to Enketo webform view. """ owner = get_object_or_404(User, username__iexact=username) xform = get_form({ 'user__username__iexact': username, 'id_string__iexact': id_string }) if not has_edit_permission(xform, owner, request, xform.shared): return HttpResponseForbidden(_(u'Not shared.')) form_url = get_form_url(request, username, settings.ENKETO_PROTOCOL) try: url = enketo_url(form_url, xform.id_string) if not url: return HttpResponseRedirect( reverse( 'form-show', kwargs={'username': username, 'id_string': id_string})) return HttpResponseRedirect(url) except EnketoError as e: data = {} owner = User.objects.get(username__iexact=username) data['profile'], __ = UserProfile.objects.get_or_create(user=owner) data['xform'] = xform data['content_user'] = owner data['form_view'] = True data['message'] = { 'type': 'alert-error', 'text': u"Enketo error, reason: %s" % e } messages.add_message( request, messages.WARNING, _("Enketo error: enketo replied %s") % e, fail_silently=True) return render(request, "profile.html", data) return HttpResponseRedirect( reverse( 'form-show', kwargs={'username': username, 'id_string': id_string}))
def test_get_single_submit_url_error_action(self, mocked): """Test get_single_submit_url to raises EnketoError.""" request = RequestFactory().get('/') enketo_url = settings.ENKETO_URL + "/api/v2/survey/single/once" username = "******" server_url = get_form_url( request, username, settings.ENKETO_PROTOCOL, True, xform_pk=1) url = '{}?server_url={}&form_id={}'.format( enketo_url, server_url, "tag_team") mocked.get(url, status_code=401) msg = "There was a problem with your submissionor form."\ " Please contact support." self.assertRaisesMessage( EnketoError, msg, get_enketo_single_submit_url, request, username, "tag_team", 1)
def test_get_single_submit_url_error_action(self, mocked): """Test get_single_submit_url to raises EnketoError.""" request = RequestFactory().get('/') enketo_url = settings.ENKETO_URL + "/api/v2/survey/single/once" username = "******" server_url = get_form_url(request, username, settings.ENKETO_PROTOCOL, True, xform_pk=1) url = '{}?server_url={}&form_id={}'.format(enketo_url, server_url, "tag_team") mocked.get(url, status_code=401) msg = "There was a problem with your submissionor form."\ " Please contact support." self.assertRaisesMessage(EnketoError, msg, get_enketo_single_submit_url, request, username, "tag_team", 1)
def _create_enketo_url(request, xform): """ Generate enketo url for a form :param request: :param xform: :return: enketo url """ form_url = get_form_url(request, xform.user.username, settings.ENKETO_PROTOCOL, xform_pk=xform.pk) url = "" try: url = enketo_url(form_url, xform.id_string) MetaData.enketo_url(xform, url) except ConnectionError as e: logging.exception("Connection Error: %s" % e) except EnketoError as e: logging.exception("Enketo Error: %s" % e.message) return url
def enketo(self, request, **kwargs): """Expose enketo urls.""" survey_type = self.kwargs.get('survey_type') or \ request.GET.get('survey_type') self.object = self.get_object() form_url = get_form_url(request, self.object.user.username, protocol=settings.ENKETO_PROTOCOL, xform_pk=self.object.pk, generate_consistent_urls=True) data = {'message': _(u"Enketo not properly configured.")} http_status = status.HTTP_400_BAD_REQUEST try: # pass default arguments to enketo_url to prepopulate form fields request_vars = request.GET defaults = generate_enketo_form_defaults(self.object, **request_vars) url = enketo_url(form_url, self.object.id_string, **defaults) preview_url = get_enketo_preview_url(request, self.object.user.username, self.object.id_string, xform_pk=self.object.pk) except EnketoError as e: data = {'message': _(u"Enketo error: %s" % e)} else: if survey_type == 'single': single_submit_url = get_enketo_single_submit_url( request, self.object.user.username, self.object.id_string, xform_pk=self.object.pk) data = {"single_submit_url": single_submit_url} elif url and preview_url: http_status = status.HTTP_200_OK data = {"enketo_url": url, "enketo_preview_url": preview_url} return Response(data, http_status)
def enketo(self, request, **kwargs): """Expose enketo urls.""" survey_type = self.kwargs.get('survey_type') or \ request.GET.get('survey_type') self.object = self.get_object() form_url = get_form_url( request, self.object.user.username, settings.ENKETO_PROTOCOL, xform_pk=self.object.pk) data = {'message': _(u"Enketo not properly configured.")} http_status = status.HTTP_400_BAD_REQUEST try: # pass default arguments to enketo_url to prepopulate form fields request_vars = request.GET defaults = generate_enketo_form_defaults( self.object, **request_vars) url = enketo_url( form_url, self.object.id_string, **defaults) preview_url = get_enketo_preview_url(request, self.object.user.username, self.object.id_string, xform_pk=self.object.pk) except EnketoError as e: data = {'message': _(u"Enketo error: %s" % e)} else: if survey_type == 'single': single_submit_url = get_enketo_single_submit_url( request, self.object.user.username, self.object.id_string, xform_pk=self.object.pk) data = {"single_submit_url": single_submit_url} elif url and preview_url: http_status = status.HTTP_200_OK data = {"enketo_url": url, "enketo_preview_url": preview_url} return Response(data, http_status)
def handle(self, *args, **kwargs): request = HttpRequest() server_name = kwargs.get('server_name') server_port = kwargs.get('server_port') protocol = kwargs.get('protocol') username = kwargs.get('username') id_string = kwargs.get('id_string') if not server_name or not server_port or not protocol: raise CommandError( 'please provide a server_name, a server_port and a protocol') if server_name not in ['api.ona.io', 'stage-api.ona.io', 'localhost']: raise CommandError('server name provided is not valid') if protocol not in ['http', 'https']: raise CommandError('protocol provided is not valid') # required for generation of enketo url request.META['HTTP_HOST'] = '%s:%s' % (server_name, server_port)\ if server_port != '80' else server_name # required for generation of enketo preview url request.META['SERVER_NAME'] = server_name request.META['SERVER_PORT'] = server_port if username and id_string: form_url = get_form_url(request, username, protocol=protocol) try: xform = XForm.objects.get(user__username=username, id_string=id_string) id_string = xform.id_string _url = enketo_url(form_url, id_string) _preview_url = get_enketo_preview_url(request, username, id_string) self.stdout.write('enketo url: %s | preview url: %s' % (_url, _preview_url)) self.stdout.write("enketo urls generation completed!!") except XForm.DoesNotExist: self.stdout.write( "No xform matching the provided username and id_string") elif username and id_string is None: form_url = get_form_url(request, username, protocol=protocol) xforms = XForm.objects.filter(user__username=username) num_of_xforms = xforms.count() if xforms: for xform in queryset_iterator(xforms): id_string = xform.id_string _url = enketo_url(form_url, id_string) _preview_url = get_enketo_preview_url( request, username, id_string) num_of_xforms -= 1 self.stdout.write( 'enketo url: %s | preview url: %s | remaining: %s' % (_url, _preview_url, num_of_xforms)) self.stdout.write("enketo urls generation completed!!") else: self.stdout.write("Username doesn't own any form") else: xforms = XForm.objects.all() num_of_xforms = xforms.count() for xform in queryset_iterator(xforms): username = xform.user.username id_string = xform.id_string form_url = get_form_url(request, username, protocol=protocol) _url = enketo_url(form_url, id_string) _preview_url = get_enketo_preview_url(request, username, id_string) num_of_xforms -= 1 self.stdout.write( 'enketo url: %s | preview url: %s | remaining: %s' % (_url, _preview_url, num_of_xforms)) self.stdout.write("enketo urls generation completed!!")
def handle(self, *args, **options): request = HttpRequest() server_name = options.get('server_name') server_port = options.get('server_port') protocol = options.get('protocol') username = options.get('username') id_string = options.get('id_string') if not server_name or not server_port or not protocol: raise CommandError( 'please provide a server_name, a server_port and a protocol') if server_name not in ['api.ona.io', 'stage-api.ona.io', 'localhost']: raise CommandError('server name provided is not valid') if protocol not in ['http', 'https']: raise CommandError('protocol provided is not valid') # required for generation of enketo url request.META['HTTP_HOST'] = '%s:%s' % (server_name, server_port)\ if server_port != '80' else server_name # required for generation of enketo preview url request.META['SERVER_NAME'] = server_name request.META['SERVER_PORT'] = server_port if username and id_string: try: xform = XForm.objects.get( user__username=username, id_string=id_string) form_url = get_form_url(request, username, protocol=protocol, xform_pk=xform.pk) id_string = xform.id_string _url = enketo_url(form_url, id_string) _preview_url = get_enketo_preview_url(request, username, id_string, xform_pk=xform.pk) self.stdout.write('enketo url: %s | preview url: %s' % (_url, _preview_url)) self.stdout.write("enketo urls generation completed!!") except XForm.DoesNotExist: self.stdout.write( "No xform matching the provided username and id_string") elif username and id_string is None: xforms = XForm.objects.filter(user__username=username) num_of_xforms = xforms.count() if xforms: for xform in queryset_iterator(xforms): form_url = get_form_url(request, username, protocol=protocol, xform_pk=xform.pk) id_string = xform.id_string _url = enketo_url(form_url, id_string) _preview_url = get_enketo_preview_url( request, username, id_string, xform_pk=xform.pk) num_of_xforms -= 1 self.stdout.write( 'enketo url: %s | preview url: %s | remaining: %s' % (_url, _preview_url, num_of_xforms)) self.stdout.write("enketo urls generation completed!!") else: self.stdout.write("Username doesn't own any form") else: xforms = XForm.objects.all() num_of_xforms = xforms.count() for xform in queryset_iterator(xforms): username = xform.user.username id_string = xform.id_string form_url = get_form_url(request, username, protocol=protocol, xform_pk=xform.pk) _url = enketo_url(form_url, id_string) _preview_url = get_enketo_preview_url(request, username, id_string, xform_pk=xform.pk) num_of_xforms -= 1 self.stdout.write( 'enketo url: %s | preview url: %s | remaining: %s' % (_url, _preview_url, num_of_xforms)) self.stdout.write("enketo urls generation completed!!")