Ejemplo n.º 1
0
    def _get_events_inner(ev_session, username, start, limit):
        '''Read events from seafevents database, and remove events that are
        no longer valid

        Return 'limit' events or less than 'limit' events if no more events remain
        '''
        valid_events = []
        next_start = start
        while True:
            events = seafevents.get_user_events(ev_session, username,
                                                next_start, limit)
            if not events:
                break

            for ev in events:
                if ev.etype == 'repo-update':
                    repo = get_repo(ev.repo_id)
                    if not repo:
                        # delete the update event for repo which has been deleted
                        seafevents.delete_event(ev_session, ev.uuid)
                        continue
                    if repo.encrypted:
                        repo.password_set = seafserv_rpc.is_passwd_set(repo.id, username)
                    ev.repo = repo
                    ev.commit = seafserv_threaded_rpc.get_commit(repo.id, repo.version, ev.commit_id)

                valid_events.append(ev)
                if len(valid_events) == limit:
                    break

            if len(valid_events) == limit:
                break            
            next_start = next_start + len(valid_events)

        return valid_events
Ejemplo n.º 2
0
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, '']))
Ejemplo n.º 3
0
def calculate_repo_info(repo_list, username):
    """
    Get some info for repo.

    """
    for repo in repo_list:
        try:
            commit = get_commits(repo.id, 0, 1)[0]
            repo.latest_modify = commit.ctime
            repo.root = commit.root_id
            repo.size = seafserv_threaded_rpc.server_repo_size(repo.id)
            if not repo.size :
                repo.size = 0;

            password_need = False
            if repo.encrypted:
                try:
                    ret = seafserv_rpc.is_passwd_set(repo.id, username)
                    if ret != 1:
                        password_need = True
                except SearpcErroe, e:
                    pass
            repo.password_need = password_need
        except Exception,e:
            repo.latest_modify = 0
            repo.commit = None
            repo.size = -1
            repo.password_need = None
Ejemplo n.º 4
0
    def _get_events_inner(ev_session, username, start, limit):
        '''Read events from seafevents database, and remove events that are
        no longer valid

        Return 'limit' events or less than 'limit' events if no more events remain
        '''
        valid_events = []
        next_start = start
        while True:
            events = seafevents.get_user_events(ev_session, username,
                                                next_start, limit)
            if not events:
                break

            for ev in events:
                if ev.etype == 'repo-update':
                    repo = get_repo(ev.repo_id)
                    if not repo:
                        # delete the update event for repo which has been deleted
                        seafevents.delete_event(ev_session, ev.uuid)
                        continue
                    if repo.encrypted:
                        repo.password_set = seafserv_rpc.is_passwd_set(repo.id, username)
                    ev.repo = repo
                    ev.commit = seafserv_threaded_rpc.get_commit(ev.commit_id)

                valid_events.append(ev)
                if len(valid_events) == limit:
                    break

            if len(valid_events) == limit:
                break            
            next_start = next_start + len(valid_events)

        return valid_events
Ejemplo n.º 5
0
    def _get_events_inner(ev_session, username, start, org_id=None):
        '''Read 11 events from seafevents database, and remove events that are
        no longer valid

        '''
        if org_id == None:
            events = seafevents.get_user_events(ev_session, username, start, start + 11)
        else:
            events = seafevents.get_org_user_events(ev_session, \
                                    org_id, username, start, start + 11)
        total = len(events)
        valid_events = []
        for ev in events:
            if ev.etype == 'repo-update':
                repo = get_repo(ev.repo_id)
                if not repo:
                    # delete the update event for repo which has been deleted
                    seafevents.delete_event(ev_session, ev.uuid)
                    continue
                if repo.encrypted:
                    repo.password_set = seafserv_rpc.is_passwd_set(repo.id, username)
                ev.repo = repo
                ev.commit = seafserv_threaded_rpc.get_commit(ev.commit_id)

            valid_events.append(ev)

        return total, valid_events
Ejemplo n.º 6
0
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, '']))
Ejemplo n.º 7
0
 def get_org_user_events(org_id, username, start):
     ev_session = SeafEventsSession()
     events = seafevents.get_org_user_events(ev_session, \
                         org_id, username, start, start + 11)
     ev_session.close()
     for ev in events:
         if ev.etype == 'repo-update':
             repo = get_repo(ev.repo_id)
             if not repo:
                 ev.etype = 'dummy'
                 continue
             if repo.encrypted:
                 repo.password_set = seafserv_rpc.is_passwd_set(repo.id, username)
             ev.repo = repo
             ev.commit = seafserv_threaded_rpc.get_commit(ev.commit_id)
     return events
