• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utils.render_permission_error函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中seahub.utils.render_permission_error函数的典型用法代码示例。如果您正苦于以下问题:Python render_permission_error函数的具体用法?Python render_permission_error怎么用?Python render_permission_error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了render_permission_error函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: repo_remove_share

def repo_remove_share(request):
    """
    If repo is shared from one person to another person, only these two peson
    can remove share.
    If repo is shared from one person to a group, then only the one share the
    repo and group staff can remove share.
    """
    repo_id = request.GET.get('repo_id', '')
    group_id = request.GET.get('gid', '')
    from_email = request.GET.get('from', '')
    if not is_valid_username(from_email):
        return render_error(request, _(u'Argument is not valid'))
    username = request.user.username

    # if request params don't have 'gid', then remove repos that share to
    # to other person; else, remove repos that share to groups
    if not group_id:
        to_email = request.GET.get('to', '')
        if not is_valid_username(to_email):
            return render_error(request, _(u'Argument is not valid'))

        if username != from_email and username != to_email:
            return render_permission_error(request, _(u'Failed to remove share'))

        if is_org_context(request):
            org_id = request.user.org.org_id
            org_remove_share(org_id, repo_id, from_email, to_email)
        else:
            seaserv.remove_share(repo_id, from_email, to_email)
    else:
        try:
            group_id = int(group_id)
        except:
            return render_error(request, _(u'group id is not valid'))

        group = seaserv.get_group(group_id)
        if not group:
            return render_error(request, _(u"Failed to unshare: the group doesn't exist."))

        if not seaserv.check_group_staff(group_id, username) \
                and username != from_email:
            return render_permission_error(request, _(u'Failed to remove share'))

        if is_org_group(group_id):
            org_id = get_org_id_by_group(group_id)
            del_org_group_repo(repo_id, org_id, group_id)
        else:
            seafile_api.unset_group_repo(repo_id, group_id, from_email)

    messages.success(request, _('Successfully removed share'))

    next = request.META.get('HTTP_REFERER', SITE_ROOT)
    return HttpResponseRedirect(next)
开发者ID:allo-,项目名称:seahub,代码行数:53,代码来源:views.py


示例2: repo_remove_share

def repo_remove_share(request):
    """
    If repo is shared from one person to another person, only these two peson
    can remove share.
    If repo is shared from one person to a group, then only the one share the
    repo and group staff can remove share.
    """
    repo_id = request.GET.get('repo_id', '')
    group_id = request.GET.get('gid', '')
    from_email = request.GET.get('from', '')
    if not is_valid_username(from_email):
        return render_error(request, _(u'Argument is not valid'))

    # if request params don't have 'gid', then remove repos that share to
    # to other person; else, remove repos that share to groups
    if not group_id:
        to_email = request.GET.get('to', '')
        if not is_valid_username(to_email):
            return render_error(request, _(u'Argument is not valid'))

        if request.user.username != from_email and \
                request.user.username != to_email:
            return render_permission_error(request, _(u'Failed to remove share'))
        remove_share(repo_id, from_email, to_email)
    else:
        try:
            group_id_int = int(group_id)
        except:
            return render_error(request, _(u'group id is not valid'))

        if not check_group_staff(group_id_int, request.user.username) \
                and request.user.username != from_email:
            return render_permission_error(request, _(u'Failed to remove share'))

        if is_org_group(group_id_int):
            org_id = get_org_id_by_group(group_id_int)
            del_org_group_repo(repo_id, org_id, group_id_int)
        else:
            from seahub.group.views import group_unshare_repo
            group_unshare_repo(request, repo_id, group_id_int, from_email)

    messages.success(request, _('Successfully removed share'))

    next = request.META.get('HTTP_REFERER', None)
    if not next:
        next = SITE_ROOT

    return HttpResponseRedirect(next)
开发者ID:tostadora,项目名称:seahub,代码行数:48,代码来源:views.py


示例3: org_group_remove

