コード例 #1
0
def multimedia_ajax(request, domain, app_id):
    app = get_app(domain, app_id)
    if not is_remote_app(app):
        try:
            multimedia_state = app.check_media_state()
        except ReportConfigurationNotFoundError:
            return JsonResponse(
                {"message": _("One of the Report menus is misconfigured, please try again after they are fixed")},
                status=500)

        context = {
            'multimedia_state': multimedia_state,
            'domain': domain,
            'app': app,
            'is_linked_app': is_linked_app(app),
        }

        if toggles.MULTI_MASTER_LINKED_DOMAINS.enabled_for_request(request):
            missing_paths = {p for p in app.all_media_paths() if p not in app.multimedia_map}
            import_apps = get_apps_in_domain(domain, include_remote=False)
            import_app_counts = {
                a.id: len(missing_paths.intersection(a.multimedia_map.keys()))
                for a in import_apps
            }
            import_apps = [a for a in import_apps if import_app_counts[a.id]]
            context.update({
                'import_apps': import_apps,
                'import_app_counts': import_app_counts,
            })

        return render(request, "app_manager/partials/settings/multimedia_ajax.html", context)
    else:
        raise Http404()
コード例 #2
0
def _get_forms(app):
    """
    Return list of forms in the app
    """
    if is_remote_app(app):
        return []
    forms = []
    for module in app.get_modules():
        forms.extend(module.get_forms())
    return forms
コード例 #3
0
def get_form_list(domain):
    form_list = []
    for app_id in get_app_ids_in_domain(domain):
        latest_app = get_app(domain, app_id, latest=True)
        if not is_remote_app(latest_app):
            for m in latest_app.get_modules():
                for f in m.get_forms():
                    form_list.append({
                        "code": f.unique_id,
                        "name": f.full_path_name
                    })
    return form_list
コード例 #4
0
def get_form_list(domain):
    form_list = []
    briefs = get_brief_apps_in_domain(domain)
    for brief in sorted(briefs, key=lambda b: b.name):
        latest_app = get_app(domain, brief.id, latest=True)
        if not is_remote_app(latest_app):
            for m in latest_app.get_modules():
                for f in m.get_forms():
                    form_list.append({
                        "code": get_combined_id(latest_app.origin_id, f.unique_id),
                        "name": f.full_path_name,
                    })
    return form_list
コード例 #5
0
def multimedia_ajax(request, domain, app_id):
    app = get_app(domain, app_id)
    if not is_remote_app(app):
        try:
            multimedia_state = app.check_media_state()
        except ReportConfigurationNotFoundError:
            return JsonResponse(
                {"message": _("One of the Report menus is misconfigured, please try again after they are fixed")},
                status=500)
        context = {
            'multimedia_state': multimedia_state,
            'domain': domain,
            'app': app,
            'is_linked_app': is_linked_app(app),
        }
        return render(request, "app_manager/partials/settings/multimedia_ajax.html", context)
    else:
        raise Http404()
コード例 #6
0
    def update_schema(self):
        all_app_ids = get_build_ids_after_version(self.domain, self.app_id,
                                                  self.last_processed_version)

        all_seen_apps = self.apps_with_errors | self.processed_apps
        to_process = [
            app_id for app_id in all_app_ids if app_id not in all_seen_apps
        ]
        if self.app_id not in all_seen_apps:
            to_process.append(self.app_id)

        for app_doc in iter_docs(Application.get_db(), to_process):
            if is_remote_app(app_doc):
                continue
            app = Application.wrap(app_doc)
            try:
                self.update_for_app(app)
            except AppManagerException:
                self.apps_with_errors.add(app.get_id)
                self.last_processed_version = app.version

        if to_process:
            self.save()
コード例 #7
0
ファイル: app_summary.py プロジェクト: solleks/commcare-hq
    def page_context(self):
        if not self.app or is_remote_app(self.app):
            raise Http404()

        return self._app_dict(self.app)
