def get(self, request, *args, **kwargs) -> HttpResponse: """ :return: either a 302 redirect to the login page or a 200 with the document """ response = super().get(request, *args, **kwargs) document = response.context_data["document"] if document.members_only and not request.user.is_authenticated: return redirect("{}?next={}".format(settings.LOGIN_URL, request.path)) elif document.members_only and not request.member.has_active_membership( ): raise PermissionDenied lang = request.GET.get("language") try: if lang == "nl": file = document.file_nl elif lang == "en": file = document.file_en else: # Fall back on language detection file = document.file except ValueError: raise Http404("This document does not exist.") ext = os.path.splitext(file.path)[1] return sendfile( request, file.path, attachment=True, attachment_filename=slugify(document.name) + ext, )
def serve_local(request: HttpRequest, path_id: str) -> HttpResponse: local_path = get_local_file_path(path_id) if local_path is None: return HttpResponseNotFound('<p>File not found</p>') # Here we determine whether a browser should treat the file like # an attachment (and thus clicking a link to it should download) # or like a link (and thus clicking a link to it should display it # in a browser tab). This is controlled by the # Content-Disposition header; `django-sendfile2` sends the # attachment-style version of that header if and only if the # attachment argument is passed to it. For attachments, # django-sendfile2 sets the response['Content-disposition'] like # this: `attachment; filename="zulip.txt"; filename*=UTF-8''zulip.txt`. # The filename* parameter is omitted for ASCII filenames like this one. # # The "filename" field (used to name the file when downloaded) is # unreliable because it doesn't have a well-defined encoding; the # newer filename* field takes precedence, since it uses a # consistent format (urlquoted). For more details on filename* # and filename, see the below docs: # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition mimetype, encoding = guess_type(local_path) attachment = mimetype not in INLINE_MIME_TYPES response = sendfile(request, local_path, attachment=attachment, mimetype=mimetype, encoding=encoding) patch_cache_control(response, private=True, immutable=True) return response
def get_protected_file(request, uid, candidateId, filetype, fileid, token): try: uid = force_text(urlsafe_base64_decode(uid)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and downloadProtectedFile_token.check_token(user, token): fileType = force_text(urlsafe_base64_decode(filetype)) fileId = force_text(urlsafe_base64_decode(fileid)) candidateId = force_text(urlsafe_base64_decode(candidateId)) if fileType == str(FILE_TYPE_RESUME): resume = Resume.objects.get(id=fileId).resume filePath = resume.path if fileType == str(FILE_TYPE_COVER_LETTER): coverLetter = CoverLetter.objects.get(id=fileId).coverLetter filePath = coverLetter.path if fileType == str(FILE_TYPE_TRANSCRIPT): transcript = Candidate.objects.get(id=candidateId).transcript filePath = transcript.path if fileType == str(FILE_TYPE_OTHER): filePath = None return sendfile(request, filePath) else: return HttpResponse('Invalid permission token')
def protected_media(request, file_path): user = request.user if file_path.startswith("gmm/") and not user.is_authenticated: raise PermissionDenied() return sendfile(request, SENDFILE_ROOT + file_path)
def _download(request, obj, filename): """Download a photo. This function provides a layer of indirection for shared albums. """ photopath = _photo_path(obj, filename) photo = get_object_or_404(Photo.objects.filter(album=obj, file=photopath)) return sendfile(request, photo.file.path, attachment=True)
def get(self, request, **kwargs): if request.user.is_anonymous: raise Http404 path = kwargs['path'] path = os.path.join(settings.SENDFILE_ROOT, path) path = os.path.abspath(path) return sendfile(request, path)
def download(self, request, *args, **kwargs): eio = self.get_object() return sendfile( request, eio.inhoud.path, attachment=True, mimetype="application/octet-stream", )
def get(self, request, path): if request.user.is_authenticated and request.user.is_staff: fs_path = private_storage.path(path) logger.info( f"private file access: user_id={request.user.id} path={path}") return sendfile(request, fs_path, attachment=True) raise PermissionDenied
def file_download(request, pk): from main.models import File file = get_object_or_404(File, pk=pk, deleted=False) if not file.rights_can('DOWNLOAD', request.user): raise Http404 return sendfile(request, file.file.path, True)
def download_grades(request, grade_document_id): grade_document = get_object_or_404(GradeDocument, id=grade_document_id) if grade_document.course.semester.grade_documents_are_deleted: raise PermissionDenied return sendfile(request, grade_document.file.path, attachment=True, attachment_filename=grade_document.filename())
def get(self, request): filename = request.query_params.get("filename") # Si es el comprimido de grabaciones no se busca en S3 iszip = filename.find("/zip/", 0) if (config_constance.S3_STORAGE_ENABLED and iszip == -1): return self._get_s3_url(filename) return sendfile(request, settings.SENDFILE_ROOT + filename)
def render_to_response(self, *args, **kwargs): # if the pdf exists, use sendfile if self.object.pdf: return sendfile(self.request, self.object.pdf.path, attachment=True, attachment_filename=self.get_filename()) kwargs['invoice'] = self.object return super(InvoicePDFTemplateResponseMixin, self).render_to_response(*args, **kwargs)
def _album_download(request, album): """This function provides a layer of indirection for shared albums""" albumpath = os.path.join(album.photospath, album.dirname) zipfilename = os.path.join(gettempdir(), "{}.zip".format(album.dirname)) if not os.path.exists(zipfilename): with ZipFile(zipfilename, "w") as f: pictures = [os.path.join(albumpath, x) for x in os.listdir(albumpath)] for picture in pictures: f.write(picture, arcname=os.path.basename(picture)) return sendfile(request, zipfilename, attachment=True)
def download_student_object(request, klass, student_id: int, **kwargs): user = request.user if user.is_staff or user.pk == student_id: requested_entry = get_object_or_404( klass, student_id=student_id, **kwargs, ) return sendfile(request, requested_entry.image.path) else: raise Http404()
def download(self, request, *args, **kwargs): eio = self.get_object() if settings.CMIS_ENABLED: return FileResponse(eio.inhoud.file, as_attachment=True) else: return sendfile( request, eio.inhoud.path, attachment=True, mimetype="application/octet-stream", )
def get(self, request, *args, **kwargs) -> HttpResponse: response = super().get(request, *args, **kwargs) obj = response.context_data["object"] obj.download_count += 1 obj.save() ext = os.path.splitext(obj.file.path)[1] filename = f"{obj.course.name}-summary{obj.year}{ext}" return sendfile(request, obj.file.path, attachment=True, attachment_filename=filename)
def get(self, request, *args, **kwargs) -> HttpResponse: response = super().get(request, *args, **kwargs) exam = response.context_data["object"] exam.download_count += 1 exam.save() ext = os.path.splitext(exam.file.path)[1] filename = f"{exam.course.name}-exam{exam.year}{ext}" return sendfile(request, exam.file.path, attachment=True, attachment_filename=filename)
def signabledocument_download(request, pk): from main.models import SignableDocument file = get_object_or_404(SignableDocument, pk=pk, deleted=False) if not file.rights_can('SHOW', request.user): if not file.should_sign(request.user): if not file.signed(request.user): raise Http404 return sendfile(request, file.file.path, True)
def get(self, request, *args, **kwargs): form = ReportTypeForm(request.GET) form.is_valid() if form.errors: return HttpResponseBadRequest("Invalid document type") file_field = f"content_{form.cleaned_data['type']}" filename = getattr(self.get_object(), file_field).path sendfile_options = self.get_sendfile_opts() return sendfile(request, filename, **sendfile_options)
def render_to_response(self, context): content_type = TAR_TYPES[str(self.object.content_type)]["mime-type"] filename = "liberated_data.{ext}".format( ext=TAR_TYPES[str(self.object.content_type)]["ext"]) response = sendfile(request=self.request, filename=self.object.path, attachment=True, attachment_filename=filename, mimetype=content_type) del response["Content-Encoding"] return response
def get(self, request, *args, **kwargs): resource = self.get_object() # Does a valid associated agreement exist for this resource? associated_agreement = (Agreement.objects.filter( resource=resource).valid().order_by('-created').first()) if associated_agreement is None: raise Http404('Unable to find valid and unhidden agreement.') # Has the user signed that agreement? try: associated_agreement.signature_set.filter( signatory=self.request.user).get() except Signature.DoesNotExist: messages.error( self.request, f'You must sign this agreement before accessing files associated with {resource.name}.' ) # Attach some data to the session so that we can redirect back to this request later request.session['access_attempt'] = (resource.slug, self.kwargs['accesspath']) return redirect(associated_agreement) # Access is granted, is the access path a file or a directory? resource_scoped_path = os.path.join(resource.slug, self.kwargs['accesspath']) try: if '..' in resource_scoped_path: raise SuspiciousFileOperation() self.path = default_storage.path(resource_scoped_path) # pylint: disable=attribute-defined-outside-init if not os.path.exists(self.path): raise Http404('File or directory not found at access path.') if os.path.isfile(self.path): FileDownloadEvent.objects.get_or_create_if_no_duplicates_past_5_minutes( resource, self.kwargs['accesspath'], request.session.session_key) return sendfile(request, self.path) except SuspiciousFileOperation as suspicious_file_operation_error: raise PermissionDenied('SuspiciousFileOperation on file access.' ) from suspicious_file_operation_error # Redirect if the file listing doesn't end in a slash if self.kwargs['accesspath'] != '' and self.kwargs['accesspath'][ -1] != '/': return redirect( reverse_lazy( 'resources_access', args=[resource.slug, self.kwargs['accesspath'] + '/'])) # Render a file listing to the user. return super().get(request, *args, **kwargs)
def get(self, request, *args, **kwargs): self.object = self.get_object() lake_counties = self.object.lake.county_set.values_list('name', flat=True) response = sendfile(request, self.object.file.path) response['Content-Disposition'] = 'attachment; filename="{}"'.format( '+'.join([ '{}[{}]'.format( slugify(str(self.object.lake)), ','.join([slugify(c) for c in lake_counties]) ), slugify(self.object.name) ]) ) return response
def get(self, request, *args, **kwargs): """ TBD """ status = request.GET.get('status', None) render_format = kwargs.get('format', None) if status is None: raise Http404 cached_name = 'lakes-{}.json'.format(status) path = os.path.join(settings.MEDIA_ROOT, cached_name) if not os.path.exists(path): raise Http404 return sendfile(request, path, mimetype='application/json')
def private_media(request, request_path): """ Serve private media files :param request: the request :return: the media file """ # Get image information from signature # raises PermissionDenied if bad signature info = _get_signature_info(request) if not os.path.isfile(info["serve_path"] ) or not info["serve_path"].endswith(request_path): # 404 if the file does not exist raise Http404("Media not found.") # Serve the file return sendfile(request, info["serve_path"], attachment=info.get("attachment", False))
def preview(request, pk, lang=None): """ View that renders the newsletter as HTML :param request: the request object :param pk: the newsletter's primary key :param lang: the language of the render :return: HttpResponse 200 containing the newsletter HTML """ lang_code = request.LANGUAGE_CODE if lang is not None: try: get_language_info(lang) activate(lang) lang_code = lang except KeyError: # Language code not recognised by get_language_info pass # Send cached file, if it exists file_path = os.path.join(settings.MEDIA_ROOT, "newsletters", f"{pk}_{lang_code}.html") if os.path.isfile(file_path): return sendfile(request, file_path) newsletter = get_object_or_404(Newsletter, pk=pk) events = services.get_agenda(newsletter.date) if newsletter.date else None return render( request, "newsletters/email.html", { "newsletter": newsletter, "agenda_events": events, "main_partner": Partner.objects.filter(is_main_partner=True).first(), "local_partner": Partner.objects.filter(is_local_partner=True).first(), "lang_code": lang_code, }, )
def download(request, download_id): download = get_object_or_404(Download, pk=download_id) if download.is_public: return sendfile(request, download.file.path) return _auth_download(request, download)
def get(self, request, *args, **kwargs): filename = getattr(self.get_object(), self.file_field).path sendfile_options = self.get_sendfile_opts() return sendfile(request, filename, **sendfile_options)
def get(self, request, *args, **kwargs): self.object = self.get_object() return sendfile(request, self.object.file.path)
def direct_download(request, filename=None): if not filename: filename = request.GET.get("filename") return sendfile(request, filename)
def _auth_download(request, download): if not download.is_user_allowed(request.user): return HttpResponseForbidden('Sorry, you cannot access this file') return sendfile(request, download.file.path)