def share_link_thumbnail_get(request, token, size, path): """ handle thumbnail src from dir download link page return thumbnail file to web """ fileshare = FileShare.objects.get_valid_file_link_by_token(token) if not fileshare: return HttpResponse() repo_id = fileshare.repo_id repo = get_repo(repo_id) if not repo: return HttpResponse() if fileshare.path == '/': image_path = path else: image_path = posixpath.join(fileshare.path, path.lstrip('/')) obj_id = get_file_id_by_path(repo_id, image_path) thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id) if not os.path.exists(thumbnail_file) and \ allow_generate_thumbnail(request, repo_id, image_path): generate_thumbnail(request, repo_id, size, image_path) try: with open(thumbnail_file, 'rb') as f: thumbnail = f.read() return HttpResponse(content=thumbnail, mimetype='image/'+THUMBNAIL_EXTENSION) except IOError as e: logger.error(e) return HttpResponse()
def group_wiki_use_lib(request, group): if group.view_perm == "pub": raise Http404 if request.method != 'POST': raise Http404 repo_id = request.POST.get('dst_repo', '') username = request.user.username next = reverse('group_wiki', args=[group.id]) repo = seafile_api.get_repo(repo_id) if repo is None: messages.error(request, _('Failed to set wiki library.')) return HttpResponseRedirect(next) if check_folder_permission(request, repo_id, '/') != 'rw': messages.error(request, _('Permission denied.')) return HttpResponseRedirect(next) GroupWiki.objects.save_group_wiki(group_id=group.id, repo_id=repo_id) # create home page if not exist page_name = "home.md" if not seaserv.get_file_id_by_path(repo_id, "/" + page_name): if not seaserv.post_empty_file(repo_id, "/", page_name, username): messages.error(request, _('Failed to create home page. Please retry later')) return HttpResponseRedirect(next)
def generate_thumbnail(request, repo_id, size, path): """ generate and save thumbnail if not exist """ thumbnail_dir = os.path.join(THUMBNAIL_ROOT, str(size)) if not os.path.exists(thumbnail_dir): os.makedirs(thumbnail_dir) file_id = get_file_id_by_path(repo_id, path) thumbnail_file = os.path.join(thumbnail_dir, file_id) if os.path.exists(thumbnail_file): return True token = seafile_api.get_fileserver_access_token(repo_id, file_id, 'view', '', use_onetime = False) inner_path = gen_inner_file_get_url(token, os.path.basename(path)) try: image_file = urllib2.urlopen(inner_path) f = StringIO(image_file.read()) image = Image.open(f) if image.mode not in ["1", "L", "P", "RGB", "RGBA"]: image = image.convert("RGB") image.thumbnail((size, size), Image.ANTIALIAS) image.save(thumbnail_file, THUMBNAIL_EXTENSION) return True except Exception as e: logger.error(e) return False
def share_link_latest_entry(request, token, size, path): fileshare = FileShare.objects.get_valid_file_link_by_token(token) if not fileshare: return None repo_id = fileshare.repo_id repo = get_repo(repo_id) if not repo: return None if fileshare.path == '/': image_path = path else: image_path = posixpath.join(fileshare.path, path.lstrip('/')) obj_id = get_file_id_by_path(repo_id, image_path) if obj_id: try: thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id) last_modified_time = os.path.getmtime(thumbnail_file) # convert float to datatime obj return datetime.datetime.fromtimestamp(last_modified_time) except Exception as e: logger.error(e) # no thumbnail file exists return None else: return None
def share_link_thumbnail_get(request, token, size, path): """ handle thumbnail src from dir download link page return thumbnail file to web """ fileshare = FileShare.objects.get_valid_file_link_by_token(token) if not fileshare: return HttpResponse() repo_id = fileshare.repo_id repo = get_repo(repo_id) if not repo: return HttpResponse() if fileshare.path == '/': image_path = path else: image_path = posixpath.join(fileshare.path, path.lstrip('/')) obj_id = get_file_id_by_path(repo_id, image_path) thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id) if not os.path.exists(thumbnail_file) and \ allow_generate_thumbnail(request, repo_id, image_path): generate_thumbnail(request, repo_id, size, image_path) try: with open(thumbnail_file, 'rb') as f: thumbnail = f.read() return HttpResponse(content=thumbnail, mimetype='image/' + THUMBNAIL_EXTENSION) except IOError as e: logger.error(e) return HttpResponse()
def personal_wiki_page_new(request, page_name="home"): if request.method == 'POST': page_name = request.POST.get('page_name', '') if not page_name: return HttpResponseRedirect(request.META.get('HTTP_REFERER')) page_name = clean_page_name(page_name) try: repo = get_personal_wiki_repo(request.user.username) except WikiDoesNotExist: return render_error(request, _('Wiki is not found.')) filename = page_name + ".md" filepath = "/" + page_name + ".md" # check whether file exists if seaserv.get_file_id_by_path(repo.id, filepath): return render_error(request, _('Page "%s" already exists.') % filename) if not seaserv.post_empty_file(repo.id, "/", filename, request.user.username): return render_error(request, _('Failed to create wiki page. Please retry later.')) url = "%s?p=%s&from=personal_wiki_page_new" % ( reverse('file_edit', args=[repo.id]), urlquote(filepath.encode('utf-8'))) return HttpResponseRedirect(url)
def group_wiki_page_new(request, group, page_name="home"): if group.view_perm == "pub": raise Http404 if request.method == "POST": form = MessageForm(request.POST) page_name = request.POST.get("page_name", "") if not page_name: return HttpResponseRedirect(request.META.get("HTTP_REFERER")) page_name = clean_page_name(page_name) try: repo = get_group_wiki_repo(group, request.user.username) except WikiDoesNotExist: return render_error(request, _("Wiki is not found.")) filename = page_name + ".md" filepath = "/" + page_name + ".md" # check whether file exists if get_file_id_by_path(repo.id, filepath): return render_error(request, _('Page "%s" already exists.') % filename) if not post_empty_file(repo.id, "/", filename, request.user.username): return render_error(request, _("Failed to create wiki page. Please retry later.")) url = "%s?p=%s&from=wiki_page_new&gid=%s" % ( reverse("file_edit", args=[repo.id]), urllib2.quote(filepath.encode("utf-8")), group.id, ) return HttpResponseRedirect(url)
def personal_wiki_use_lib(request): if request.method != 'POST': raise Http404 repo_id = request.POST.get('dst_repo', '') username = request.user.username next = reverse('personal_wiki', args=[]) repo = seafile_api.get_repo(repo_id) if repo is None: messages.error(request, _('Failed to set wiki library.')) return HttpResponseRedirect(next) if check_folder_permission(request, repo_id, '/') != 'rw': messages.error(request, _('Permission denied.')) return HttpResponseRedirect(next) PersonalWiki.objects.save_personal_wiki(username=username, repo_id=repo_id) # create home page if not exist page_name = "home.md" if not seaserv.get_file_id_by_path(repo_id, "/" + page_name): if not seaserv.post_empty_file(repo_id, "/", page_name, username): messages.error(request, _('Failed to create home page. Please retry later')) return HttpResponseRedirect(next)
def personal_wiki_page_new(request, page_name="home"): if request.method == 'POST': page_name = request.POST.get('page_name', '') if not page_name: return HttpResponseRedirect(request.META.get('HTTP_REFERER')) page_name = clean_page_name(page_name) try: repo = get_personal_wiki_repo(request.user.username) except WikiDoesNotExist: return render_error(request, _('Wiki is not found.')) filename = page_name + ".md" filepath = "/" + page_name + ".md" # check whether file exists if seaserv.get_file_id_by_path(repo.id, filepath): return render_error(request, _('Page "%s" already exists.') % filename) if not seaserv.post_empty_file(repo.id, "/", filename, request.user.username): return render_error( request, _('Failed to create wiki page. Please retry later.')) url = "%s?p=%s&from=personal_wiki_page_new" % (reverse( 'file_edit', args=[repo.id]), urlquote(filepath.encode('utf-8'))) return HttpResponseRedirect(url)
def share_link_latest_entry(request, token, size, path): fileshare = FileShare.objects.get_valid_file_link_by_token(token) if not fileshare: return None repo_id = fileshare.repo_id repo = get_repo(repo_id) if not repo: return None image_path = get_real_path_by_fs_and_req_path(fileshare, path) obj_id = get_file_id_by_path(repo_id, image_path) if obj_id: try: thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id) last_modified_time = os.path.getmtime(thumbnail_file) # convert float to datatime obj return datetime.datetime.fromtimestamp(last_modified_time) except Exception as e: logger.error(e) # no thumbnail file exists return None else: return None
def group_wiki_page_new(request, group, page_name="home"): if group.view_perm == "pub": raise Http404 if request.method == 'POST': form = MessageForm(request.POST) page_name = request.POST.get('page_name', '') if not page_name: return HttpResponseRedirect(request.META.get('HTTP_REFERER')) page_name = clean_page_name(page_name) try: repo = get_group_wiki_repo(group, request.user.username) except WikiDoesNotExist: return render_error(request, _('Wiki is not found.')) filename = page_name + ".md" filepath = "/" + page_name + ".md" # check whether file exists if get_file_id_by_path(repo.id, filepath): return render_error(request, _('Page "%s" already exists.') % filename) if not post_empty_file(repo.id, "/", filename, request.user.username): return render_error(request, _('Failed to create wiki page. Please retry later.')) url = "%s?p=%s&from=wiki_page_new&gid=%s" % ( reverse('file_edit', args=[repo.id]), urllib2.quote(filepath.encode('utf-8')), group.id) return HttpResponseRedirect(url)
def thumbnail_create(request, repo_id): content_type = 'application/json; charset=utf-8' result = {} path = request.GET.get('path') size = request.GET.get('size', THUMBNAIL_DEFAULT_SIZE) obj_id = get_file_id_by_path(repo_id, path) raw_path, inner_path, user_perm = get_file_view_path_and_perm( request, repo_id, obj_id, path) if user_perm is None: err_msg = _(u"Permission denied.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) repo = get_repo(repo_id) if repo.encrypted: err_msg = _( u"Image thumbnail is not supported in encrypted libraries.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) if not ENABLE_THUMBNAIL: err_msg = _(u"Thumbnail function is not enabled.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) open_file = urllib2.urlopen(raw_path) file_size = int(open_file.info()['Content-Length']) if file_size > THUMBNAIL_IMAGE_SIZE_LIMIT * 1024**2: # if file is bigger than 30MB err_msg = _(u"Image file is too large.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=520, content_type=content_type) thumbnail_dir = os.path.join(THUMBNAIL_ROOT, size) if not os.path.exists(thumbnail_dir): os.makedirs(thumbnail_dir) thumbnail_file = os.path.join(thumbnail_dir, obj_id) if not os.path.exists(thumbnail_file): try: f = StringIO(open_file.read()) image = Image.open(f) image.thumbnail((int(size), int(size)), Image.ANTIALIAS) image.save(thumbnail_file, THUMBNAIL_EXTENSION) except Exception as e: logger.error(e) return HttpResponse(json.dumps({'success': False}), status=500, content_type=content_type) result['thumbnail_src'] = get_thumbnail_src(repo_id, obj_id, size) return HttpResponse(json.dumps(result), content_type=content_type)
def share_link_thumbnail_get(request, token, size, path): """ handle thumbnail src from dir download link page return thumbnail file to web """ try: size = int(size) except ValueError as e: logger.error(e) return HttpResponse() fileshare = FileShare.objects.get_valid_file_link_by_token(token) if not fileshare: return HttpResponse() password_check_passed, err_msg = check_share_link_common( request, fileshare) if not password_check_passed: d = { 'token': token, 'view_name': 'view_shared_dir', 'err_msg': err_msg } return render_to_response('share_access_validation.html', d, context_instance=RequestContext(request)) image_path = get_real_path_by_fs_and_req_path(fileshare, path) repo_id = fileshare.repo_id repo = get_repo(repo_id) obj_id = get_file_id_by_path(repo_id, image_path) # check if file exist if not repo or not obj_id: return HttpResponse() # check if is allowed if repo.encrypted or not ENABLE_THUMBNAIL: return HttpResponse() success = True thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id) if not os.path.exists(thumbnail_file): success, status_code = generate_thumbnail(request, repo_id, size, image_path) if success: try: with open(thumbnail_file, 'rb') as f: thumbnail = f.read() return HttpResponse(content=thumbnail, content_type='image/' + THUMBNAIL_EXTENSION) except IOError as e: logger.error(e) return HttpResponse() else: return HttpResponse()
def generate_thumbnail(request, repo_id, size, path): """ generate and save thumbnail if not exist before generate thumbnail, you should check: 1. if repo exist: should exist; 2. if repo is encrypted: not encrypted; 3. if ENABLE_THUMBNAIL: enabled; """ try: size = int(size) except ValueError as e: logger.error(e) return (False, 400) thumbnail_dir = os.path.join(THUMBNAIL_ROOT, str(size)) if not os.path.exists(thumbnail_dir): os.makedirs(thumbnail_dir) file_id = get_file_id_by_path(repo_id, path) if not file_id: return (False, 400) thumbnail_file = os.path.join(thumbnail_dir, file_id) if os.path.exists(thumbnail_file): return (True, 200) repo = get_repo(repo_id) file_size = get_file_size(repo.store_id, repo.version, file_id) if file_size > THUMBNAIL_IMAGE_SIZE_LIMIT * 1024**2: return (False, 403) token = seafile_api.get_fileserver_access_token(repo_id, file_id, 'view', '', use_onetime = True) inner_path = gen_inner_file_get_url(token, os.path.basename(path)) try: image_file = urllib2.urlopen(inner_path) f = StringIO(image_file.read()) image = Image.open(f) # check image memory cost size limit # use RGBA as default mode(4x8-bit pixels, true colour with transparency mask) # every pixel will cost 4 byte in RGBA mode width, height = image.size image_memory_cost = width * height * 4 / 1024 / 1024 if image_memory_cost > THUMBNAIL_IMAGE_ORIGINAL_SIZE_LIMIT: return (False, 403) if image.mode not in ["1", "L", "P", "RGB", "RGBA"]: image = image.convert("RGB") image = get_rotated_image(image) image.thumbnail((size, size), Image.ANTIALIAS) image.save(thumbnail_file, THUMBNAIL_EXTENSION) return (True, 200) except Exception as e: logger.error(e) return (False, 500)
def get_file_url(repo_id, path, filename): obj_id = get_file_id_by_path(repo_id, path) if not obj_id: raise WikiPageMissing access_token = seafserv_rpc.web_get_access_token(repo_id, obj_id, 'view', '') url = gen_file_get_url(access_token, filename) return url, obj_id
def generate_thumbnail(request, repo_id, size, path): """ generate and save thumbnail if not exist before generate thumbnail, you should check: 1. if repo exist: should exist; 2. if repo is encrypted: not encrypted; 3. if ENABLE_THUMBNAIL: enabled; """ try: size = int(size) except ValueError as e: logger.error(e) return (False, 400) thumbnail_dir = os.path.join(THUMBNAIL_ROOT, str(size)) if not os.path.exists(thumbnail_dir): os.makedirs(thumbnail_dir) file_id = get_file_id_by_path(repo_id, path) if not file_id: return (False, 400) thumbnail_file = os.path.join(thumbnail_dir, file_id) if os.path.exists(thumbnail_file): return (True, 200) repo = get_repo(repo_id) file_size = get_file_size(repo.store_id, repo.version, file_id) filetype, fileext = get_file_type_and_ext(os.path.basename(path)) if filetype == VIDEO: # video thumbnails if ENABLE_VIDEO_THUMBNAIL: return create_video_thumbnails(repo, file_id, path, size, thumbnail_file, file_size) else: return (False, 400) # image thumbnails if file_size > THUMBNAIL_IMAGE_SIZE_LIMIT * 1024**2: return (False, 403) token = seafile_api.get_fileserver_access_token(repo_id, file_id, 'view', '', use_onetime=True) inner_path = gen_inner_file_get_url(token, os.path.basename(path)) try: image_file = urllib2.urlopen(inner_path) f = StringIO(image_file.read()) return _create_thumbnail_common(f, thumbnail_file, size) except Exception as e: logger.error(e) return (False, 500)
def generate_thumbnail(request, repo_id, size, path): """ generate and save thumbnail if not exist before generate thumbnail, you should check: 1. if repo exist: should exist; 2. if repo is encrypted: not encrypted; 3. if ENABLE_THUMBNAIL: enabled; """ try: size = int(size) except ValueError as e: logger.error(e) return (False, 400) thumbnail_dir = os.path.join(THUMBNAIL_ROOT, str(size)) if not os.path.exists(thumbnail_dir): os.makedirs(thumbnail_dir) file_id = get_file_id_by_path(repo_id, path) if not file_id: return (False, 400) thumbnail_file = os.path.join(thumbnail_dir, file_id) if os.path.exists(thumbnail_file): return (True, 200) repo = get_repo(repo_id) file_size = get_file_size(repo.store_id, repo.version, file_id) if file_size > THUMBNAIL_IMAGE_SIZE_LIMIT * 1024**2: return (False, 403) token = seafile_api.get_fileserver_access_token(repo_id, file_id, 'view', '', use_onetime = True) inner_path = gen_inner_file_get_url(token, os.path.basename(path)) try: image_file = urllib2.urlopen(inner_path) f = StringIO(image_file.read()) image = Image.open(f) # check image memory cost size limit # use RGBA as default mode(4x8-bit pixels, true colour with transparency mask) # every pixel will cost 4 byte in RGBA mode width, height = image.size image_memory_cost = width * height * 4 / 1024 / 1024 if image_memory_cost > THUMBNAIL_IMAGE_ORIGINAL_SIZE_LIMIT: return (False, 403) if image.mode not in ["1", "L", "P", "RGB", "RGBA"]: image = image.convert("RGB") image.thumbnail((size, size), Image.ANTIALIAS) image.save(thumbnail_file, THUMBNAIL_EXTENSION) return (True, 200) except Exception as e: logger.error(e) return (False, 500)
def share_link_thumbnail_get(request, token, size, path): """ handle thumbnail src from dir download link page return thumbnail file to web """ try: size = int(size) except ValueError as e: logger.error(e) return HttpResponse() fileshare = FileShare.objects.get_valid_file_link_by_token(token) if not fileshare: return HttpResponse() password_check_passed, err_msg = check_share_link_common(request, fileshare) if not password_check_passed: d = {'token': token, 'view_name': 'view_shared_dir', 'err_msg': err_msg} return render_to_response('share_access_validation.html', d, context_instance=RequestContext(request)) if fileshare.path == '/': image_path = path else: image_path = posixpath.join(fileshare.path, path.lstrip('/')) repo_id = fileshare.repo_id repo = get_repo(repo_id) obj_id = get_file_id_by_path(repo_id, image_path) # check if file exist if not repo or not obj_id: return HttpResponse() # check if is allowed if repo.encrypted or not ENABLE_THUMBNAIL: return HttpResponse() success = True thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id) if not os.path.exists(thumbnail_file): success, status_code = generate_thumbnail(request, repo_id, size, image_path) if success: try: with open(thumbnail_file, 'rb') as f: thumbnail = f.read() return HttpResponse(content=thumbnail, content_type='image/' + THUMBNAIL_EXTENSION) except IOError as e: logger.error(e) return HttpResponse() else: return HttpResponse()
def repl(matchobj): if matchobj.group(2): # return origin string in backquotes return matchobj.group(2) page_alias = page_name = matchobj.group(1).strip() if len(page_name.split('|')) > 1: page_alias = page_name.split('|')[0] page_name = page_name.split('|')[1] filetype, fileext = get_file_type_and_ext(page_name) if fileext == '': # convert page_name that extension is missing to a markdown page try: dirent = get_wiki_dirent(repo_id, page_name) a_tag = "<a href='%s'>%s</a>" return a_tag % (smart_str(url_prefix + normalize_page_name(page_name) + '/'), page_alias) except (WikiDoesNotExist, WikiPageMissing): a_tag = '''<a class="wiki-page-missing" href='%s'>%s</a>''' return a_tag % (smart_str(url_prefix + page_name.replace('/', '-') + '/'), page_alias) elif filetype == IMAGE: # load image to wiki page path = "/" + page_name filename = os.path.basename(path) obj_id = seaserv.get_file_id_by_path(repo_id, path) if not obj_id: # Replace '/' in page_name to '-', since wiki name can not # contain '/'. return '''<a class="wiki-page-missing" href='%s'>%s</a>''' % \ (url_prefix + '/' + page_name.replace('/', '-'), page_name) token = seaserv.web_get_access_token(repo_id, obj_id, 'view', username) ret = '<img class="wiki-image" src="%s" alt="%s" />' % ( gen_file_get_url(token, filename), filename) return smart_str(ret) else: from seahub.base.templatetags.seahub_tags import file_icon_filter from django.conf import settings # convert other types of filelinks to clickable links path = "/" + page_name icon = file_icon_filter(page_name) s = reverse('repo_view_file', args=[repo_id]) + \ '?p=' + urlquote(path) a_tag = '''<img src="%simg/file/%s" alt="%s" class="file-icon vam" /> <a href='%s' target='_blank' class="vam">%s</a>''' ret = a_tag % (settings.MEDIA_URL, icon, icon, smart_str(s), page_name) return smart_str(ret)
def repl(matchobj): if matchobj.group(2): # return origin string in backquotes return matchobj.group(2) linkname = matchobj.group(1).strip() filetype, fileext = get_file_type_and_ext(linkname) filetype = filetype.lower() if fileext == '': # convert linkname that extension is missing to a markdown page filename = linkname + ".md" path = "/" + filename if get_file_id_by_path(repo_id, path): a_tag = "<a href='%s'>%s</a>" return a_tag % (reverse('group_wiki', args=[group.id, linkname]), linkname) else: a_tag = '''<a class="wiki-page-missing" href='%s'>%s</a>''' return a_tag % (reverse('group_wiki', args=[group.id, linkname.replace('/', '-')]), linkname) elif filetype == 'image': # load image to wiki page path = "/" + linkname filename = os.path.basename(path) obj_id = get_file_id_by_path(repo_id, path) if not obj_id: # Replace '/' in linkname to '-', since wiki name can not # contain '/'. return '''<a class="wiki-page-missing" href='%s'>%s</a>''' % \ (reverse('group_wiki', args=[group.id, linkname.replace('/', '-')]), linkname) token = web_get_access_token(repo_id, obj_id, 'view', username) return '<img src="%s" alt="%s" />' % (gen_file_get_url(token, filename), filename) else: from base.templatetags.seahub_tags import file_icon_filter # convert other types of filelinks to clickable links path = "/" + linkname icon = file_icon_filter(linkname) s = reverse('repo_view_file', args=[repo_id]) + '?p=' + path a_tag = '''<img src="%simg/file/%s" alt="%s" class="vam" /> <a href='%s' target='_blank' class="vam">%s</a>''' return a_tag % (MEDIA_URL, icon, icon, s, linkname)
def latest_entry(request, repo_id, size, path): obj_id = get_file_id_by_path(repo_id, path) if obj_id: try: thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id) last_modified_time = os.path.getmtime(thumbnail_file) # convert float to datatime obj return datetime.datetime.fromtimestamp(last_modified_time) except Exception as e: # no thumbnail file exists logger.error(e) return None else: return None
def share_link_thumbnail_get(request, token, size, path): """ handle thumbnail src from dir download link page return thumbnail file to web """ try: size = int(size) except ValueError as e: logger.error(e) return HttpResponse() fileshare = FileShare.objects.get_valid_file_link_by_token(token) if not fileshare: return HttpResponse() if fileshare.path == '/': image_path = path else: image_path = posixpath.join(fileshare.path, path.lstrip('/')) repo_id = fileshare.repo_id repo = get_repo(repo_id) obj_id = get_file_id_by_path(repo_id, image_path) # check if file exist if not repo or not obj_id: return HttpResponse() # check if is allowed if repo.encrypted or not ENABLE_THUMBNAIL: return HttpResponse() success = True thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id) if not os.path.exists(thumbnail_file): success, status_code = generate_thumbnail(request, repo_id, size, image_path) if success: try: with open(thumbnail_file, 'rb') as f: thumbnail = f.read() return HttpResponse(content=thumbnail, content_type='image/' + THUMBNAIL_EXTENSION) except IOError as e: logger.error(e) return HttpResponse() else: return HttpResponse()
def post(self, request, slug): """ Add a page in a wiki """ try: wiki = Wiki.objects.get(slug=slug) except Wiki.DoesNotExist: error_msg = "Wiki not found." return api_error(status.HTTP_404_NOT_FOUND, error_msg) # perm check username = request.user.username if wiki.username != username: error_msg = _('Permission denied.') return api_error(status.HTTP_403_FORBIDDEN, error_msg) page_name = request.POST.get('name', '') if not page_name: error_msg = 'name invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) page_name = clean_page_name(page_name) filename = page_name + ".md" filepath = "/" + page_name + ".md" try: repo = seafile_api.get_repo(wiki.repo_id) if not repo: error_msg = "Wiki library not found." return api_error(status.HTTP_404_NOT_FOUND, error_msg) except SearpcError: error_msg = _("Internal Server Error") return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # check whether file exists if get_file_id_by_path(repo.id, filepath): error_msg = _('Page "%s" already exists.') % filename return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: seafile_api.post_empty_file(repo.id, '/', filename, request.user.username) except SearpcError as e: logger.error(e) error_msg = _('Internal Server Error') return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) wiki_page_object = get_wiki_page_object(wiki, page_name) return Response(wiki_page_object)
def repl(matchobj): if matchobj.group(2): # return origin string in backquotes return matchobj.group(2) page_alias = page_name = matchobj.group(1).strip() if len(page_name.split("|")) > 1: page_alias = page_name.split("|")[0] page_name = page_name.split("|")[1] filetype, fileext = get_file_type_and_ext(page_name) if fileext == "": # convert page_name that extension is missing to a markdown page try: dirent = get_wiki_dirent(repo_id, page_name) a_tag = "<a href='%s'>%s</a>" return a_tag % (smart_str(url_prefix + normalize_page_name(page_name) + "/"), page_alias) except (WikiDoesNotExist, WikiPageMissing): a_tag = """<a class="wiki-page-missing" href='%s'>%s</a>""" return a_tag % (smart_str(url_prefix + page_name.replace("/", "-") + "/"), page_alias) elif filetype == IMAGE: # load image to wiki page path = "/" + page_name filename = os.path.basename(path) obj_id = seaserv.get_file_id_by_path(repo_id, path) if not obj_id: # Replace '/' in page_name to '-', since wiki name can not # contain '/'. return """<a class="wiki-page-missing" href='%s'>%s</a>""" % ( url_prefix + "/" + page_name.replace("/", "-"), page_name, ) token = seaserv.web_get_access_token(repo_id, obj_id, "view", username) ret = '<img class="wiki-image" src="%s" alt="%s" />' % (gen_file_get_url(token, filename), filename) return smart_str(ret) else: from seahub.base.templatetags.seahub_tags import file_icon_filter from django.conf import settings # convert other types of filelinks to clickable links path = "/" + page_name icon = file_icon_filter(page_name) s = reverse("repo_view_file", args=[repo_id]) + "?p=" + urlquote(path) a_tag = ( """<img src="%simg/file/%s" alt="%s" class="vam" /> <a href='%s' target='_blank' class="vam">%s</a>""" ) ret = a_tag % (settings.MEDIA_URL, icon, icon, smart_str(s), page_name) return smart_str(ret)
def allow_generate_thumbnail(request, repo_id, path): """check if thumbnail is allowed """ # get file type obj_name = os.path.basename(path) file_type, file_ext = get_file_type_and_ext(obj_name) # get file size file_id = get_file_id_by_path(repo_id, path) if not file_id: return False repo = get_repo(repo_id) file_size = get_file_size(repo.store_id, repo.version, file_id) if repo.encrypted or file_type != IMAGE or not ENABLE_THUMBNAIL: return False # check image compressed size limit if file_size < THUMBNAIL_IMAGE_COMPRESSED_SIZE_LIMIT * 1024**2: return True # get image memory cost token = seafile_api.get_fileserver_access_token(repo_id, file_id, 'view', '', use_onetime=True) inner_path = gen_inner_file_get_url(token, obj_name) try: image_file = urllib2.urlopen(inner_path) f = StringIO(image_file.read()) image = Image.open(f) width, height = image.size # check image memory cost size limit # use RGBA as default mode(4x8-bit pixels, true colour with transparency mask) # every pixel will cost 4 byte in RGBA mode image_memory_cost = width * height * 4 / 1024 / 1024 if image_memory_cost < THUMBNAIL_IMAGE_ORIGINAL_SIZE_LIMIT: return True except Exception as e: logger.error(e) return False
def repl(matchobj): if matchobj.group(2): # return origin string in backquotes return matchobj.group(2) page_alias = page_name = matchobj.group(1).strip() if len(page_name.split('|')) > 1: page_alias = page_name.split('|')[0] page_name = page_name.split('|')[1] filetype, fileext = get_file_type_and_ext(page_name) if fileext == '': # convert page_name that extension is missing to a markdown page try: dirent = get_wiki_dirent(repo_id, page_name) a_tag = '''<a href="%s">%s</a>''' return a_tag % (smart_str(url_prefix + normalize_page_name(page_name) + '/'), page_alias) except (WikiDoesNotExist, WikiPageMissing): a_tag = '''<a href="%s" class="wiki-page-missing">%s</a>''' return a_tag % (smart_str(url_prefix + normalize_page_name(page_name) + '/'), page_alias) elif filetype == IMAGE: # load image to wiki page path = "/" + page_name filename = os.path.basename(path) obj_id = seaserv.get_file_id_by_path(repo_id, path) if not obj_id: # Replace '/' in page_name to '-', since wiki name can not # contain '/'. return '''<a href="%s" class="wiki-page-missing">%s</a>''' % \ (url_prefix + '/' + page_name.replace('/', '-'), page_name) token = seafile_api.get_fileserver_access_token(repo_id, obj_id, 'view', username) ret = '<img src="%s" alt="%s" class="wiki-image" />' % (gen_file_get_url(token, filename), filename) return smart_str(ret) else: from seahub.base.templatetags.seahub_tags import file_icon_filter from django.conf import settings # convert other types of filelinks to clickable links path = "/" + page_name icon = file_icon_filter(page_name) s = reverse('view_lib_file', args=[repo_id, urlquote(path)]) a_tag = '''<img src="%simg/file/%s" alt="%s" class="file-icon vam" /> <a href="%s" class="vam" target="_blank">%s</a>''' ret = a_tag % (settings.MEDIA_URL, icon, icon, smart_str(s), page_name) return smart_str(ret)
def thumbnail_create(request, repo_id): content_type = 'application/json; charset=utf-8' result = {} path = request.GET.get('path') size = request.GET.get('size', THUMBNAIL_DEFAULT_SIZE) obj_id = get_file_id_by_path(repo_id, path) raw_path, inner_path, user_perm = get_file_view_path_and_perm(request, repo_id, obj_id, path) if user_perm is None: err_msg = _(u"Permission denied.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) repo = get_repo(repo_id) if repo.encrypted: err_msg = _(u"Image thumbnail is not supported in encrypted libraries.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) if not ENABLE_THUMBNAIL: err_msg = _(u"Thumbnail function is not enabled.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) thumbnail_dir = os.path.join(THUMBNAIL_ROOT, size) if not os.path.exists(thumbnail_dir): os.makedirs(thumbnail_dir) thumbnail_file = os.path.join(thumbnail_dir, obj_id) if not os.path.exists(thumbnail_file): try: f = StringIO(urllib2.urlopen(raw_path).read()) image = Image.open(f) image.thumbnail((int(size), int(size)), Image.ANTIALIAS) image.save(thumbnail_file, THUMBNAIL_EXTENSION) except Exception as e: logger.error(e) return HttpResponse(json.dumps({'success': False}), status=500, content_type=content_type) result['thumbnail_src'] = get_thumbnail_src(repo_id, obj_id, size) return HttpResponse(json.dumps(result), content_type=content_type)
def allow_generate_thumbnail(request, repo_id, path): """check if thumbnail is allowed """ # get file type obj_name = os.path.basename(path) file_type, file_ext = get_file_type_and_ext(obj_name) # get file size file_id = get_file_id_by_path(repo_id, path) if not file_id: return False repo = get_repo(repo_id) file_size = get_file_size(repo.store_id, repo.version, file_id) if repo.encrypted or file_type != IMAGE or not ENABLE_THUMBNAIL: return False # check image compressed size limit if file_size < THUMBNAIL_IMAGE_COMPRESSED_SIZE_LIMIT * 1024**2: return True # get image memory cost token = seafile_api.get_fileserver_access_token(repo_id, file_id, 'view', '', use_onetime = True) inner_path = gen_inner_file_get_url(token, obj_name) try: image_file = urllib2.urlopen(inner_path) f = StringIO(image_file.read()) image = Image.open(f) width, height = image.size # check image memory cost size limit # use RGBA as default mode(4x8-bit pixels, true colour with transparency mask) # every pixel will cost 4 byte in RGBA mode image_memory_cost = width * height * 4 / 1024 / 1024 if image_memory_cost < THUMBNAIL_IMAGE_ORIGINAL_SIZE_LIMIT: return True except Exception as e: logger.error(e) return False
def repl(matchobj): if matchobj.group(2): # return origin string in backquotes return matchobj.group(2) link_alias = link_name = matchobj.group(1).strip() if len(link_name.split('|')) > 1: link_alias = link_name.split('|')[0] link_name = link_name.split('|')[1] filetype, fileext = get_file_type_and_ext(link_name) if fileext == '': # convert link_name that extension is missing to a markdown page try: dirent = get_wiki_dirent(repo_id, link_name) path = "/" + dirent.obj_name href = reverse('repo_view_file', args=[repo_id]) + '?p=' + urlquote(path) a_tag = '''<a href="%s">%s</a>''' return a_tag % (href, link_alias) except (WikiDoesNotExist, WikiPageMissing): a_tag = '''<p class="wiki-page-missing">%s</p>''' return a_tag % (link_alias) elif filetype == IMAGE: # load image to current page path = "/" + link_name filename = os.path.basename(path) obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return '''<p class="wiki-page-missing">%s</p>''' % link_name token = web_get_access_token(repo_id, obj_id, 'view', username) return '<img class="wiki-image" src="%s" alt="%s" />' % ( gen_file_get_url(token, filename), filename) else: from seahub.base.templatetags.seahub_tags import file_icon_filter # convert other types of filelinks to clickable links path = "/" + link_name icon = file_icon_filter(link_name) s = reverse('repo_view_file', args=[repo_id ]) + '?p=' + urlquote(path) a_tag = '''<img src="%simg/file/%s" alt="%s" class="vam" /> <a href="%s" target="_blank" class="vam">%s</a>''' return a_tag % (MEDIA_URL, icon, icon, s, link_name)
def repl(matchobj): if matchobj.group(2): # return origin string in backquotes return matchobj.group(2) link_alias = link_name = matchobj.group(1).strip() if len(link_name.split("|")) > 1: link_alias = link_name.split("|")[0] link_name = link_name.split("|")[1] filetype, fileext = get_file_type_and_ext(link_name) if fileext == "": # convert link_name that extension is missing to a markdown page try: dirent = get_wiki_dirent(repo_id, link_name) path = "/" + dirent.obj_name href = reverse("repo_view_file", args=[repo_id]) + "?p=" + urlquote(path) a_tag = """<a href="%s">%s</a>""" return a_tag % (href, link_alias) except (WikiDoesNotExist, WikiPageMissing): a_tag = """<p class="wiki-page-missing">%s</p>""" return a_tag % (link_alias) elif filetype == IMAGE: # load image to current page path = "/" + link_name filename = os.path.basename(path) obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return """<p class="wiki-page-missing">%s</p>""" % link_name token = web_get_access_token(repo_id, obj_id, "view", username) return '<img class="wiki-image" src="%s" alt="%s" />' % (gen_file_get_url(token, filename), filename) else: from seahub.base.templatetags.seahub_tags import file_icon_filter # convert other types of filelinks to clickable links path = "/" + link_name icon = file_icon_filter(link_name) s = reverse("repo_view_file", args=[repo_id]) + "?p=" + urlquote(path) a_tag = ( """<img src="%simg/file/%s" alt="%s" class="vam" /> <a href="%s" target="_blank" class="vam">%s</a>""" ) return a_tag % (MEDIA_URL, icon, icon, s, link_name)
def generate_thumbnail(request, repo_id, size, path): """ generate and save thumbnail if not exist """ try: size = int(size) except ValueError as e: logger.error(e) return False thumbnail_dir = os.path.join(THUMBNAIL_ROOT, str(size)) if not os.path.exists(thumbnail_dir): os.makedirs(thumbnail_dir) file_id = get_file_id_by_path(repo_id, path) if not file_id: return False thumbnail_file = os.path.join(thumbnail_dir, file_id) if os.path.exists(thumbnail_file): return True token = seafile_api.get_fileserver_access_token(repo_id, file_id, 'view', '', use_onetime=True) inner_path = gen_inner_file_get_url(token, os.path.basename(path)) try: image_file = urllib2.urlopen(inner_path) f = StringIO(image_file.read()) image = Image.open(f) if image.mode not in ["1", "L", "P", "RGB", "RGBA"]: image = image.convert("RGB") image.thumbnail((size, size), Image.ANTIALIAS) image.save(thumbnail_file, THUMBNAIL_EXTENSION) return True except Exception as e: logger.error(e) return False
def personal_wiki_use_lib(request): if request.method != 'POST': raise Http404 repo_id = request.POST.get('dst_repo', '') username = request.user.username next = reverse('personal_wiki', args=[]) repo = seafile_api.get_repo(repo_id) if repo is None: messages.error(request, _('Failed to set wiki library.')) return HttpResponseRedirect(next) PersonalWiki.objects.save_personal_wiki(username=username, repo_id=repo_id) # create home page if not exist page_name = "home.md" if not seaserv.get_file_id_by_path(repo_id, "/" + page_name): if not seaserv.post_empty_file(repo_id, "/", page_name, username): messages.error(request, _('Failed to create home page. Please retry later')) return HttpResponseRedirect(next)
def personal_wiki_use_lib(request): if request.method != "POST": raise Http404 repo_id = request.POST.get("dst_repo", "") username = request.user.username next = reverse("personal_wiki", args=[]) repo = seafile_api.get_repo(repo_id) if repo is None: messages.error(request, _("Failed to set wiki library.")) return HttpResponseRedirect(next) PersonalWiki.objects.save_personal_wiki(username=username, repo_id=repo_id) # create home page if not exist page_name = "home.md" if not seaserv.get_file_id_by_path(repo_id, "/" + page_name): if not seaserv.post_empty_file(repo_id, "/", page_name, username): messages.error(request, _("Failed to create home page. Please retry later")) return HttpResponseRedirect(next)
def thumbnail_get(request, repo_id, size, path): """ handle thumbnail src from repo file list return thumbnail file to web """ repo = get_repo(repo_id) obj_id = get_file_id_by_path(repo_id, path) # check if file exist if not repo or not obj_id: return HttpResponse() # check if is allowed if repo.encrypted or not ENABLE_THUMBNAIL or \ check_folder_permission(request, repo_id, path) is None: return HttpResponse() try: size = int(size) except ValueError as e: logger.error(e) return HttpResponse() success = True thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id) if not os.path.exists(thumbnail_file): success, status_code = generate_thumbnail(request, repo_id, size, path) if success: try: with open(thumbnail_file, 'rb') as f: thumbnail = f.read() return HttpResponse(content=thumbnail, content_type='image/' + THUMBNAIL_EXTENSION) except IOError as e: logger.error(e) return HttpResponse() else: return HttpResponse()
def thumbnail_get(request, repo_id, size, path): """ handle thumbnail src from repo file list return thumbnail file to web """ repo = get_repo(repo_id) obj_id = get_file_id_by_path(repo_id, path) # check if file exist if not repo or not obj_id: return HttpResponse() # check if is allowed if repo.encrypted or not ENABLE_THUMBNAIL or \ check_folder_permission(request, repo_id, path) is None: return HttpResponse() try: size = int(size) except ValueError as e: logger.error(e) return HttpResponse() success = True thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id) if not os.path.exists(thumbnail_file): success, status_code = generate_thumbnail(request, repo_id, size, path) if success: try: with open(thumbnail_file, 'rb') as f: thumbnail = f.read() return HttpResponse(content=thumbnail, content_type='image/' + THUMBNAIL_EXTENSION) except IOError as e: logger.error(e) return HttpResponse(status=500) else: return HttpResponse(status=status_code)
def thumbnail_get(request, repo_id, size, path): """ handle thumbnail src from repo file list return thumbnail file to web """ if check_folder_permission(request, repo_id, path) is None: return HttpResponse() obj_id = get_file_id_by_path(repo_id, path) thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id) if not os.path.exists(thumbnail_file) and \ allow_generate_thumbnail(request, repo_id, path): generate_thumbnail(request, repo_id, size, path) try: with open(thumbnail_file, 'rb') as f: thumbnail = f.read() return HttpResponse(content=thumbnail, mimetype='image/'+THUMBNAIL_EXTENSION) except IOError as e: logger.error(e) return HttpResponse()
def group_wiki_use_lib(request, group): if group.view_perm == "pub": raise Http404 if request.method != 'POST': raise Http404 repo_id = request.POST.get('dst_repo', '') username = request.user.username next = reverse('group_wiki', args=[group.id]) repo = seafile_api.get_repo(repo_id) if repo is None: messages.error(request, _('Failed to set wiki library.')) return HttpResponseRedirect(next) GroupWiki.objects.save_group_wiki(group_id=group.id, repo_id=repo_id) # create home page if not exist page_name = "home.md" if not seaserv.get_file_id_by_path(repo_id, "/" + page_name): if not seaserv.post_empty_file(repo_id, "/", page_name, username): messages.error(request, _('Failed to create home page. Please retry later')) return HttpResponseRedirect(next)
def thumbnail_get(request, repo_id, size, path): """ handle thumbnail src from repo file list return thumbnail file to web """ if check_folder_permission(request, repo_id, path) is None: return HttpResponse() obj_id = get_file_id_by_path(repo_id, path) thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id) if not os.path.exists(thumbnail_file) and \ allow_generate_thumbnail(request, repo_id, path): generate_thumbnail(request, repo_id, size, path) try: with open(thumbnail_file, 'rb') as f: thumbnail = f.read() return HttpResponse(content=thumbnail, mimetype='image/' + THUMBNAIL_EXTENSION) except IOError as e: logger.error(e) return HttpResponse()
def view_raw_file(request, repo_id, file_path): """Returns raw content of a file. Arguments: - `request`: - `repo_id`: """ repo = get_repo(repo_id) if not repo: raise Http404 file_path = file_path.rstrip("/") if file_path[0] != "/": file_path = "/" + file_path obj_id = get_file_id_by_path(repo_id, file_path) if not obj_id: raise Http404 raw_path, inner_path, user_perm = get_file_view_path_and_perm(request, repo.id, obj_id, file_path) if user_perm is None: raise Http404 return HttpResponseRedirect(raw_path)
def file_edit(request, repo_id): repo = get_repo(repo_id) if not repo: raise Http404 if request.method == 'POST': return file_edit_submit(request, repo_id) if check_repo_access_permission(repo_id, request.user) != 'rw': return render_permission_error(request, _(u'Unable to edit file')) path = request.GET.get('p', '/') if path[-1] == '/': path = path[:-1] u_filename = os.path.basename(path) filename = urllib2.quote(u_filename.encode('utf-8')) head_id = repo.head_cmmt_id obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u'The file does not exist.')) token = web_get_access_token(repo_id, obj_id, 'view', request.user.username) # generate path and link zipped = gen_path_link(path, repo.name) filetype, fileext = get_file_type_and_ext(filename) op = None err = '' file_content = None encoding = None file_encoding_list = FILE_ENCODING_LIST if filetype == TEXT or filetype == MARKDOWN or filetype == SF: if repo.encrypted: repo.password_set = seafile_api.is_password_set( repo_id, request.user.username) if not repo.password_set: op = 'decrypt' if not op: inner_path = gen_inner_file_get_url(token, filename) file_enc = request.GET.get('file_enc', 'auto') if not file_enc in FILE_ENCODING_LIST: file_enc = 'auto' err, file_content, encoding = repo_file_get(inner_path, file_enc) if encoding and encoding not in FILE_ENCODING_LIST: file_encoding_list.append(encoding) else: err = _(u'Edit online is not offered for this type of file.') # Redirect to different place according to from page when user click # cancel button on file edit page. cancel_url = reverse('repo_view_file', args=[repo.id ]) + '?p=' + urlquote(path) page_from = request.GET.get('from', '') gid = request.GET.get('gid', '') wiki_name = os.path.splitext(u_filename)[0] if page_from == 'wiki_page_edit' or page_from == 'wiki_page_new': cancel_url = reverse('group_wiki', args=[gid, wiki_name]) elif page_from == 'personal_wiki_page_edit' or page_from == 'personal_wiki_page_new': cancel_url = reverse('personal_wiki', args=[wiki_name]) return render_to_response('file_edit.html', { 'repo': repo, 'u_filename': u_filename, 'wiki_name': wiki_name, 'path': path, 'zipped': zipped, 'filetype': filetype, 'fileext': fileext, 'op': op, 'err': err, 'file_content': file_content, 'encoding': encoding, 'file_encoding_list': file_encoding_list, 'head_id': head_id, 'from': page_from, 'gid': gid, 'cancel_url': cancel_url, }, context_instance=RequestContext(request))
def view_file(request, repo_id): """ Steps to view file: 1. Get repo id and file path. 2. Check user's permission. 3. Check whether this file can be viewed online. 4.1 Get file content if file is text file. 4.2 Prepare flash if file is document. 4.3 Prepare or use pdfjs if file is pdf. 4.4 Other file return it's raw path. """ username = request.user.username # check arguments repo = get_repo(repo_id) if not repo: raise Http404 path = request.GET.get('p', '/').rstrip('/') obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u'File does not exist')) # construct some varibles u_filename = os.path.basename(path) current_commit = get_commits(repo_id, 0, 1)[0] # Check whether user has permission to view file and get file raw path, # render error page if permission deny. raw_path, inner_path, user_perm = get_file_view_path_and_perm( request, repo_id, obj_id, path) if not user_perm: return render_permission_error(request, _(u'Unable to view file')) # check if the user is the owner or not, for 'private share' if is_org_context(request): repo_owner = seafile_api.get_org_repo_owner(repo.id) is_repo_owner = True if repo_owner == username else False else: is_repo_owner = seafile_api.is_repo_owner(username, repo.id) # get file type and extension filetype, fileext = get_file_type_and_ext(u_filename) img_prev = None img_next = None ret_dict = { 'err': '', 'file_content': '', 'encoding': '', 'file_enc': '', 'file_encoding_list': [], 'html_exists': False, 'filetype': filetype } fsize = get_file_size(repo.store_id, repo.version, obj_id) exceeds_limit, err_msg = file_size_exceeds_preview_limit(fsize, filetype) if exceeds_limit: ret_dict['err'] = err_msg else: """Choose different approach when dealing with different type of file.""" if is_textual_file(file_type=filetype): handle_textual_file(request, filetype, inner_path, ret_dict) if filetype == MARKDOWN: c = ret_dict['file_content'] ret_dict['file_content'] = convert_md_link( c, repo_id, username) elif filetype == DOCUMENT: handle_document(inner_path, obj_id, fileext, ret_dict) elif filetype == SPREADSHEET: handle_spreadsheet(inner_path, obj_id, fileext, ret_dict) elif filetype == OPENDOCUMENT: if fsize == 0: ret_dict['err'] = _(u'Invalid file format.') elif filetype == PDF: handle_pdf(inner_path, obj_id, fileext, ret_dict) elif filetype == IMAGE: parent_dir = os.path.dirname(path) dirs = seafile_api.list_dir_by_commit_and_path( current_commit.repo_id, current_commit.id, parent_dir) if not dirs: raise Http404 img_list = [] for dirent in dirs: if not stat.S_ISDIR(dirent.props.mode): fltype, flext = get_file_type_and_ext(dirent.obj_name) if fltype == 'Image': img_list.append(dirent.obj_name) if len(img_list) > 1: img_list.sort(lambda x, y: cmp(x.lower(), y.lower())) cur_img_index = img_list.index(u_filename) if cur_img_index != 0: img_prev = posixpath.join(parent_dir, img_list[cur_img_index - 1]) if cur_img_index != len(img_list) - 1: img_next = posixpath.join(parent_dir, img_list[cur_img_index + 1]) else: pass # generate file path navigator zipped = gen_path_link(path, repo.name) # file shared link l = FileShare.objects.filter(repo_id=repo_id).filter( username=username).filter(path=path) fileshare = l[0] if len(l) > 0 else None http_or_https = request.is_secure() and 'https' or 'http' domain = RequestSite(request).domain if fileshare: file_shared_link = gen_file_share_link(fileshare.token) else: file_shared_link = '' for g in request.user.joined_groups: g.avatar = grp_avatar(g.id, 20) """List repo groups""" # Get groups this repo is shared. if request.user.org: org_id = request.user.org.org_id repo_shared_groups = get_org_groups_by_repo(org_id, repo_id) else: repo_shared_groups = get_shared_groups_by_repo(repo_id) # Filter out groups that user in joined. groups = [x for x in repo_shared_groups if is_group_user(x.id, username)] if len(groups) > 1: ctx = {} ctx['groups'] = groups repogrp_str = render_to_string("snippets/repo_group_list.html", ctx) else: repogrp_str = '' file_path_hash = hashlib.md5(urllib2.quote( path.encode('utf-8'))).hexdigest()[:12] # fetch file contributors and latest contributor contributors, last_modified, last_commit_id = \ FileContributors.objects.get_file_contributors( repo_id, path.encode('utf-8'), file_path_hash, obj_id) latest_contributor = contributors[0] if contributors else None # check whether file is starred is_starred = False org_id = -1 if request.user.org: org_id = request.user.org.org_id is_starred = is_file_starred(username, repo.id, path.encode('utf-8'), org_id) template = 'view_file_%s.html' % ret_dict['filetype'].lower() return render_to_response( template, { 'repo': repo, 'is_repo_owner': is_repo_owner, 'obj_id': obj_id, 'filename': u_filename, 'path': path, 'zipped': zipped, 'current_commit': current_commit, 'fileext': fileext, 'raw_path': raw_path, 'fileshare': fileshare, 'protocol': http_or_https, 'domain': domain, 'file_shared_link': file_shared_link, 'err': ret_dict['err'], 'file_content': ret_dict['file_content'], 'file_enc': ret_dict['file_enc'], 'encoding': ret_dict['encoding'], 'file_encoding_list': ret_dict['file_encoding_list'], 'html_exists': ret_dict['html_exists'], 'html_detail': ret_dict.get('html_detail', {}), 'filetype': ret_dict['filetype'], 'groups': groups, 'use_pdfjs': USE_PDFJS, 'contributors': contributors, 'latest_contributor': latest_contributor, 'last_modified': last_modified, 'last_commit_id': last_commit_id, 'repo_group_str': repogrp_str, 'is_starred': is_starred, 'user_perm': user_perm, 'img_prev': img_prev, 'img_next': img_next, 'highlight_keyword': settings.HIGHLIGHT_KEYWORD, }, context_instance=RequestContext(request))
def generate_thumbnail(request, repo_id, size, path): """ generate and save thumbnail if not exist before generate thumbnail, you should check: 1. if repo exist: should exist; 2. if repo is encrypted: not encrypted; 3. if ENABLE_THUMBNAIL: enabled; """ try: size = int(size) except ValueError as e: logger.error(e) return (False, 400) thumbnail_dir = os.path.join(THUMBNAIL_ROOT, str(size)) if not os.path.exists(thumbnail_dir): os.makedirs(thumbnail_dir) file_id = get_file_id_by_path(repo_id, path) if not file_id: return (False, 400) thumbnail_file = os.path.join(thumbnail_dir, file_id) if os.path.exists(thumbnail_file): return (True, 200) repo = get_repo(repo_id) file_size = get_file_size(repo.store_id, repo.version, file_id) filetype, fileext = get_file_type_and_ext(os.path.basename(path)) if filetype == VIDEO: # video thumbnails if ENABLE_VIDEO_THUMBNAIL: return create_video_thumbnails(repo, file_id, path, size, thumbnail_file, file_size) else: return (False, 400) if filetype == XMIND: return extract_xmind_image(repo_id, path, size) # image thumbnails if file_size > THUMBNAIL_IMAGE_SIZE_LIMIT * 1024**2: return (False, 400) if fileext.lower() == 'psd': return create_psd_thumbnails(repo, file_id, path, size, thumbnail_file, file_size) token = seafile_api.get_fileserver_access_token(repo_id, file_id, 'view', '', use_onetime=True) if not token: return (False, 500) inner_path = gen_inner_file_get_url(token, os.path.basename(path)) try: image_file = urllib2.urlopen(inner_path) f = StringIO(image_file.read()) return _create_thumbnail_common(f, thumbnail_file, size) except Exception as e: logger.error(e) return (False, 500)
def view_file(request, repo_id): """ Steps to view file: 1. Get repo id and file path. 2. Check user's permission. 3. Check whether this file can be viewed online. 4.1 Get file content if file is text file. 4.2 Prepare flash if file is document. 4.3 Prepare or use pdfjs if file is pdf. 4.4 Other file return it's raw path. """ username = request.user.username # check arguments repo = get_repo(repo_id) if not repo: raise Http404 path = request.GET.get("p", "/") obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u"File does not exist")) # construct some varibles u_filename = os.path.basename(path) filename_utf8 = urllib2.quote(u_filename.encode("utf-8")) current_commit = get_commits(repo_id, 0, 1)[0] # Check whether user has permission to view file and get file raw path, # render error page if permission is deny. raw_path, user_perm = get_file_view_path_and_perm(request, repo_id, obj_id, u_filename) if not user_perm: return render_permission_error(request, _(u"Unable to view file")) # get file type and extension filetype, fileext = get_file_type_and_ext(u_filename) img_prev = None img_next = None ret_dict = { "err": "", "file_content": "", "encoding": "", "file_enc": "", "file_encoding_list": [], "swf_exists": False, "filetype": filetype, } # Check file size fsize = get_file_size(obj_id) if fsize > FILE_PREVIEW_MAX_SIZE: from django.template.defaultfilters import filesizeformat err = _(u"File size surpasses %s, can not be opened online.") % filesizeformat(FILE_PREVIEW_MAX_SIZE) ret_dict["err"] = err else: """Choose different approach when dealing with different type of file.""" if is_textual_file(file_type=filetype): handle_textual_file(request, filetype, raw_path, ret_dict) if filetype == MARKDOWN: c = ret_dict["file_content"] ret_dict["file_content"] = convert_md_link(c, repo_id, username) elif filetype == DOCUMENT: handle_document(raw_path, obj_id, fileext, ret_dict) elif filetype == PDF: handle_pdf(raw_path, obj_id, fileext, ret_dict) elif filetype == IMAGE: parent_dir = os.path.dirname(path) dirs = list_dir_by_path(current_commit.id, parent_dir) if not dirs: raise Http404 img_list = [] for dirent in dirs: if not stat.S_ISDIR(dirent.props.mode): fltype, flext = get_file_type_and_ext(dirent.obj_name) if fltype == "Image": img_list.append(dirent.obj_name) if len(img_list) > 1: img_list.sort(lambda x, y: cmp(x.lower(), y.lower())) cur_img_index = img_list.index(u_filename) if cur_img_index != 0: img_prev = os.path.join(parent_dir, img_list[cur_img_index - 1]) if cur_img_index != len(img_list) - 1: img_next = os.path.join(parent_dir, img_list[cur_img_index + 1]) else: pass # generate file path navigator zipped = gen_path_link(path, repo.name) # file shared link l = FileShare.objects.filter(repo_id=repo_id).filter(username=username).filter(path=path) fileshare = l[0] if len(l) > 0 else None http_or_https = request.is_secure() and "https" or "http" domain = RequestSite(request).domain if fileshare: file_shared_link = gen_shared_link(request, fileshare.token, "f") else: file_shared_link = "" # my contacts used in shared link autocomplete contacts = Contact.objects.filter(user_email=username) """List repo groups""" # Get groups this repo is shared. if request.user.org: org_id = request.user.org["org_id"] repo_shared_groups = get_org_groups_by_repo(org_id, repo_id) else: repo_shared_groups = get_shared_groups_by_repo(repo_id) # Filter out groups that user in joined. groups = [x for x in repo_shared_groups if is_group_user(x.id, username)] if len(groups) > 1: ctx = {} ctx["groups"] = groups repogrp_str = render_to_string("snippets/repo_group_list.html", ctx) else: repogrp_str = "" file_path_hash = md5_constructor(urllib2.quote(path.encode("utf-8"))).hexdigest()[:12] # fetch file contributors and latest contributor contributors, last_modified, last_commit_id = get_file_contributors( repo_id, path.encode("utf-8"), file_path_hash, obj_id ) latest_contributor = contributors[0] if contributors else None # check whether file is starred is_starred = False org_id = -1 if request.user.org: org_id = request.user.org["org_id"] is_starred = is_file_starred(username, repo.id, path.encode("utf-8"), org_id) template = "view_file_%s.html" % ret_dict["filetype"].lower() return render_to_response( template, { "repo": repo, "obj_id": obj_id, "filename": u_filename, "path": path, "zipped": zipped, "current_commit": current_commit, "fileext": fileext, "raw_path": raw_path, "fileshare": fileshare, "protocol": http_or_https, "domain": domain, "file_shared_link": file_shared_link, "contacts": contacts, "err": ret_dict["err"], "file_content": ret_dict["file_content"], "file_enc": ret_dict["file_enc"], "encoding": ret_dict["encoding"], "file_encoding_list": ret_dict["file_encoding_list"], "swf_exists": ret_dict["swf_exists"], "filetype": ret_dict["filetype"], "applet_root": get_ccnetapplet_root(), "groups": groups, "DOCUMENT_CONVERTOR_ROOT": DOCUMENT_CONVERTOR_ROOT, "use_pdfjs": USE_PDFJS, "contributors": contributors, "latest_contributor": latest_contributor, "last_modified": last_modified, "last_commit_id": last_commit_id, "repo_group_str": repogrp_str, "is_starred": is_starred, "user_perm": user_perm, "img_prev": img_prev, "img_next": img_next, }, context_instance=RequestContext(request), )
def view_file(request, repo_id): """ Steps to view file: 1. Get repo id and file path. 2. Check user's permission. 3. Check whether this file can be viewed online. 4.1 Get file content if file is text file. 4.2 Prepare flash if file is document. 4.3 Prepare or use pdfjs if file is pdf. 4.4 Other file return it's raw path. """ username = request.user.username # check arguments repo = get_repo(repo_id) if not repo: raise Http404 path = request.GET.get('p', '/') obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u'File does not exist')) # construct some varibles u_filename = os.path.basename(path) current_commit = get_commits(repo_id, 0, 1)[0] # Check whether user has permission to view file and get file raw path, # render error page if permission is deny. raw_path, user_perm = get_file_view_path_and_perm(request, repo_id, obj_id, u_filename) if not user_perm: return render_permission_error(request, _(u'Unable to view file')) # get file type and extension filetype, fileext = get_file_type_and_ext(u_filename) img_prev = None img_next = None ret_dict = {'err': '', 'file_content': '', 'encoding': '', 'file_enc': '', 'file_encoding_list': [], 'html_exists': False, 'filetype': filetype} fsize = get_file_size(obj_id) exceeds_limit, err_msg = file_size_exceeds_preview_limit(fsize, filetype) if exceeds_limit: ret_dict['err'] = err_msg else: """Choose different approach when dealing with different type of file.""" if is_textual_file(file_type=filetype): handle_textual_file(request, filetype, raw_path, ret_dict) if filetype == MARKDOWN: c = ret_dict['file_content'] ret_dict['file_content'] = convert_md_link(c, repo_id, username) elif filetype == DOCUMENT: handle_document(raw_path, obj_id, fileext, ret_dict) elif filetype == PDF: handle_pdf(raw_path, obj_id, fileext, ret_dict) elif filetype == IMAGE: parent_dir = os.path.dirname(path) dirs = list_dir_by_path(current_commit.id, parent_dir) if not dirs: raise Http404 img_list = [] for dirent in dirs: if not stat.S_ISDIR(dirent.props.mode): fltype, flext = get_file_type_and_ext(dirent.obj_name) if fltype == 'Image': img_list.append(dirent.obj_name) if len(img_list) > 1: img_list.sort(lambda x, y : cmp(x.lower(), y.lower())) cur_img_index = img_list.index(u_filename) if cur_img_index != 0: img_prev = os.path.join(parent_dir, img_list[cur_img_index - 1]) if cur_img_index != len(img_list) - 1: img_next = os.path.join(parent_dir, img_list[cur_img_index + 1]) else: pass # generate file path navigator zipped = gen_path_link(path, repo.name) # file shared link l = FileShare.objects.filter(repo_id=repo_id).filter( username=username).filter(path=path) fileshare = l[0] if len(l) > 0 else None http_or_https = request.is_secure() and 'https' or 'http' domain = RequestSite(request).domain if fileshare: file_shared_link = gen_shared_link(request, fileshare.token, 'f') else: file_shared_link = '' # my contacts used in shared link autocomplete contacts = Contact.objects.filter(user_email=username) """List repo groups""" # Get groups this repo is shared. if request.user.org: org_id = request.user.org['org_id'] repo_shared_groups = get_org_groups_by_repo(org_id, repo_id) else: repo_shared_groups = get_shared_groups_by_repo(repo_id) # Filter out groups that user in joined. groups = [ x for x in repo_shared_groups if is_group_user(x.id, username)] if len(groups) > 1: ctx = {} ctx['groups'] = groups repogrp_str = render_to_string("snippets/repo_group_list.html", ctx) else: repogrp_str = '' file_path_hash = md5_constructor(urllib2.quote(path.encode('utf-8'))).hexdigest()[:12] # fetch file contributors and latest contributor contributors, last_modified, last_commit_id = get_file_contributors(repo_id, path.encode('utf-8'), file_path_hash, obj_id) latest_contributor = contributors[0] if contributors else None # check whether file is starred is_starred = False org_id = -1 if request.user.org: org_id = request.user.org['org_id'] is_starred = is_file_starred(username, repo.id, path.encode('utf-8'), org_id) template = 'view_file_%s.html' % ret_dict['filetype'].lower() search_repo_id = None if not repo.encrypted: search_repo_id = repo.id return render_to_response(template, { 'repo': repo, 'obj_id': obj_id, 'filename': u_filename, 'path': path, 'zipped': zipped, 'current_commit': current_commit, 'fileext': fileext, 'raw_path': raw_path, 'fileshare': fileshare, 'protocol': http_or_https, 'domain': domain, 'file_shared_link': file_shared_link, 'contacts': contacts, 'err': ret_dict['err'], 'file_content': ret_dict['file_content'], 'file_enc': ret_dict['file_enc'], 'encoding': ret_dict['encoding'], 'file_encoding_list':ret_dict['file_encoding_list'], 'html_exists': ret_dict['html_exists'], 'html_detail': ret_dict.get('html_detail', {}), 'filetype': ret_dict['filetype'], "applet_root": get_ccnetapplet_root(), 'groups': groups, 'use_pdfjs':USE_PDFJS, 'contributors': contributors, 'latest_contributor': latest_contributor, 'last_modified': last_modified, 'last_commit_id': last_commit_id, 'repo_group_str': repogrp_str, 'is_starred': is_starred, 'user_perm': user_perm, 'img_prev': img_prev, 'img_next': img_next, 'search_repo_id': search_repo_id, }, context_instance=RequestContext(request))
def group_discuss(request, group): if group.is_pub: raise Http404 username = request.user.username form = MessageForm() # remove user notifications UserNotification.objects.seen_group_msg_notices(username, group.id) # Get all group members. members = get_group_members(group.id) """group messages""" # Show 15 group messages per page. paginator = Paginator(GroupMessage.objects.filter(group_id=group.id).order_by("-timestamp"), 15) # Make sure page request is an int. If not, deliver first page. try: page = int(request.GET.get("page", "1")) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: group_msgs = paginator.page(page) except (EmptyPage, InvalidPage): group_msgs = paginator.page(paginator.num_pages) group_msgs.page_range = paginator.get_page_range(group_msgs.number) # Force evaluate queryset to fix some database error for mysql. group_msgs.object_list = list(group_msgs.object_list) msg_attachments = MessageAttachment.objects.filter(group_message__in=group_msgs.object_list) msg_replies = MessageReply.objects.filter(reply_to__in=group_msgs.object_list) reply_to_list = [r.reply_to_id for r in msg_replies] for msg in group_msgs.object_list: msg.reply_cnt = reply_to_list.count(msg.id) msg.replies = [] for r in msg_replies: if msg.id == r.reply_to_id: msg.replies.append(r) msg.replies = msg.replies[-3:] msg.attachments = [] for att in msg_attachments: if att.group_message_id != msg.id: continue # Attachment name is file name or directory name. # If is top directory, use repo name instead. path = att.path if path == "/": repo = get_repo(att.repo_id) if not repo: # TODO: what should we do here, tell user the repo # is no longer exists? continue att.name = repo.name else: path = path.rstrip("/") # cut out last '/' if possible att.name = os.path.basename(path) # Load to discuss page if attachment is a image and from recommend. if att.attach_type == "file" and att.src == "recommend": att.filetype, att.fileext = get_file_type_and_ext(att.name) if att.filetype == IMAGE: att.obj_id = get_file_id_by_path(att.repo_id, path) if not att.obj_id: att.err = _(u"File does not exist") else: att.token = seafile_api.get_fileserver_access_token(att.repo_id, att.obj_id, "view", username) att.img_url = gen_file_get_url(att.token, att.name) msg.attachments.append(att) # get available modules(wiki, etc) mods_available = get_available_mods_by_group(group.id) mods_enabled = get_enabled_mods_by_group(group.id) return render_to_response( "group/group_discuss.html", { "group": group, "is_staff": group.is_staff, "group_msgs": group_msgs, "form": form, "mods_enabled": mods_enabled, "mods_available": mods_available, }, context_instance=RequestContext(request), )
def thumbnail_create(request, repo_id): content_type = 'application/json; charset=utf-8' result = {} if not request.is_ajax(): err_msg = _(u"Permission denied.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) if not ENABLE_THUMBNAIL: err_msg = _(u"Thumbnail function is not enabled.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) repo = get_repo(repo_id) if not repo: err_msg = _(u"Library does not exist.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) if repo.encrypted: err_msg = _( u"Image thumbnail is not supported in encrypted libraries.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) path = request.GET.get('path', None) obj_id = get_file_id_by_path(repo_id, path) if path is None or obj_id is None: err_msg = _(u"Wrong path.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) # permission check token = request.GET.get('t', None) if token: fileshare = FileShare.objects.get_valid_file_link_by_token(token) if not fileshare or not path.startswith(fileshare.path) or \ fileshare.repo_id != repo_id: # check if is valid download link share token and # if is a valid repo/dir belonged to this file share err_msg = _(u"Permission denied.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) else: if not request.user.is_authenticated(): err_msg = _(u"Please login first.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) elif check_repo_access_permission(repo_id, request.user) is None: err_msg = _(u"Permission denied.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) # get image file from url size = request.GET.get('size', THUMBNAIL_DEFAULT_SIZE) file_name = os.path.basename(path) access_token = seafile_api.get_fileserver_access_token( repo_id, obj_id, 'view', request.user.username) raw_path = gen_file_get_url(access_token, file_name) open_file = urllib2.urlopen(raw_path) file_size = int(open_file.info()['Content-Length']) # image file size limit check if file_size > THUMBNAIL_IMAGE_SIZE_LIMIT * 1024**2: err_msg = _(u"Image file is too large.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=520, content_type=content_type) thumbnail_dir = os.path.join(THUMBNAIL_ROOT, size) if not os.path.exists(thumbnail_dir): os.makedirs(thumbnail_dir) thumbnail_file = os.path.join(thumbnail_dir, obj_id) if not os.path.exists(thumbnail_file): try: f = StringIO(open_file.read()) image = Image.open(f) if image.mode not in ["1", "L", "P", "RGB", "RGBA"]: image = image.convert("RGB") image.thumbnail((int(size), int(size)), Image.ANTIALIAS) image.save(thumbnail_file, THUMBNAIL_EXTENSION) except Exception as e: logger.error(e) err_msg = _('Failed to create thumbnail.') return HttpResponse(json.dumps({'err_msg': err_msg}), status=500, content_type=content_type) result['thumbnail_src'] = get_thumbnail_src(repo_id, obj_id, size) return HttpResponse(json.dumps(result), content_type=content_type)
def view_file(request, repo_id): """ Steps to view file: 1. Get repo id and file path. 2. Check user's permission. 3. Check whether this file can be viewed online. 4.1 Get file content if file is text file. 4.2 Prepare flash if file is document. 4.3 Prepare or use pdfjs if file is pdf. 4.4 Other file return it's raw path. """ username = request.user.username # check arguments repo = get_repo(repo_id) if not repo: raise Http404 path = request.GET.get('p', '/') obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u'File does not exist')) # construct some varibles u_filename = os.path.basename(path) filename_utf8 = urllib2.quote(u_filename.encode('utf-8')) current_commit = get_commits(repo_id, 0, 1)[0] # Check whether user has permission to view file and get file raw path, # render error page if permission is deny. raw_path, user_perm = get_file_view_path_and_perm(request, repo_id, obj_id, u_filename) if not user_perm: return render_permission_error(request, _(u'Unable to view file')) # get file type and extension filetype, fileext = get_file_type_and_ext(u_filename) img_prev = None img_next = None ret_dict = {'err': '', 'file_content': '', 'encoding': '', 'file_enc': '', 'file_encoding_list': [], 'html_exists': False, 'filetype': filetype} # Check file size fsize = get_file_size(obj_id) if fsize > FILE_PREVIEW_MAX_SIZE: err = _(u'File size surpasses %s, can not be opened online.') % \ filesizeformat(FILE_PREVIEW_MAX_SIZE) ret_dict['err'] = err elif filetype in (DOCUMENT, PDF) and fsize > OFFICE_PREVIEW_MAX_SIZE: err = _(u'File size surpasses %s, can not be opened online.') % \ filesizeformat(OFFICE_PREVIEW_MAX_SIZE) ret_dict['err'] = err else: """Choose different approach when dealing with different type of file.""" if is_textual_file(file_type=filetype): handle_textual_file(request, filetype, raw_path, ret_dict) if filetype == MARKDOWN: c = ret_dict['file_content'] ret_dict['file_content'] = convert_md_link(c, repo_id, username) elif filetype == DOCUMENT: handle_document(raw_path, obj_id, fileext, ret_dict) elif filetype == PDF: handle_pdf(raw_path, obj_id, fileext, ret_dict) elif filetype == IMAGE: parent_dir = os.path.dirname(path) dirs = list_dir_by_path(current_commit.id, parent_dir) if not dirs: raise Http404 img_list = [] for dirent in dirs: if not stat.S_ISDIR(dirent.props.mode): fltype, flext = get_file_type_and_ext(dirent.obj_name) if fltype == 'Image': img_list.append(dirent.obj_name) if len(img_list) > 1: img_list.sort(lambda x, y : cmp(x.lower(), y.lower())) cur_img_index = img_list.index(u_filename) if cur_img_index != 0: img_prev = os.path.join(parent_dir, img_list[cur_img_index - 1]) if cur_img_index != len(img_list) - 1: img_next = os.path.join(parent_dir, img_list[cur_img_index + 1]) else: pass # generate file path navigator zipped = gen_path_link(path, repo.name) # file shared link l = FileShare.objects.filter(repo_id=repo_id).filter( username=username).filter(path=path) fileshare = l[0] if len(l) > 0 else None http_or_https = request.is_secure() and 'https' or 'http' domain = RequestSite(request).domain if fileshare: file_shared_link = gen_shared_link(request, fileshare.token, 'f') else: file_shared_link = '' # my contacts used in shared link autocomplete contacts = Contact.objects.filter(user_email=username) """List repo groups""" # Get groups this repo is shared. if request.user.org: org_id = request.user.org['org_id'] repo_shared_groups = get_org_groups_by_repo(org_id, repo_id) else: repo_shared_groups = get_shared_groups_by_repo(repo_id) # Filter out groups that user in joined. groups = [ x for x in repo_shared_groups if is_group_user(x.id, username)] if len(groups) > 1: ctx = {} ctx['groups'] = groups repogrp_str = render_to_string("snippets/repo_group_list.html", ctx) else: repogrp_str = '' file_path_hash = md5_constructor(urllib2.quote(path.encode('utf-8'))).hexdigest()[:12] # fetch file contributors and latest contributor contributors, last_modified, last_commit_id = get_file_contributors(repo_id, path.encode('utf-8'), file_path_hash, obj_id) latest_contributor = contributors[0] if contributors else None # check whether file is starred is_starred = False org_id = -1 if request.user.org: org_id = request.user.org['org_id'] is_starred = is_file_starred(username, repo.id, path.encode('utf-8'), org_id) template = 'view_file_%s.html' % ret_dict['filetype'].lower() search_repo_id = None if not repo.encrypted: search_repo_id = repo.id return render_to_response(template, { 'repo': repo, 'obj_id': obj_id, 'filename': u_filename, 'path': path, 'zipped': zipped, 'current_commit': current_commit, 'fileext': fileext, 'raw_path': raw_path, 'fileshare': fileshare, 'protocol': http_or_https, 'domain': domain, 'file_shared_link': file_shared_link, 'contacts': contacts, 'err': ret_dict['err'], 'file_content': ret_dict['file_content'], 'file_enc': ret_dict['file_enc'], 'encoding': ret_dict['encoding'], 'file_encoding_list':ret_dict['file_encoding_list'], 'html_exists': ret_dict['html_exists'], 'html_detail': ret_dict.get('html_detail', {}), 'filetype': ret_dict['filetype'], "applet_root": get_ccnetapplet_root(), 'groups': groups, 'use_pdfjs':USE_PDFJS, 'contributors': contributors, 'latest_contributor': latest_contributor, 'last_modified': last_modified, 'last_commit_id': last_commit_id, 'repo_group_str': repogrp_str, 'is_starred': is_starred, 'user_perm': user_perm, 'img_prev': img_prev, 'img_next': img_next, 'search_repo_id': search_repo_id, }, context_instance=RequestContext(request))
def file_edit(request, repo_id): repo = get_repo(repo_id) if not repo: raise Http404 if request.method == 'POST': return file_edit_submit(request, repo_id) if get_user_permission(request, repo_id) != 'rw': return render_permission_error(request, _(u'Unable to edit file')) path = request.GET.get('p', '/') if path[-1] == '/': path = path[:-1] u_filename = os.path.basename(path) filename = urllib2.quote(u_filename.encode('utf-8')) head_id = repo.head_cmmt_id obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u'The file does not exist.')) token = web_get_access_token(repo_id, obj_id, 'view', request.user.username) # generate path and link zipped = gen_path_link(path, repo.name) filetype, fileext = get_file_type_and_ext(filename) op = None err = '' file_content = None encoding = None file_encoding_list = FILE_ENCODING_LIST if filetype == TEXT or filetype == MARKDOWN or filetype == SF: if repo.encrypted: repo.password_set = seafserv_rpc.is_passwd_set(repo_id, request.user.username) if not repo.password_set: op = 'decrypt' if not op: raw_path = gen_file_get_url(token, filename) file_enc = request.GET.get('file_enc', 'auto') if not file_enc in FILE_ENCODING_LIST: file_enc = 'auto' err, file_content, encoding = repo_file_get(raw_path, file_enc) if encoding and encoding not in FILE_ENCODING_LIST: file_encoding_list.append(encoding) else: err = _(u'Edit online is not offered for this type of file.') # Redirect to different place according to from page when user click # cancel button on file edit page. cancel_url = reverse('repo_view_file', args=[repo.id]) + '?p=' + urlquote(path) page_from = request.GET.get('from', '') gid = request.GET.get('gid', '') wiki_name = os.path.splitext(u_filename)[0] if page_from == 'wiki_page_edit' or page_from == 'wiki_page_new': cancel_url = reverse('group_wiki', args=[gid, wiki_name]) elif page_from == 'personal_wiki_page_edit' or page_from == 'personal_wiki_page_new': cancel_url = reverse('personal_wiki', args=[wiki_name]) search_repo_id = None if not repo.encrypted: search_repo_id = repo.id return render_to_response('file_edit.html', { 'repo':repo, 'u_filename':u_filename, 'wiki_name': wiki_name, 'path':path, 'zipped':zipped, 'filetype':filetype, 'fileext':fileext, 'op':op, 'err':err, 'file_content':file_content, 'encoding': encoding, 'file_encoding_list':file_encoding_list, 'head_id': head_id, 'from': page_from, 'gid': gid, 'cancel_url': cancel_url, 'search_repo_id': search_repo_id, }, context_instance=RequestContext(request))
def file_edit(request, repo_id): repo = get_repo(repo_id) if not repo: raise Http404 if request.method == "POST": return file_edit_submit(request, repo_id) if get_user_permission(request, repo_id) != "rw": return render_permission_error(request, _(u"Unable to edit file")) path = request.GET.get("p", "/") if path[-1] == "/": path = path[:-1] u_filename = os.path.basename(path) filename = urllib2.quote(u_filename.encode("utf-8")) head_id = repo.head_cmmt_id obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u"The file does not exist.")) token = web_get_access_token(repo_id, obj_id, "view", request.user.username) # generate path and link zipped = gen_path_link(path, repo.name) filetype, fileext = get_file_type_and_ext(filename) op = None err = "" file_content = None encoding = None file_encoding_list = FILE_ENCODING_LIST if filetype == TEXT or filetype == MARKDOWN or filetype == SF: if repo.encrypted: repo.password_set = seafserv_rpc.is_passwd_set(repo_id, request.user.username) if not repo.password_set: op = "decrypt" if not op: raw_path = gen_file_get_url(token, filename) file_enc = request.GET.get("file_enc", "auto") if not file_enc in FILE_ENCODING_LIST: file_enc = "auto" err, file_content, encoding = repo_file_get(raw_path, file_enc) if encoding and encoding not in FILE_ENCODING_LIST: file_encoding_list.append(encoding) else: err = _(u"Edit online is not offered for this type of file.") return render_to_response( "file_edit.html", { "repo": repo, "u_filename": u_filename, "wiki_name": os.path.splitext(u_filename)[0], "path": path, "zipped": zipped, "filetype": filetype, "fileext": fileext, "op": op, "err": err, "file_content": file_content, "encoding": encoding, "file_encoding_list": file_encoding_list, "head_id": head_id, "from": request.GET.get("from", ""), "gid": request.GET.get("gid", ""), }, context_instance=RequestContext(request), )
def thumbnail_create(request, repo_id): content_type = 'application/json; charset=utf-8' result = {} if not request.is_ajax(): err_msg = _(u"Permission denied.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) if not ENABLE_THUMBNAIL: err_msg = _(u"Thumbnail function is not enabled.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) repo = get_repo(repo_id) if not repo: err_msg = _(u"Library does not exist.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) if repo.encrypted: err_msg = _(u"Image thumbnail is not supported in encrypted libraries.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) path = request.GET.get('path', None) obj_id = get_file_id_by_path(repo_id, path) if path is None or obj_id is None: err_msg = _(u"Wrong path.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) # permission check token = request.GET.get('t', None) if token: fileshare = FileShare.objects.get_valid_file_link_by_token(token) if not fileshare or not path.startswith(fileshare.path) or \ fileshare.repo_id != repo_id: # check if is valid download link share token and # if is a valid repo/dir belonged to this file share err_msg = _(u"Permission denied.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) else: if not request.user.is_authenticated(): err_msg = _(u"Please login first.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) elif check_repo_access_permission(repo_id, request.user) is None: err_msg = _(u"Permission denied.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=403, content_type=content_type) # get image file from url size = request.GET.get('size', THUMBNAIL_DEFAULT_SIZE) file_name = os.path.basename(path) access_token = seafile_api.get_fileserver_access_token(repo_id, obj_id, 'view', request.user.username) raw_path = gen_file_get_url(access_token, file_name) open_file = urllib2.urlopen(raw_path) file_size = int(open_file.info()['Content-Length']) # image file size limit check if file_size > THUMBNAIL_IMAGE_SIZE_LIMIT * 1024**2: err_msg = _(u"Image file is too large.") return HttpResponse(json.dumps({"err_msg": err_msg}), status=520, content_type=content_type) thumbnail_dir = os.path.join(THUMBNAIL_ROOT, size) if not os.path.exists(thumbnail_dir): os.makedirs(thumbnail_dir) thumbnail_file = os.path.join(thumbnail_dir, obj_id) if not os.path.exists(thumbnail_file): try: f = StringIO(open_file.read()) image = Image.open(f) if image.mode not in ["1", "L", "P", "RGB", "RGBA"]: image = image.convert("RGB") image.thumbnail((int(size), int(size)), Image.ANTIALIAS) image.save(thumbnail_file, THUMBNAIL_EXTENSION) except Exception as e: logger.error(e) err_msg = _('Failed to create thumbnail.') return HttpResponse(json.dumps({'err_msg': err_msg}), status=500, content_type=content_type) result['thumbnail_src'] = get_thumbnail_src(repo_id, obj_id, size) return HttpResponse(json.dumps(result), content_type=content_type)
def group_discuss(request, group): if group.is_pub: raise Http404 username = request.user.username form = MessageForm() # remove user notifications UserNotification.objects.seen_group_msg_notices(username, group.id) # Get all group members. members = get_group_members(group.id) """group messages""" # Show 15 group messages per page. paginator = Paginator(GroupMessage.objects.filter( group_id=group.id).order_by('-timestamp'), 15) # Make sure page request is an int. If not, deliver first page. try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: group_msgs = paginator.page(page) except (EmptyPage, InvalidPage): group_msgs = paginator.page(paginator.num_pages) group_msgs.page_range = paginator.get_page_range(group_msgs.number) # Force evaluate queryset to fix some database error for mysql. group_msgs.object_list = list(group_msgs.object_list) msg_attachments = MessageAttachment.objects.filter(group_message__in=group_msgs.object_list) msg_replies = MessageReply.objects.filter(reply_to__in=group_msgs.object_list) reply_to_list = [ r.reply_to_id for r in msg_replies ] for msg in group_msgs.object_list: msg.reply_cnt = reply_to_list.count(msg.id) msg.replies = [] for r in msg_replies: if msg.id == r.reply_to_id: msg.replies.append(r) msg.replies = msg.replies[-3:] msg.attachments = [] for att in msg_attachments: if att.group_message_id != msg.id: continue # Attachment name is file name or directory name. # If is top directory, use repo name instead. path = att.path if path == '/': repo = get_repo(att.repo_id) if not repo: # TODO: what should we do here, tell user the repo # is no longer exists? continue att.name = repo.name else: path = path.rstrip('/') # cut out last '/' if possible att.name = os.path.basename(path) # Load to discuss page if attachment is a image and from recommend. if att.attach_type == 'file' and att.src == 'recommend': att.filetype, att.fileext = get_file_type_and_ext(att.name) if att.filetype == IMAGE: att.obj_id = get_file_id_by_path(att.repo_id, path) if not att.obj_id: att.err = _(u'File does not exist') else: att.token = seafile_api.get_fileserver_access_token( att.repo_id, att.obj_id, 'view', username) att.img_url = gen_file_get_url(att.token, att.name) msg.attachments.append(att) # get available modules(wiki, etc) mods_available = get_available_mods_by_group(group.id) mods_enabled = get_enabled_mods_by_group(group.id) return render_to_response("group/group_discuss.html", { "group" : group, "is_staff": group.is_staff, "group_msgs": group_msgs, "form": form, "mods_enabled": mods_enabled, "mods_available": mods_available, }, context_instance=RequestContext(request))