Ejemplo n.º 8
0
def repo_revert_history(request, repo_id):

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

    repo = get_repo(repo_id)
    if not repo:
        messages.error(request, _("Library does not exist"))
        return HttpResponseRedirect(next)

    # perm check
    perm = check_folder_permission(request, repo_id, '/')
    username = request.user.username
    repo_owner = seafile_api.get_repo_owner(repo.id)

    if perm is None or repo_owner != username:
        messages.error(request, _("Permission denied"))
        return HttpResponseRedirect(next)

    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:
            reverse_url = HASH_URLS["VIEW_COMMON_LIB_DIR"] % {
                'repo_id': repo_id,
                'path': ''
            }
            return HttpResponseRedirect(reverse_url)
Ejemplo n.º 9
0
def check_repo_access_permission(request, repo):
    if not can_access_repo(request, repo.id):
        return api_error(status.HTTP_403_FORBIDDEN, 'Forbid to access this repo.')

    password_set = False
    if repo.encrypted:
        try:
            ret = seafserv_rpc.is_passwd_set(repo.id, request.user.username)
            if ret == 1:
                password_set = True
        except SearpcError, e:
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
                             "SearpcError:" + e.msg)

        if not password_set:
            password = request.REQUEST.get('password', default=None)
            if not password:
                return api_error(HTTP_440_REPO_PASSWD_REQUIRED,
                                 'Repo password is needed.')

            return set_repo_password(request, repo, password)
Ejemplo n.º 10
0
def check_repo_access_permission(request, repo):
    if not can_access_repo(request, repo.id):
        return api_error(status.HTTP_403_FORBIDDEN, 'Forbid to access this repo.')

    password_set = False
    if repo.encrypted:
        try:
            ret = seafserv_rpc.is_passwd_set(repo.id, request.user.username)
            if ret == 1:
                password_set = True
        except SearpcError, e:
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
                             "SearpcError:" + e.msg)

        if not password_set:
            password = request.REQUEST.get('password', default=None)
            if not password:
                return api_error(HTTP_440_REPO_PASSWD_REQUIRED,
                                 'Repo password is needed.')

            return set_repo_password(request, repo, password)
Ejemplo n.º 11
0
def check_repo_access_permission(request, repo):
    if not repo:
        return api_error(request, '404')

    if not can_access_repo(request, repo.id):
        return api_error(request, '403')

    password_set = False
    if repo.encrypted:
        try:
            ret = seafserv_rpc.is_passwd_set(repo.id, request.user.username)
            if ret == 1:
                password_set = True
        except SearpcError, e:
            return api_error(request, '405', "SearpcError:" + e.msg)

        if not password_set:
            password = request.REQUEST.get('password', default=None)
            if not password:
                return api_error(request, '409')

            return set_repo_password(request, repo, password)
Ejemplo n.º 12
0
    def _get_events(username, start, org_id=None):
        ev_session = SeafEventsSession()
        if org_id == None:
            events = seafevents.get_user_events(ev_session, username, start, start + 11)
        else:
            events = seafevents.get_org_user_events(ev_session, \
                                    org_id, username, start, start + 11)
        valid_events = []
        ev_session.close()
        for ev in events:
            if ev.etype == 'repo-update':
                repo = get_repo(ev.repo_id)
                if not repo:
                    continue
                if repo.encrypted:
                    repo.password_set = seafserv_rpc.is_passwd_set(repo.id, username)
                ev.repo = repo
                ev.commit = seafserv_threaded_rpc.get_commit(ev.commit_id)

            valid_events.append(ev)

        return valid_events
Ejemplo n.º 13
0
def repo_revert_history(request, repo_id):

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

    repo = get_repo(repo_id)
    if not repo:
        messages.error(request, _("Library does not exist"))
        return HttpResponseRedirect(next)

    # perm check
    perm = check_folder_permission(request, repo_id, '/')
    username = request.user.username
    repo_owner = seafile_api.get_repo_owner(repo.id)

    if perm is None or repo_owner != username:
        messages.error(request, _("Permission denied"))
        return HttpResponseRedirect(next)

    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, '']))
Ejemplo n.º 14
0
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))
Ejemplo n.º 15
0
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),
    )
