Esempio n. 1
0
    def get(self, request):

        user = request.user
        if True:  # user.user_type.level >= UserLevels.admin:
            if request.subst_user:
                user = request.subst_user

        def getit():
            ui = settings.SITE.plugins.react
            # if not settings.SITE.build_js_cache_on_startup:
            #     ui.renderer.build_js_cache(False)
            ar = BaseRequest(
                # user=user,
                request=request,
                renderer=ui.renderer)
            context = dict(
                # title=ar.get_title(),
                # heading=ar.get_title(),
                # main=main,
                front_end=ui,
                request=request,
                user=user,  # Current user
            )
            context.update(ar=ar)
            context = ar.get_printable_context(**context)
            env = settings.SITE.plugins.jinja.renderer.jinja_env
            template = env.get_template("react/main.html")
            return http.HttpResponse(template.render(**context),
                                     content_type='text/html;charset="utf-8"')

        return with_user_profile(user.user_type, getit)
Esempio n. 2
0
    def post(self, request, *args, **kw):
        """logs the user in and builds the linoweb.js file for the logged in user"""
        username = request.POST.get('username')
        password = request.POST.get('password')
        # print(username, password)
        user = auth.authenticate(request, username=username, password=password)
        auth.login(request,
                   user,
                   backend=u'lino.core.auth.backends.ModelBackend')

        # target = '/user/settings/'
        def result():
            if not settings.SITE.build_js_cache_on_startup:
                settings.SITE.plugins.react.renderer.build_js_cache(False)
            # http.HttpResponseRedirect(target) # Seems that fetch has some issues with this...
            return json_response({"success": True})

        return with_user_profile(user.user_type, result)
Esempio n. 3
0
    def get(self, request):
        request = BaseRequest(request)
        u = request.user
        su = request.subst_user
        su_name = request.subst_user.get_full_name() if su else ""

        # not_anon = u.is_authenticated if type(u.is_authenticated) == bool else u.is_authenticated()
        not_anon = u.is_authenticated

        def getit():
            # print(20200419, settings.SITE.build_media_url(*settings.SITE.plugins.react.renderer.lino_js_parts()))
            if not settings.SITE.build_js_cache_on_startup:
                settings.SITE.plugins.react.renderer.build_js_cache(False)
            user_settings = dict(
                user_type=u.user_type,
                dashboard_items=len(u.get_preferences().dashboard_items),
                # [d.serialize() for d in u.get_preferences().dashboard_items],
                lv=str(settings.SITE.kernel.code_mtime),
                lang=get_language(),
                site_data=settings.SITE.build_media_url(
                    *settings.SITE.plugins.react.renderer.lino_js_parts()),
                logged_in=not_anon,
                username=u.get_full_name() if not_anon else _("Anonymous"),
                su_name=
                su_name,  # subst_user # must be passed as param in get_user_settings request,
                act_as_subtext=_(
                    "You are authorised to act as the following users."),
                act_as_title_text=_("Act as another user"),
                act_as_button_text=_("Act as another user"),
                act_as_self_text=_("Stop acting as another user"),
                # #3070: Add id and the text of "My setting" menu
                my_setting_text=_("My settings"),
                user_id=u.pk,
            )
            if su_name:
                user_settings["user_id"] = user_settings["su_id"] = su.id
                user_settings["su_user_type"] = su.user_type

            if not_anon:
                user_settings["authorities"] = u.get_authorities()

            return json_response(user_settings)

        return with_user_profile((su or u).user_type, getit)
Esempio n. 4
0
    def build_site_cache(self, force=False):
        """
        Build the site cache files under `/media/cache`, especially the
        :xfile:`lino*.js` files, one per user user_type and language.
        """
        # if not self.is_prepared:
        #     self.prepare_layouts()
        #     self.is_prepared = True

        if settings.SITE.never_build_site_cache:
            logger.debug(
                "Not building site cache because `settings.SITE.never_build_site_cache` is True"
            )
            return
        if not os.path.isdir(settings.MEDIA_ROOT):
            logger.debug(
                "Not building site cache because " +
                "directory '%s' (settings.MEDIA_ROOT) does not exist.",
                settings.STATIC_ROOT)
            return

        started = time.time()
        # logger.info("20140401 build_site_cache started")

        settings.SITE.on_each_app('setup_site_cache', force)

        settings.SITE.makedirs_if_missing(
            os.path.join(settings.MEDIA_ROOT, 'upload'))
        settings.SITE.makedirs_if_missing(
            os.path.join(settings.MEDIA_ROOT, 'webdav'))

        if force or settings.SITE.build_js_cache_on_startup:
            count = 0
            for lng in settings.SITE.languages:
                with translation.override(lng.django_code):
                    for user_type in UserTypes.objects():
                        count += with_user_profile(user_type,
                                                   self.build_js_cache, force)
            logger.info("%d lino*.js files have been built in %s seconds.",
                        count,
                        time.time() - started)