def org_group_remove(request, url_prefix, group_id):
    # Request header may missing HTTP_REFERER, we need to handle that case.
    next = request.META.get("HTTP_REFERER", None)
    if not next:
        next = seahub_settings.SITE_ROOT

    try:
        group_id_int = int(group_id)
    except ValueError:
        return HttpResponseRedirect(next)

    # Check whether is the org group.
    org_id = get_org_id_by_group(group_id_int)
    if request.user.org["org_id"] != org_id:
        return render_permission_error(
            request,
            _(u"This group doesn't belong to current organazation"),
            extra_ctx={"org": request.user.org, "base_template": "org_base.html"},
        )

    try:
        ccnet_threaded_rpc.remove_group(group_id_int, request.user.username)
        seafserv_threaded_rpc.remove_repo_group(group_id_int, None)
        ccnet_threaded_rpc.remove_org_group(org_id, group_id_int)
    except SearpcError, e:
        return render_error(request, e.msg, extra_ctx={"org": request.user.org, "base_template": "org_base.html"})
开发者ID:weixu8,项目名称:seahub,代码行数:26,代码来源:views.py


示例4: group_dismiss

def group_dismiss(request, group_id):
    """
    Dismiss a group, only group staff can perform this operation.
    """
    next = request.META.get('HTTP_REFERER', None)
    if not next:
        next = SITE_ROOT

    try:
        group_id_int = int(group_id)
    except ValueError:
        return HttpResponseRedirect(next)

    # Check whether user is group staff
    user = request.user.username
    if not ccnet_threaded_rpc.check_group_staff(group_id_int, user):
        return render_permission_error(request, _(u'Only administrators can dismiss the group'))

    try:
        ccnet_threaded_rpc.remove_group(group_id_int, user)
        seafserv_threaded_rpc.remove_repo_group(group_id_int, None)

        if request.user.org:
            org_id = request.user.org['org_id']
            url_prefix = request.user.org['url_prefix']
            ccnet_threaded_rpc.remove_org_group(org_id, group_id_int)
            return HttpResponseRedirect(reverse('org_groups',
                                                args=[url_prefix]))

    except SearpcError, e:
        return render_error(request, _(e.msg))
开发者ID:chuyskywalker,项目名称:seahub,代码行数:31,代码来源:views.py


示例5: repo_history

def repo_history(request, repo_id):
    """
    List library modification histories.
    """
    user_perm = check_folder_permission(request, repo_id, '/')
    if not user_perm:
        return render_permission_error(request, _(u'Unable to view library modification'))

    repo = get_repo(repo_id)
    if not repo:
        raise Http404

    username = request.user.username
    try:
        server_crypto = UserOptions.objects.is_server_crypto(username)
    except CryptoOptionNotSetError:
        # Assume server_crypto is ``False`` if this option is not set.
        server_crypto = False

    password_set = False
    if repo.props.encrypted and \
            (repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)):
        try:
            ret = seafserv_rpc.is_passwd_set(repo_id, username)
            if ret == 1:
                password_set = True
        except SearpcError, e:
            return render_error(request, e.msg)

        if not password_set:
            return HttpResponseRedirect(reverse("view_common_lib_dir", args=[repo_id, '']))
开发者ID:domal,项目名称:seahub,代码行数:31,代码来源:__init__.py


示例6: repo_recycle_view

def repo_recycle_view(request, repo_id):
    if not seafile_api.get_dir_id_by_path(repo_id, '/') or \
        check_folder_permission(request, repo_id, '/') != 'rw':
        return render_permission_error(request, _(u'Unable to view recycle page'))

    commit_id = request.GET.get('commit_id', '')
    if not commit_id:
        return render_recycle_root(request, repo_id)
    else:
        return render_recycle_dir(request, repo_id, commit_id)
开发者ID:domal,项目名称:seahub,代码行数:10,代码来源:__init__.py


示例7: view_snapshot_file

def view_snapshot_file(request, repo_id):
    ret_dict = {}
    view_history_file_common(request, repo_id, ret_dict)
    if not request.user_perm:
        return render_permission_error(request, _(u"Unable to view file"))

    # generate file path navigator
    path = ret_dict["path"]
    repo = ret_dict["repo"]
    ret_dict["zipped"] = gen_path_link(path, repo.name)

    return render_to_response("view_snapshot_file.html", ret_dict, context_instance=RequestContext(request))
开发者ID:sonicby,项目名称:seahub,代码行数:12,代码来源:file.py


示例8: view_history_file

