def get_or_post(self, request, form): """Common result, the same for GET or POST data. Takes a bound form.""" pattern = form.cleaned_data["q"] if form.is_valid() else None search_query = self.get_query(request, pattern=pattern) page = request.GET.get("page") paginator = Paginator(search_query, 25) try: paginated_results = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. paginated_results = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. paginated_results = paginator.page(paginator.num_pages) context = { "form": form, "paginated_url": "%s?%s" % (reverse("df:site_search"), urlencode({"q": pattern})), "paginated_results": paginated_results, "formatted_results": self.formatted_results(paginated_results), "formatted_header": self.formatted_header(), } extra_context = self.get_template_values(request) context.update(extra_context) set_websocket_topics(request) return self.render_to_response(context)
def df_init_websocket(context, *topics): """Set the websocket URL with the access token. Allow to access the right topics.""" if not settings.WEBSOCKET_URL: return "" elif not context.get("df_has_ws_topics") and not topics: return "" elif not context.get("df_has_ws_topics") and context.get("df_http_request"): set_websocket_topics(context["df_http_request"], *topics) ws_token = context["df_window_key"] session_id = context["df_session_id"] signer = signing.Signer(session_id) signed_token = signer.sign(ws_token) protocol = "wss" if settings.USE_SSL else "ws" site_name = "%s:%s" % (settings.SERVER_NAME, settings.SERVER_PORT) script = '$.df._wsConnect("%s://%s%s?token=%s");' % ( protocol, site_name, settings.WEBSOCKET_URL, signed_token, ) script += '$.df._wsToken="%s";' % signed_token script = "$(document).ready(function(){%s});" % script init_value = '<script type="application/javascript">%s</script>' % script init_value += ( '<script type="text/javascript" src="%s" charset="utf-8"></script>' % reverse("df:signals") ) return mark_safe(init_value)
def df_init_websocket(context, *topics): """Set the websocket URL with the access token. Allow to access the right topics.""" if not settings.WEBSOCKET_URL: return "" elif not context.get("df_has_ws_topics") and not topics: return "" elif not context.get("df_has_ws_topics") and context.get( "df_http_request"): set_websocket_topics(context["df_http_request"], *topics) ws_token = context["df_window_key"] session_id = context["df_session_id"] signer = signing.Signer(session_id) signed_token = signer.sign(ws_token) protocol = "wss" if settings.USE_SSL else "ws" site_name = "%s:%s" % (settings.SERVER_NAME, settings.SERVER_PORT) script = '$.df._wsConnect("%s://%s%s?token=%s");' % ( protocol, site_name, settings.WEBSOCKET_URL, signed_token, ) script += '$.df._wsToken="%s";' % signed_token script = "$(document).ready(function(){%s});" % script init_value = '<script type="application/javascript">%s</script>' % script init_value += ( '<script type="text/javascript" src="%s" charset="utf-8"></script>' % reverse("df:signals")) return mark_safe(init_value)
def cache_private(request): logger.warning("compute cache_private page") set_websocket_topics(request) return TemplateResponse( request, "easydemo/index.html", {"form": TestForm(), "title": "Cached for public"}, )
def cache_vary_on_headers(request): logger.warning( "compute cache_vary_on_headers page (User-Agent=%s)" % request.META.get("HTTP_USER_AGENT") ) set_websocket_topics(request) return TemplateResponse( request, "easydemo/index.html", {"form": TestForm(), "title": "Cache by User-Agent"}, )
def chat(request): name = None if request.method == "POST": form = ChatLoginForm(request.POST) if form.is_valid(): name = form.cleaned_data["name"] form = None set_websocket_topics(request, "chat-%s" % name) else: form = ChatLoginForm() set_websocket_topics(request) template_values = {"form": form, "name": name} return TemplateResponse(request, "easydemo/chat.html", template_values)
def get(self, request, *args, **kwargs): logger.debug("debug log message") logger.info("info log message") logger.warning("warn log message") logger.error("error log message") messages.error(request, "Example of error message") set_websocket_topics(request) form = TestForm() upload_form = UploadFileForm() template_values = { "form": form, "title": "Hello, world!", "debug": settings.DEBUG, "upload_form": upload_form, "simple_upload_form": SimpleUploadFileForm(), } return self.render_to_response(template_values)
def show_doc(request, doc_id, path=''): user = request.user if request.user.is_authenticated else None if not user and not settings.PUBLIC_DOCS: raise Http404 doc = get_object_or_404(UploadDoc, id=doc_id) if user: set_websocket_topics(request, doc) root_path = os.path.abspath(doc.path) full_path = os.path.abspath(os.path.join(root_path, path)) if not full_path.startswith(root_path): raise Http404 checked, created = LastDocs.objects.get_or_create(user=user, doc=doc) use_auth = reverse('updoc:show_doc', kwargs={'doc_id': doc_id, 'path': path}) == request.path view = 'updoc:show_doc' if use_auth else 'updoc:show_doc_alt' if not created: now = datetime.datetime.utcnow().replace(tzinfo=utc) LastDocs.objects.filter(user=user, doc=doc).update(count=F('count') + 1, last=now) editable = user and (user.is_superuser or user == doc.user) if not os.path.isfile(full_path): directory = list_directory(root_path, path, view, view_arg='path', view_kwargs={'doc_id': doc.id}, dir_view_name=view, dir_view_arg='path', dir_view_kwargs={'doc_id': doc.id}, show_files=True, show_dirs=True, show_parent=bool(path), show_hidden=False) template_values = {'directory': directory, 'doc': doc, 'editable': editable, 'title': str(doc), 'keywords': ' '.join([keyword.value for keyword in doc.keywords.all()]), 'doc_id': doc_id, } return TemplateResponse(request, 'updoc/list_dir.html', template_values) if full_path.endswith('.md'): view_name = 'updoc:show_doc' if not user: view_name = 'updoc:show_doc_alt' path_components = [(reverse(view_name, kwargs={'doc_id': doc_id, 'path': ''}), _('root'))] components = path.split('/') for index_, comp in enumerate(components): p = '/'.join(components[0:index_ + 1]) path_components.append((reverse(view_name, kwargs={'doc_id': doc_id, 'path': p}), comp)) template_values = {'doc': doc, 'editable': editable, 'title': str(doc), 'path': path, 'paths': path_components, 'keywords': ' '.join([keyword.value for keyword in doc.keywords.all()]), 'doc_id': doc_id, } try: with open(full_path) as fd: content = fd.read() template_values['content'] = mark_safe(markdown.markdown(content)) return TemplateResponse(request, 'updoc/markdown.html', template_values) except UnicodeDecodeError: pass return send_file_replace_url(request, full_path, allow_replace=True)
def my_docs(request): if request.user.is_authenticated: set_websocket_topics(request) user = request.user if request.user.is_authenticated else None if request.method == 'POST' and user and user.has_perm('updoc.add_uploaddoc'): form = UrlRewriteForm(request.POST) if form.is_valid(): RewrittenUrl(user=user, src=form.cleaned_data['src'], dst=form.cleaned_data['dst']).save() messages.info(request, _('URL %(src)s will be rewritten as %(dst)s') % form.cleaned_data) return HttpResponseRedirect(reverse('updoc:my_docs')) else: form = UrlRewriteForm() uploads = UploadDoc.query(request).order_by('-upload_time').select_related() rw_urls = RewrittenUrl.query(request).order_by('src') template_values = {'uploads': uploads, 'title': _('My documents'), 'rw_urls': rw_urls, 'rw_form': form, 'editable': True, 'has_search_results': False, } return TemplateResponse(request, 'updoc/my_docs.html', template_values)
def post(self, request): set_websocket_topics(request) form = TestForm(request.POST) if form.is_valid(): messages.info(request, "Plain form is valid") upload_form = UploadFileForm(request.POST, request.FILES) if upload_form.is_valid(): messages.info(request, "File upload form is valid") template_values = { "form": form, "title": "Hello, world!", "debug": settings.DEBUG, "upload_form": upload_form, "simple_upload_form": SimpleUploadFileForm(), } return self.render_to_response(template_values)
def show_search_results(request): """Index view, displaying and processing a form.""" if request.user.is_authenticated: set_websocket_topics(request) search = DocSearchForm(request.GET) pattern, doc_id = '', '' if search.is_valid(): pattern = search.cleaned_data['search'] doc_id = search.cleaned_data['doc_id'] or '' # ElasticSearch es_search = [] es_total = 0 if request.user.is_anonymous and not settings.PUBLIC_INDEX: messages.info(request, _('You must be logged to search across docs.')) else: try: es_search, es_total = search_archive(pattern, archive_id=doc_id) except ESError: messages.error(request, _('Unable to use indexed search.')) extra_obj = {} for obj in UploadDoc.objects.filter(id__in=set([x[0] for x in es_search])).only('id', 'name'): extra_obj[obj.id] = obj.name es_result = [] for es in es_search: if es[0] not in extra_obj: continue es_result.append((extra_obj[es[0]], es[0], es[1])) es_result.sort(key=lambda x: x[1]) es_data = {'results': es_result, 'total': es_total, } # classical search if not doc_id: docs = UploadDoc.objects.all() # list of UploadDoc.name, UploadDoc.id, path, UploadDoc.upload_time if len(pattern) > 3: docs = docs.filter(Q(name__icontains=pattern) | Q(keywords__value__icontains=pattern)) else: docs = docs.filter(Q(name__iexact=pattern) | Q(keywords__value__iexact=pattern)) docs = docs.distinct().select_related() else: docs = None template_values = {'uploads': docs, 'title': _('Search results'), 'rw_form': None, 'editable': False, 'es_data': es_data, 'doc_id': doc_id, } return TemplateResponse(request, 'updoc/my_docs.html', template_values)
def index(request): if request.user.is_authenticated: set_websocket_topics(request) if request.user.is_anonymous and not settings.PUBLIC_INDEX: messages.info(request, _('You must be logged to see documentations.')) keywords_with_counts, recent_uploads, recent_checked = [], [], [] else: keywords_with_counts = Keyword.objects.all().annotate(count=Count('uploaddoc')).filter(count__gt=0)\ .order_by('-count')[0:15] recent_uploads = UploadDoc.objects.order_by('-upload_time')[0:10] recent_checked = LastDocs.query(request).select_related().order_by('-last')[0:20] if request.user.is_anonymous and not settings.PUBLIC_BOOKMARKS: rss_roots = [] else: rss_roots = RssRoot.objects.all().order_by('name') template_values = {'recent_checked': recent_checked, 'title': _('Updoc'), 'rss_roots': rss_roots, 'recent_uploads': recent_uploads, 'keywords': keywords_with_counts, 'show_all_link': True, 'list_title': _('Recent uploads'), } return TemplateResponse(request, 'updoc/index.html', template_values)
def show_all_docs(request): if request.user.is_authenticated: set_websocket_topics(request) user = request.user if request.user.is_authenticated else None search = DocSearchForm(request.GET) if request.user.is_anonymous and not settings.PUBLIC_INDEX: messages.info(request, _('You must be logged to see documentations.')) keywords_with_counts, recent_uploads, recent_checked = [], [], [] else: recent_uploads = UploadDoc.objects.order_by('name') recent_checked = LastDocs.objects.filter(user=user).select_related().order_by('-last')[0:40] if request.user.is_anonymous and not settings.PUBLIC_BOOKMARKS: rss_roots = [] else: rss_roots = RssRoot.objects.all().order_by('name') template_values = {'recent_checked': recent_checked, 'title': _('Updoc'), 'rss_roots': rss_roots, 'recent_uploads': recent_uploads, 'search': search, 'keywords': [], 'show_all_link': False, 'list_title': _('All documents'), } return TemplateResponse(request, 'updoc/index.html', template_values)
def system_state(request): if not request.user or not request.user.is_superuser: raise Http404 components_values = [y.render(request) for y in system_checks] template_values = admin_context( { "components": components_values, "site_header": site.site_header, "site_title": site.site_title, "title": _("System state"), "has_permission": request.user.is_active and request.user.is_staff, } ) set_websocket_topics(request) # noinspection PyUnresolvedReferences return TemplateResponse( request, template="djangofloor/django/system_state.html", context=template_values, )
def upload(request): """Index view, displaying and processing a form.""" set_websocket_topics(request) if request.method == 'POST': form = MetadatadUploadForm(request.POST) if form.is_valid(): messages.info(request, _('File successfully uploaded')) obj = get_object_or_404(UploadDoc.query(request), id=form.cleaned_data['pk']) obj.name = form.cleaned_data['name'] for keyword in form.cleaned_data['keywords'].lower().split(): obj.keywords.add(Keyword.get(keyword)) obj.save() return HttpResponseRedirect(reverse('upload')) elif 'pk' in form.cleaned_data: obj = get_object_or_404(UploadDoc.query(request), id=form.cleaned_data['pk']) obj.delete() messages.error(request, _('Unable to upload this file')) else: messages.error(request, _('Unable to upload this file')) else: form = FileUploadForm() template_values = {'form': form, 'title': _('Upload a new file'), 'root_host': settings.SERVER_BASE_URL[:-1]} return TemplateResponse(request, 'updoc/upload.html', template_values)
def show_favorite(request, root_id=None): if request.user.is_authenticated: set_websocket_topics(request) if request.user.is_anonymous and not settings.PUBLIC_BOOKMARKS: roots = [] favorites = [] messages.info(request, _('You must be logged to see this page.')) current_root_name = _('Bookmarks') root_id = 0 else: roots = list(RssRoot.objects.all().order_by('name')) if root_id is None and roots: root_id = roots[0].id elif not root_id: root_id = 0 if root_id: current_root_name = get_object_or_404(RssRoot, id=root_id).name else: current_root_name = _('Bookmarks') favorites = RssItem.objects.filter(root__id=root_id).order_by('name') template_values = {'roots': roots, 'values': favorites, 'current_root_name': current_root_name, 'current_id': int(root_id)} return TemplateResponse(request, 'updoc/list_favorites.html', template_values)
def df_init_websocket(context, *topics): """Set the websocket URL with the access token. Allow to access the right topics.""" if not settings.WEBSOCKET_URL: return "" elif not context.get("df_has_ws_topics") and not topics: return "" elif not context.get("df_has_ws_topics") and context.get("df_http_request"): set_websocket_topics(context["df_http_request"], *topics) ws_token = context["df_window_key"] session_id = context["df_session_id"] user = context.get("user") # from django.contrib.auth context processors user_pk = None if user and user.is_authenticated: user_pk = user.pk try: backend_path = context["df_http_request"].session[BACKEND_SESSION_KEY] except KeyError: backend_path = None signed_token = sign_token( session_id, ws_token, user_pk=user_pk, backend_path=backend_path ) protocol = "wss" if settings.USE_SSL else "ws" site_name = "%s:%s" % (settings.SERVER_NAME, settings.SERVER_PORT) script = '$.df._wsConnect("%s://%s%s?token=%s");' % ( protocol, site_name, settings.WEBSOCKET_URL, signed_token, ) script += '$.df._wsToken="%s";' % signed_token script = "$(document).ready(function(){%s});" % script init_value = '<script type="application/javascript">%s</script>' % script init_value += ( '<script type="text/javascript" src="%s" charset="utf-8"></script>' % reverse("df:signals") ) return mark_safe(init_value)
def cache_nevercache(request): logger.warning("compute never_cache page") set_websocket_topics(request) return TemplateResponse( request, "easydemo/index.html", {"form": TestForm(), "title": "Never cache"} )