Ejemplo n.º 16
0
def file_edit_submit(request, repo_id):
    content_type = 'application/json; charset=utf-8'
    def error_json(error_msg=_(u'Internal Error'), op=None):
        return HttpResponse(json.dumps({'error': error_msg, 'op': op}),
                            status=400,
                            content_type=content_type)

    if get_user_permission(request, repo_id) != 'rw':
        return error_json(_(u'Permission denied'))
        
    repo = get_repo(repo_id)
    if not repo:
        return error_json(_(u'The library does not exist.'))
    if repo.encrypted:
        repo.password_set = seafserv_rpc.is_passwd_set(repo_id, request.user.username)
        if not repo.password_set:
            return error_json(_(u'The library is encrypted.'), 'decrypt')

    content = request.POST.get('content')
    encoding = request.POST.get('encoding')
    path = request.GET.get('p')

    if content is None or not path or encoding not in ["gbk", "utf-8"]:
        return error_json(_(u'Invalid arguments'))
    head_id = request.GET.get('head', None)

    content = content.encode(encoding)

    # first dump the file content to a tmp file, then update the file
    fd, tmpfile = mkstemp()
    def remove_tmp_file():
        try:
            os.remove(tmpfile)
        except:
            pass

    try:
        bytesWritten = os.write(fd, content)
    except:
        bytesWritten = -1
    finally:
        os.close(fd)

    if bytesWritten != len(content):
        remove_tmp_file()
        return error_json()

    if request.GET.get('from', '') == 'wiki_page_edit':
        try:
            gid = int(request.GET.get('gid', 0))
        except ValueError:
            gid = 0
        wiki_name = os.path.splitext(os.path.basename(path))[0]
        next = reverse('group_wiki', args=[gid, wiki_name])
    elif request.GET.get('from', '') == 'wiki_page_new':
        try:
            gid = int(request.GET.get('gid', 0))
        except ValueError:
            gid = 0
        next = reverse('group_wiki_pages', args=[gid])
    elif request.GET.get('from', '') == 'personal_wiki_page_edit':
        wiki_name = os.path.splitext(os.path.basename(path))[0]
        next = reverse('personal_wiki', args=[wiki_name])
    elif request.GET.get('from', '') == 'personal_wiki_page_new':
        next = reverse('personal_wiki_pages')
    else:
        next = reverse('repo_view_file', args=[repo_id]) + '?p=' + urlquote(path)

    parent_dir = os.path.dirname(path).encode('utf-8')
    filename = os.path.basename(path).encode('utf-8')
    try:
        seafserv_threaded_rpc.put_file(repo_id, tmpfile, parent_dir,
                                 filename, request.user.username, head_id)
        remove_tmp_file()
        return HttpResponse(json.dumps({'href': next}),
                            content_type=content_type)
    except SearpcError, e:
        remove_tmp_file()
        return error_json(str(e))
Ejemplo n.º 17
0
def file_edit_submit(request, repo_id):
    content_type = "application/json; charset=utf-8"

    def error_json(error_msg=_(u"Internal Error"), op=None):
        return HttpResponse(json.dumps({"error": error_msg, "op": op}), status=400, content_type=content_type)

    if get_user_permission(request, repo_id) != "rw":
        return error_json(_(u"Permission denied"))

    repo = get_repo(repo_id)
    if not repo:
        return error_json(_(u"The library does not exist."))
    if repo.encrypted:
        repo.password_set = seafserv_rpc.is_passwd_set(repo_id, request.user.username)
        if not repo.password_set:
            return error_json(_(u"The library is encrypted."), "decrypt")

    content = request.POST.get("content")
    encoding = request.POST.get("encoding")
    path = request.GET.get("p")

    if content is None or not path or encoding not in ["gbk", "utf-8"]:
        return error_json(_(u"Invalid arguments"))
    head_id = request.GET.get("head", None)

    content = content.encode(encoding)

    # first dump the file content to a tmp file, then update the file
    fd, tmpfile = tempfile.mkstemp()

    def remove_tmp_file():
        try:
            os.remove(tmpfile)
        except:
            pass

    try:
        bytesWritten = os.write(fd, content)
    except:
        bytesWritten = -1
    finally:
        os.close(fd)

    if bytesWritten != len(content):
        remove_tmp_file()
        return error_json()

    if request.GET.get("from", "") == "wiki_page_edit":
        try:
            gid = int(request.GET.get("gid", 0))
        except ValueError:
            gid = 0
        wiki_name = os.path.splitext(os.path.basename(path))[0]
        next = reverse("group_wiki", args=[gid, wiki_name])
    elif request.GET.get("from", "") == "wiki_page_new":
        try:
            gid = int(request.GET.get("gid", 0))
        except ValueError:
            gid = 0
        next = reverse("group_wiki_pages", args=[gid])
    else:
        next = reverse("repo_view_file", args=[repo_id]) + "?p=" + urlquote(path)

    parent_dir = os.path.dirname(path).encode("utf-8")
    filename = os.path.basename(path).encode("utf-8")
    try:
        seafserv_threaded_rpc.put_file(repo_id, tmpfile, parent_dir, filename, request.user.username, head_id)
        remove_tmp_file()
        return HttpResponse(json.dumps({"href": next}), content_type=content_type)
    except SearpcError, e:
        remove_tmp_file()
        return error_json(str(e))