def view_history_file(request, repo_id):
    ret_dict = {}
    view_history_file_common(request, repo_id, ret_dict)
    if not request.user_perm:
        return render_permission_error(request, _(u'Unable to view file'))
        
    # generate file path navigator
    path = ret_dict['path']
    repo = ret_dict['repo']
    ret_dict['zipped'] = gen_path_link(path, repo.name)

    return render_to_response('view_history_file.html', ret_dict,
                              context_instance=RequestContext(request))
开发者ID:viktorlindgren,项目名称:seahub,代码行数:13,代码来源:file.py


示例9: group_unshare_repo

def group_unshare_repo(request, repo_id, group_id, from_email):
    """
    Unshare a repo in group.
    
    """
    # Check whether group exists
    group = get_group(group_id)
    if not group:
        return render_error(request, _(u"Failed to unshare: the group doesn't exist."))

    # Check whether user is group staff or the one share the repo
    if not check_group_staff(group_id, from_email) and \
            seafserv_threaded_rpc.get_group_repo_owner(repo_id) != from_email:
        return render_permission_error(request, _(u"Operation failed: only administrators and the owner of the library can unshare it."))
        
    if seafserv_threaded_rpc.group_unshare_repo(repo_id, group_id, from_email) != 0:
        return render_error(request, _(u"Failed to unshare: internal error."))
开发者ID:chuyskywalker,项目名称:seahub,代码行数:17,代码来源:views.py


示例10: view_trash_file

def view_trash_file(request, repo_id):
    ret_dict = {}
    view_history_file_common(request, repo_id, ret_dict)
    if not request.user_perm:
        return render_permission_error(request, _(u"Unable to view file"))

    basedir = request.GET.get("base", "")
    if not basedir:
        raise Http404
    days = show_delete_days(request)
    ret_dict["basedir"] = basedir
    ret_dict["days"] = days

    # generate file path navigator
    path = ret_dict["path"]
    repo = ret_dict["repo"]
    ret_dict["zipped"] = gen_path_link(path, repo.name)

    return render_to_response("view_trash_file.html", ret_dict, context_instance=RequestContext(request))
开发者ID:sonicby,项目名称:seahub,代码行数:19,代码来源:file.py


示例11: view_trash_file

def view_trash_file(request, repo_id):
    ret_dict = {}
    view_history_file_common(request, repo_id, ret_dict)
    if not request.user_perm:
        return render_permission_error(request, _(u'Unable to view file'))

    basedir = request.GET.get('base', '')
    if not basedir:
        raise Http404
    days = show_delete_days(request)
    ret_dict['basedir'] = basedir
    ret_dict['days'] = days
    
    # generate file path navigator
    path = ret_dict['path']
    repo = ret_dict['repo']
    ret_dict['zipped'] = gen_path_link(path, repo.name)

    return render_to_response('view_trash_file.html', ret_dict,
                              context_instance=RequestContext(request), )
开发者ID:viktorlindgren,项目名称:seahub,代码行数:20,代码来源:file.py


示例12: draft

def draft(request, pk):
    d = get_object_or_404(Draft, pk=pk)

    # check perm
    uuid = FileUUIDMap.objects.get_fileuuidmap_by_uuid(d.origin_file_uuid)
    origin_repo_id = d.origin_repo_id
    permission = check_folder_permission(request, origin_repo_id, '/')
    if not permission:
        return render_permission_error(request, _(u'Permission denied.'))

    origin_file_path = posixpath.join(uuid.parent_path, uuid.filename)
    origin_file = seafile_api.get_file_id_by_path(origin_repo_id, origin_file_path)
    origin_file_exists = True
    if not origin_file:
        origin_file_exists = False

    draft_file = seafile_api.get_file_id_by_path(origin_repo_id, d.draft_file_path)
    draft_file_exists = True
    if not draft_file:
        draft_file_exists = False

    draft_file_name = os.path.basename(d.draft_file_path)

    author_info = user_to_dict(d.username, avatar_size=32)

    return render(request, "draft.html", {
        "draft_id": d.id,
        "draft_repo_id": origin_repo_id,
        "draft_origin_file_path": origin_file_path,
        "draft_file_path": d.draft_file_path,
        "draft_file_name": draft_file_name,
        "permission": permission,
        "author": author_info['user_name'],
        "author_avatar_url": author_info['avatar_url'],
        "origin_file_exists": origin_file_exists,
        "draft_file_exists": draft_file_exists,
        "draft_status": d.status,
        "publish_file_version": d.publish_file_version,
        "origin_file_version": d.origin_file_version
    })