Esempio n. 5
0
    def build_site_cache(self, force=False):
        """
        Build the site cache files under `/media/cache`, especially the
        :xfile:`lino*.js` files, one per user user_type and language.
        """
        # if not self.is_prepared:
        #     self.prepare_layouts()
        #     self.is_prepared = True

        if settings.SITE.never_build_site_cache:
            logger.debug(
                "Not building site cache because `settings.SITE.never_build_site_cache` is True")
            return
        if not os.path.isdir(settings.MEDIA_ROOT):
            logger.debug(
                "Not building site cache because " +
                "directory '%s' (settings.MEDIA_ROOT) does not exist.",
                settings.STATIC_ROOT)
            return

        started = time.time()
        # logger.info("20140401 build_site_cache started")

        settings.SITE.on_each_app('setup_site_cache', force)

        settings.SITE.makedirs_if_missing(
            os.path.join(settings.MEDIA_ROOT, 'upload'))
        settings.SITE.makedirs_if_missing(
            os.path.join(settings.MEDIA_ROOT, 'webdav'))

        if force or settings.SITE.build_js_cache_on_startup:
            count = 0
            for lng in settings.SITE.languages:
                with translation.override(lng.django_code):
                    for user_type in UserTypes.objects():
                        count += with_user_profile(
                            user_type, self.build_js_cache, force)
            logger.info("%d lino*.js files have been built in %s seconds.",
                        count, time.time() - started)
Esempio n. 6
0
    def get_field_info(ar, column_names=None):
        """
        Return a tuple `(fields, headers, widths)` which expresses which
        columns, headers and widths the user wants for this
        request. If `self` has web request info (:attr:`request` is
        not None), checks for GET parameters cn, cw and ch.  Also
        calls the tables's :meth:`override_column_headers
        <lino.core.actors.Actor.override_column_headers>` method.
        """
        from lino.modlib.users.utils import with_user_profile
        from lino.core.layouts import ColumnsLayout

        def getit():

            if ar.request is None:
                columns = None
            else:
                data = getrqdata(ar.request)
                columns = [
                    str(x) for x in data.getlist(constants.URL_PARAM_COLUMNS)
                ]
            if columns:
                all_widths = data.getlist(constants.URL_PARAM_WIDTHS)
                hiddens = [(x == 'true')
                           for x in data.getlist(constants.URL_PARAM_HIDDENS)]
                fields = []
                widths = []
                ah = ar.actor.get_handle()
                for i, cn in enumerate(columns):
                    col = None
                    for e in ah.list_layout.main.columns:
                        if e.name == cn:
                            col = e
                            break
                    if col is None:
                        raise Exception("No column named %r in %s" %
                                        (cn, ar.ah.list_layout.main.columns))
                    if not hiddens[i]:
                        fields.append(col)
                        widths.append(int(all_widths[i]))
            else:
                if column_names:
                    ll = ColumnsLayout(column_names, datasource=ar.actor)
                    lh = ll.get_layout_handle(settings.SITE.kernel.default_ui)
                    columns = lh.main.columns
                    columns = [e for e in columns if not e.hidden]
                else:
                    ah = ar.actor.get_request_handle(ar)

                    columns = ah.list_layout.main.columns
                    # print(20160530, ah, columns, ah.list_layout.main)

                # render them so that babelfields in hidden_languages
                # get hidden:
                for e in columns:
                    e.value = e.ext_options()
                    # try:
                    #     e.value = e.ext_options()
                    # except AttributeError as ex:
                    #     raise AttributeError("20160529 %s : %s" % (e, ex))
                #
                columns = [
                    e for e in columns if not e.value.get('hidden', False)
                ]

                columns = [e for e in columns if not e.hidden]

                # if str(ar.actor) == "isip.ExamPolicies":
                # from lino.modlib.extjs.elems import is_hidden_babel_field
                # print("20180103", [c.name for c in columns])
                # print("20180103", [c.field for c in columns])
                # print("20180103", [c.value['hidden'] for c in columns])
                # print("20180103", [
                #     is_hidden_babel_field(c.field) for c in columns])
                # print("20180103", [
                #     getattr(c.field, '_babel_language', None)
                #     for c in columns])
                widths = [
                    "%d" % (col.width or col.preferred_width)
                    for col in columns
                ]
                # print("20180831 {}".format(widths))
                # ~ 20130415 widths = ["%d%%" % (col.width or col.preferred_width) for col in columns]
                # ~ fields = [col.field._lino_atomizer for col in columns]
                fields = columns

            headers = [column_header(col) for col in fields]

            # if str(ar.actor).endswith("DailySlave"):
            #     print("20181022", fields[0].field.verbose_name)

            oh = ar.actor.override_column_headers(ar)
            if oh:
                for i, e in enumerate(columns):
                    header = oh.get(e.name, None)
                    if header is not None:
                        headers[i] = header
                # ~ print 20120507, oh, headers

            return fields, headers, widths

        u = ar.get_user()
        if u is None:
            return getit()
        else:
            return with_user_profile(u.user_type, getit)