コード例 #8
0
 def has_media(self):
     from corehq.apps.app_manager.util import is_remote_app
     for app in self.full_applications():
         if not is_remote_app(app) and app.has_media():
             return True
     return False
コード例 #9
0
def view_generic(request,
                 domain,
                 app_id,
                 module_id=None,
                 form_id=None,
                 copy_app_form=None,
                 release_manager=False,
                 module_unique_id=None,
                 form_unique_id=None):
    """
    This is the main view for the app. All other views redirect to here.

    """
    if form_id and not module_id and module_unique_id is None:
        return bail(request, domain, app_id)

    app = get_app(domain, app_id)
    module = form = None

    if module_id:
        try:
            module = app.get_module(module_id)
        except ModuleNotFoundException:
            raise Http404()
        if not module.unique_id:
            module.get_or_create_unique_id()
            app.save()
    elif module_unique_id:
        try:
            module = app.get_module_by_unique_id(module_unique_id)
        except ModuleNotFoundException:
            raise Http404()
        module_id = module.id

    if form_id and module is not None:
        try:
            form = module.get_form(form_id)
        except IndexError:
            raise Http404()
    elif form_unique_id:
        try:
            form = app.get_form(form_unique_id)
        except FormNotFoundException:
            raise Http404()
        form_id = form.id

    if form is not None and module is None:
        # this is the case where only the form_unique_id is given
        module = form.get_module()
        module_id = module.id

    # Application states that should no longer exist
    if app.application_version == APP_V1:
        _assert = soft_assert()
        _assert(False, 'App version 1.0', {'domain': domain, 'app_id': app_id})
        return render(request, "app_manager/no_longer_supported.html", {
            'domain': domain,
            'app': app,
        })
    if not app.vellum_case_management and not app.is_remote_app():
        # Soft assert but then continue rendering; template will contain a user-facing warning
        _assert = soft_assert(['jschweers' + '@' + 'dimagi.com'])
        _assert(False, 'vellum_case_management=False', {
            'domain': domain,
            'app_id': app_id
        })
    if (form is not None
            and "usercase_preload" in getattr(form, "actions", {})
            and form.actions.usercase_preload.preload):
        _assert = soft_assert(['dmiller' + '@' + 'dimagi.com'])
        _assert(
            False, 'User property easy refs + old-style config = bad', {
                'domain': domain,
                'app_id': app_id,
                'module_id': module_id,
                'module_unique_id': module_unique_id,
                'form_id': form_id,
                'form_unique_id': form_unique_id,
            })

    context = get_apps_base_context(request, domain, app)
    if app.copy_of:
        # redirect to "main" app rather than specific build
        return HttpResponseRedirect(
            reverse("view_app", args=[domain, app.copy_of]))

    context.update({
        'module': module,
        'form': form,
    })

    lang = context['lang']
    if not module and hasattr(app, 'translations'):
        context.update({"translations": app.translations.get(lang, {})})

    if not app.is_remote_app():
        context.update({
            'add_ons':
            add_ons.get_dict(request, app, module, form),
            'add_ons_privileges':
            add_ons.get_privileges_dict(request),
            'add_ons_layout':
            add_ons.get_layout(request),
        })

    if form:
        template, form_context = get_form_view_context_and_template(
            request, domain, form, context['langs'], current_lang=lang)
        context.update(form_context)
    elif module:
        template = get_module_template(request.user, module)
        # make sure all modules have unique ids
        app.ensure_module_unique_ids(should_save=True)
        module_context = get_module_view_context(request, app, module, lang)
        context.update(module_context)
    else:
        context.update(get_app_view_context(request, app))

        template = 'app_manager/app_view_settings.html'
        if release_manager:
            template = 'app_manager/app_view_release_manager.html'
        if release_manager:
            context.update(get_releases_context(request, domain, app_id))
        context.update({
            'is_app_settings_page': not release_manager,
        })

    # update multimedia context for forms and modules.
    menu_host = form or module
    if menu_host:
        default_file_name = 'module%s' % module_id
        if form:
            default_file_name = '%s_form%s' % (default_file_name, form_id)

        specific_media = [{
            'menu_refs':
            app.get_menu_media(module,
                               form=form,
                               form_index=form_id,
                               to_language=lang),
            'default_file_name':
            '{name}_{lang}'.format(name=default_file_name, lang=lang),
        }]

        if not form and module and not isinstance(
                module, ReportModule) and module.uses_media():

            def _make_name(suffix):
                return "{default_name}_{suffix}_{lang}".format(
                    default_name=default_file_name,
                    suffix=suffix,
                    lang=lang,
                )

            specific_media.append({
                'menu_refs':
                app.get_case_list_form_media(module, to_language=lang),
                'default_file_name':
                _make_name('case_list_form'),
                'qualifier':
                'case_list_form_',
            })
            specific_media.append({
                'menu_refs':
                app.get_case_list_menu_item_media(module, to_language=lang),
                'default_file_name':
                _make_name('case_list_menu_item'),
                'qualifier':
                'case_list-menu_item_',
            })
            if (toggles.CASE_LIST_LOOKUP.enabled(request.user.username)
                    or toggles.CASE_LIST_LOOKUP.enabled(app.domain)
                    or toggles.BIOMETRIC_INTEGRATION.enabled(app.domain)):
                specific_media.append({
                    'menu_refs':
                    app.get_case_list_lookup_image(module),
                    'default_file_name':
                    '{}_case_list_lookup'.format(default_file_name),
                    'qualifier':
                    'case-list-lookupcase',
                })

                if hasattr(module, 'product_details'):
                    specific_media.append({
                        'menu_refs':
                        app.get_case_list_lookup_image(module, type='product'),
                        'default_file_name':
                        '{}_product_list_lookup'.format(default_file_name),
                        'qualifier':
                        'case-list-lookupproduct',
                    })

        uploaders = {
            'icon':
            MultimediaImageUploadController(
                "hqimage",
                reverse(ProcessImageFileUploadView.urlname,
                        args=[app.domain, app.get_id])),
            'audio':
            MultimediaAudioUploadController(
                "hqaudio",
                reverse(ProcessAudioFileUploadView.urlname,
                        args=[app.domain, app.get_id])),
        }

        multimedia_map = app.multimedia_map
        if form or module:
            multimedia_map = (form or module).get_relevant_multimedia_map(app)
        context.update({
            'multimedia': {
                "object_map":
                app.get_object_map(multimedia_map=multimedia_map),
                'upload_managers': uploaders,
                'upload_managers_js':
                {type: u.js_options
                 for type, u in uploaders.items()},
            }
        })

        context['module_icon'] = None
        if toggles.CUSTOM_ICON_BADGES.enabled(domain):
            context[
                'module_icon'] = module.custom_icon if module.custom_icon else CustomIcon(
                )
        context['nav_menu_media_specifics'] = specific_media

    error = request.GET.get('error', '')

    context.update({
        'error': error,
        'app': app,
    })

    # Pass form for Copy Application to template
    domain_names = {
        d.name
        for d in Domain.active_for_user(request.couch_user)
        if not (is_linked_domain(request.domain) and get_domain_master_link(
            request.domain).master_domain == d.name)
    }
    domain_names.add(request.domain)
    if copy_app_form is None:
        copy_app_form = CopyApplicationForm(domain, app)
        context.update({
            'domain_names': sorted(domain_names),
        })
    linked_domains_enabled = toggles.LINKED_DOMAINS.enabled(domain)
    context.update({
        'copy_app_form': copy_app_form,
        'linked_domains_enabled': linked_domains_enabled,
    })

    context['latest_commcare_version'] = get_commcare_versions(
        request.user)[-1]

    if not is_remote_app(app) and has_privilege(
            request, privileges.COMMCARE_LOGO_UPLOADER):
        uploader_slugs = list(ANDROID_LOGO_PROPERTY_MAPPING.keys())
        from corehq.apps.hqmedia.controller import MultimediaLogoUploadController
        from corehq.apps.hqmedia.views import ProcessLogoFileUploadView
        uploaders = [
            MultimediaLogoUploadController(
                slug,
                reverse(
                    ProcessLogoFileUploadView.urlname,
                    args=[domain, app_id, slug],
                )) for slug in uploader_slugs
        ]
        context.update({
            "sessionid": request.COOKIES.get('sessionid'),
            "uploaders": uploaders,
            "uploaders_js": [u.js_options for u in uploaders],
            "refs": {
                slug: ApplicationMediaReference(
                    app.logo_refs.get(slug, {}).get("path", slug),
                    media_class=CommCareImage,
                ).as_dict()
                for slug in uploader_slugs
            },
            "media_info": {
                slug: app.logo_refs.get(slug)
                for slug in uploader_slugs if app.logo_refs.get(slug)
            },
        })

    context.update({
        'show_live_preview':
        should_show_preview_app(request, app, request.couch_user.username),
        'can_preview_form':
        request.couch_user.has_permission(domain, 'edit_data')
    })

    confirm = request.session.pop('CONFIRM', False)
    context.update({'confirm': confirm})

    response = render(request, template, context)

    set_lang_cookie(response, lang)
    return response