开发者ID:haiwen,项目名称:seahub,代码行数:40,代码来源:views.py


示例13: group_remove

def group_remove(request, group_id):
    """
    Remove group from groupadmin page. Only system admin can perform this
    operation.
    """
    # Check whether user is system admin.
    if not request.user.is_staff:
        return render_permission_error(request, _(u'Only administrators can delete the group.'))
        
    # Request header may missing HTTP_REFERER, we need to handle that case.
    next = request.META.get('HTTP_REFERER', None)
    if not next:
        next = SITE_ROOT

    try:
        group_id_int = int(group_id)
    except ValueError:
        return HttpResponseRedirect(next)

    try:
        ccnet_threaded_rpc.remove_group(group_id_int, request.user.username)
        seafserv_threaded_rpc.remove_repo_group(group_id_int, None)
    except SearpcError, e:
        return render_error(request, _(e.msg))
开发者ID:chuyskywalker,项目名称:seahub,代码行数:24,代码来源:views.py


示例14: view_file

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)
#.........这里部分代码省略.........
开发者ID:vikingliu,项目名称:seahub,代码行数:101,代码来源:file.py


示例15: org_repo_share

def org_repo_share(request, url_prefix):
    """
    Share org repo to members or groups in current org.
    """
    if request.method != "POST":
        raise Http404

    org = get_user_current_org(request.user.username, url_prefix)
    if not org:
        return HttpResponseRedirect(reverse(myhome))

    form = RepoShareForm(request.POST)
    if not form.is_valid():
        # TODO: may display error msg on form
        raise Http404

    email_or_group = form.cleaned_data["email_or_group"]
    repo_id = form.cleaned_data["repo_id"]
    permission = form.cleaned_data["permission"]
    from_email = request.user.username

    # Test whether user is the repo owner
    if not validate_org_repo_owner(org.org_id, repo_id, request.user.username):
        return render_permission_error(
            request,
            _(u"Only the owner of this library has permission to share it."),
            extra_ctx={"org": org, "base_template": "org_base.html"},
        )

    share_to_list = string2list(email_or_group)
    for share_to in share_to_list:
        if share_to == "all":
            """ Share to public """

            try:
                seafserv_threaded_rpc.set_org_inner_pub_repo(org.org_id, repo_id, permission)
            except:
                msg = _(u"Failed to share to all members")
                messages.add_message(request, messages.ERROR, msg)
                continue

            msg = _(u'Shared to all members successfully, you can go check it at <a href="%s">Share</a>.') % (
                reverse("org_shareadmin", args=[org.url_prefix])
            )
            messages.add_message(request, messages.INFO, msg)
        elif share_to.find("@") == -1:
            """ Share repo to group """
            # TODO: if we know group id, then we can simplly call group_share_repo
            group_name = share_to

            # Get all org groups.
            groups = get_org_groups(org.org_id, -1, -1)
            find = False
            for group in groups:
                # for every group that user joined, if group name and
                # group creator matchs, then has finded the group
                if group.props.group_name == group_name:
                    seafserv_threaded_rpc.add_org_group_repo(repo_id, org.org_id, group.id, from_email, permission)
                    find = True
                    msg = _(
                        u'Shared to %(group)s successfully,you can go check it at <a href="%(share)s">Share</a>.'
                    ) % {"group": group_name, "share": reverse("org_shareadmin", args=[org.url_prefix])}

                    messages.add_message(request, messages.INFO, msg)
                    break
            if not find:
                msg = _(u"Failed to share to %s.") % group_name
                messages.add_message(request, messages.ERROR, msg)
        else:
            """ Share repo to user """
            # Test whether share_to is in this org
            if not org_user_exists(org.org_id, share_to):
                msg = _(u"Failed to share to %s: this user does not exist in the organization.") % share_to
                messages.add_message(request, messages.ERROR, msg)
                continue

            # Record share info to db.
            try:
                seafserv_threaded_rpc.add_share(repo_id, from_email, share_to, permission)
                msg = _(
                    u'Shared to %(share_to)s successfully,you can go check it at <a href="%(share)s">Share</a>.'
                ) % {"share_to": share_to, "share": reverse("org_shareadmin", args=[org.url_prefix])}
                messages.add_message(request, messages.INFO, msg)
            except SearpcError, e:
                msg = _(u"Failed to share to %s.") % share_to
                messages.add_message(request, messages.ERROR, msg)
                continue