Esempio n. 7
0
    def get_field_info(ar, column_names=None):
        """
        Return a tuple `(fields, headers, widths)` which expresses which
        columns, headers and widths the user wants for this
        request. If `self` has web request info (:attr:`request` is
        not None), checks for GET parameters cn, cw and ch.  Also
        calls the tables's :meth:`override_column_headers
        <lino.core.actors.Actor.override_column_headers>` method.
        """
        from lino.modlib.users.utils import with_user_profile
        from lino.core.layouts import ColumnsLayout

        def getit():

            if ar.request is None:
                columns = None
            else:
                data = getrqdata(ar.request)
                columns = [
                    six.text_type(x) for x in
                    data.getlist(constants.URL_PARAM_COLUMNS)]
            if columns:
                all_widths = data.getlist(constants.URL_PARAM_WIDTHS)
                hiddens = [(x == 'true') for x in data.getlist(
                    constants.URL_PARAM_HIDDENS)]
                fields = []
                widths = []
                ah = ar.actor.get_handle()
                for i, cn in enumerate(columns):
                    col = None
                    for e in ah.list_layout.main.columns:
                        if e.name == cn:
                            col = e
                            break
                    if col is None:
                        raise Exception("No column named %r in %s" %
                                        (cn, ar.ah.list_layout.main.columns))
                    if not hiddens[i]:
                        fields.append(col)
                        widths.append(int(all_widths[i]))
            else:
                if column_names:
                    ll = ColumnsLayout(column_names, datasource=ar.actor)
                    lh = ll.get_layout_handle(settings.SITE.kernel.default_ui)
                    columns = lh.main.columns
                    columns = [e for e in columns if not e.hidden]
                else:
                    ah = ar.actor.get_request_handle(ar)
                    
                    columns = ah.list_layout.main.columns
                    # print(20160530, ah, columns, ah.list_layout.main)

                # render them so that babelfields in hidden_languages
                # get hidden:
                for e in columns:
                    e.value = e.ext_options()
                    # try:
                    #     e.value = e.ext_options()
                    # except AttributeError as ex:
                    #     raise AttributeError("20160529 %s : %s" % (e, ex))
                #
                columns = [e for e in columns if not
                           e.value.get('hidden', False)]

                columns = [e for e in columns if not e.hidden]

                # if str(ar.actor) == "isip.ExamPolicies":
                    # from lino.modlib.extjs.elems import is_hidden_babel_field
                    # print("20180103", [c.name for c in columns])
                    # print("20180103", [c.field for c in columns])
                    # print("20180103", [c.value['hidden'] for c in columns])
                    # print("20180103", [
                    #     is_hidden_babel_field(c.field) for c in columns])
                    # print("20180103", [
                    #     getattr(c.field, '_babel_language', None)
                    #     for c in columns])
                widths = ["%d" % (col.width or col.preferred_width)
                          for col in columns]
                # print("20180831 {}".format(widths))
                #~ 20130415 widths = ["%d%%" % (col.width or col.preferred_width) for col in columns]
                #~ fields = [col.field._lino_atomizer for col in columns]
                fields = columns

            headers = [column_header(col) for col in fields]

            # if str(ar.actor).endswith("DailyPlanner"):
            #     print("20181022", fields[0].field.verbose_name)

            oh = ar.actor.override_column_headers(ar)
            if oh:
                for i, e in enumerate(columns):
                    header = oh.get(e.name, None)
                    if header is not None:
                        headers[i] = header
                #~ print 20120507, oh, headers

            return fields, headers, widths
    
        u = ar.get_user()
        if u is None:
            return getit()
        else:
            return with_user_profile(u.user_type, getit)