コード例 #10
0
 def require_remote_app():
     if not is_remote_app(app):
         raise Exception("App type %s does not support profile url" % app.get_doc_type())
コード例 #11
0
def get_app_view_context(request, app):
    """
    This provides the context to render commcare settings on Edit Application Settings page

    This is where additional app or domain specific context can be added to any individual
    commcare-setting defined in commcare-app-settings.yaml or commcare-profile-settings.yaml
    """
    context = {}

    settings_layout = copy.deepcopy(
        get_commcare_settings_layout(app)
    )

    for section in settings_layout:
        new_settings = []
        for setting in section['settings']:
            toggle_name = setting.get('toggle')
            if toggle_name and not toggle_enabled(request, toggle_name):
                continue
            privilege_name = setting.get('privilege')
            if privilege_name and not has_privilege(request, privilege_name):
                continue
            disable_if_true = setting.get('disable_if_true')
            if disable_if_true and getattr(app, setting['id']):
                continue
            if is_linked_app(app):
                if setting['id'] in app.SUPPORTED_SETTINGS:
                    if setting['id'] not in app.linked_app_attrs:
                        setting['is_inherited'] = True
            new_settings.append(setting)
        section['settings'] = new_settings

    app_view_options = {
        'permissions': {
            'cloudcare': has_privilege(request, privileges.CLOUDCARE),
            'case_sharing_groups': has_privilege(request,
                                                 privileges.CASE_SHARING_GROUPS),
        },
        'sections': settings_layout,
        'urls': {
            'save': reverse("edit_commcare_settings", args=(app.domain, app.id)),
        },
        'user': {
            'is_previewer': request.couch_user.is_previewer(),
        },
        'values': get_settings_values(app),
        'warning': _("This is not an allowed value for this field"),
    }
    if (app.get_doc_type() == 'Application'
            and toggles.CUSTOM_PROPERTIES.enabled(request.domain)
            and 'custom_properties' in getattr(app, 'profile', {})):
        custom_properties_array = [{'key': p[0], 'value': p[1]} for p in app.profile.get('custom_properties').items()]
        app_view_options.update({'customProperties': custom_properties_array})
    context.update({
        'app_view_options': app_view_options,
    })

    build_config = CommCareBuildConfig.fetch()
    options = build_config.get_menu()
    if not request.user.is_superuser and not toggles.IS_CONTRACTOR.enabled(request.user.username):
        options = [option for option in options if not option.superuser_only]
    options_map = defaultdict(lambda: {"values": [], "value_names": []})
    for option in options:
        builds = options_map[option.build.major_release()]
        builds["values"].append(option.build.to_string())
        builds["value_names"].append(option.get_label())
        if "default" not in builds:
            app_ver = MAJOR_RELEASE_TO_VERSION[option.build.major_release()]
            builds["default"] = build_config.get_default(app_ver).to_string()

    def _get_setting(setting_type, setting_id):
        # get setting dict from settings_layout
        if not settings_layout:
            return None
        matched = [x for x in [
                setting for section in settings_layout
                for setting in section['settings']
            ] if x['type'] == setting_type and x['id'] == setting_id]
        if matched:
            return matched[0]
        else:
            return None

    build_spec_setting = _get_setting('hq', 'build_spec')
    if build_spec_setting:
        build_spec_setting['options_map'] = options_map
        build_spec_setting['default_app_version'] = app.application_version

    practice_user_setting = _get_setting('hq', 'practice_mobile_worker_id')
    if practice_user_setting and has_privilege(request, privileges.PRACTICE_MOBILE_WORKERS):
        try:
            practice_users = get_practice_mode_mobile_workers(request.domain)
        except ESError:
            notify_exception(request, 'Error getting practice mode mobile workers')
            practice_users = []
        practice_user_setting['values'] = [''] + [u['_id'] for u in practice_users]
        practice_user_setting['value_names'] = [_('Not set')] + [u['username'] for u in practice_users]

    context.update({
        'bulk_ui_translation_upload': {
            'action': reverse('upload_bulk_ui_translations',
                              args=(app.domain, app.get_id)),
            'download_url': reverse('download_bulk_ui_translations',
                                    args=(app.domain, app.get_id)),
            'adjective': _("U\u200BI translation"),
            'plural_noun': _("U\u200BI translations"),
        },
        'bulk_app_translation_upload': {
            'action': reverse('upload_bulk_app_translations',
                              args=(app.domain, app.get_id)),
            'download_url': reverse('download_bulk_app_translations',
                                    args=(app.domain, app.get_id)),
            'adjective': _("app translation"),
            'plural_noun': _("app translations"),
            'can_select_language': toggles.BULK_UPDATE_MULTIMEDIA_PATHS.enabled_for_request(request),
            'can_validate_app_translations': toggles.VALIDATE_APP_TRANSLATIONS.enabled_for_request(request),
        },
    })
    context.update({
        'bulk_ui_translation_form': get_bulk_upload_form(
            context,
            context_key="bulk_ui_translation_upload",
        ),
        'bulk_app_translation_form': get_bulk_upload_form(
            context,
            context_key="bulk_app_translation_upload",
            form_class=AppTranslationsBulkUploadForm,
        ),
    })
    context.update({
        'smart_lang_display_enabled': getattr(app, 'smart_lang_display', False)
    })

    context.update({
        'is_linked_app': is_linked_app(app),
        'is_remote_app': is_remote_app(app),
    })
    if is_linked_app(app):
        try:
            master_versions_by_id = app.get_latest_master_releases_versions()
            master_briefs = [brief for brief in app.get_master_app_briefs() if brief.id in master_versions_by_id]
        except RemoteRequestError:
            messages.error(request, "Unable to reach remote master server. Please try again later.")
            master_versions_by_id = {}
            master_briefs = []
        upstream_brief = {}
        for b in master_briefs:
            if b.id == app.upstream_app_id:
                upstream_brief = b
        context.update({
            'master_briefs': master_briefs,
            'master_versions_by_id': master_versions_by_id,
            'multiple_masters': app.enable_multi_master and len(master_briefs) > 1,
            'upstream_version': app.upstream_version,
            'upstream_brief': upstream_brief,
            'upstream_url': _get_upstream_url(app, request.couch_user),
            'upstream_url_template': _get_upstream_url(app, request.couch_user, master_app_id='---'),
        })
    return context