开发者ID:weixu8,项目名称:seahub,代码行数:87,代码来源:views.py


示例16: view_file

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:
#.........这里部分代码省略.........
开发者ID:sonicby,项目名称:seahub,代码行数:101,代码来源:file.py


示例17: file_edit

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))
开发者ID:viktorlindgren,项目名称:seahub,代码行数:85,代码来源:file.py


示例18: view_file

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.    
#.........这里部分代码省略.........
开发者ID:viktorlindgren,项目名称:seahub,代码行数:101,代码来源:file.py


示例19: share_repo

def share_repo(request):
    """
    Handle repo share request
    """
    if request.method != 'POST':
        raise Http404
    
    form = RepoShareForm(request.POST)
    if not form.is_valid():
        # TODO: may display error msg on form 
        raise Http404
    
    email_or_group = form.cleaned_data['email_or_group']
    repo_id = form.cleaned_data['repo_id']
    permission = form.cleaned_data['permission']
    from_email = request.user.username

    repo = get_repo(repo_id)
    if not repo:
        raise Http404

    is_encrypted = True if repo.encrypted else False
        
    # Test whether user is the repo owner.
    if not validate_owner(request, repo_id):
        return render_permission_error(request, _(u'Only the owner of the library has permission to share it.'))
    
    to_email_list = string2list(email_or_group)
    for to_email in to_email_list:
        if to_email == 'all':
            ''' Share to public '''

            # ignore 'all' if we're running in cloud mode
            if not CLOUD_MODE:
                try:
                    seafserv_threaded_rpc.set_inner_pub_repo(repo_id, permission)
                except:
                    msg = _(u'Failed to share to all members')
                    message.add_message(request, message.ERROR, msg)
                    continue

                msg = _(u'Shared to all members successfully, go check it at <a href="%s">Share</a>.') % \
                    (reverse('share_admin'))
                messages.add_message(request, messages.INFO, msg)
                
        elif to_email.find('@') == -1:
            ''' Share repo to group '''
            # TODO: if we know group id, then we can simplly call group_share_repo
            group_name = to_email

            # get all personal groups
            groups = get_personal_groups(-1, -1)
            find = False
            for group in groups:
                # for every group that user joined, if group name matchs,
                # then has find the group
                if group.props.group_name == group_name:
                    from seahub.group.views import group_share_repo
                    group_share_repo(request, repo_id, int(group.props.id),
                                     from_email, permission)
                    find = True
                    msg = _(u'Shared to %(group)s successfully,go check it at <a href="%(share)s">Share</a>.') % \
                            {'group':group_name, 'share':reverse('share_admin')}
                    
                    messages.add_message(request, messages.INFO, msg)
                    break
            if not find:
                msg = _(u'Failed to share to %s,as it does not exists.') % group_name
                messages.add_message(request, messages.ERROR, msg)
        else:
            ''' Share repo to user '''
            # Add email to contacts.
            mail_sended.send(sender=None, user=request.user.username,
                             email=to_email)

            if not is_registered_user(to_email):
                # Generate shared link and send mail if user has not registered.
                # kwargs = {'repo_id': repo_id,
                #           'repo_owner': from_email,
                #           'anon_email': to_email,
                #           'is_encrypted': is_encrypted,
                #           }
                # anonymous_share(request, **kwargs)
                msg = _(u'Failed to share to %s, as the email is not registered.') % to_email
                messages.add_message(request, messages.ERROR, msg)
                continue
            else:
                # Record share info to db.
                try:
                    seafserv_threaded_rpc.add_share(repo_id, from_email, to_email,
                                                    permission)
                except SearpcError, e:
                    msg = _(u'Failed to share to %s .') % to_email
                    messages.add_message(request, messages.ERROR, msg)
                    continue

                msg = _(u'Shared to %(email)s successfully,go check it at <a href="%(share)s">Share</a>.') % \
                        {'email':to_email, 'share':reverse('share_admin')}
                messages.add_message(request, messages.INFO, msg)
开发者ID:chuyskywalker,项目名称:seahub,代码行数:99,代码来源:views.py


示例20: file_edit

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.send_html_email函数代码示例发布时间:2022-05-27
下一篇:
Python utils.render_error函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap