Exemple #1
0
    def put(self, request, repo_id):
        """ Copy a single file/folder to other place.
        """

        # check parameter for src
        path = request.GET.get('path', None)
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        try:
            dirent = seafile_api.get_dirent_by_path(repo_id, path)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if not dirent:
            error_msg = 'File or folder %s not found.' % path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if path == '/':
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # normalize path to '/1/2/3' format
        # NOT ends with '/'
        path = normalize_file_path(path)

        # now get `src_dir` and `obj_name` according to normalized path
        src_repo_id = repo_id
        src_dir = os.path.dirname(path)
        src_obj_name = os.path.basename(path)

        # check parameter for dst
        dst_repo_id = request.data.get('dst_repo_id', src_repo_id)
        if dst_repo_id != src_repo_id and not seafile_api.get_repo(dst_repo_id):
            error_msg = 'Library %s not found.' % dst_repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        dst_dir = request.data.get('dst_dir', '/')
        if dst_dir != '/':
            dst_dir = normalize_dir_path(dst_dir)
            if not seafile_api.get_dir_id_by_path(dst_repo_id, dst_dir):
                error_msg = 'Folder %s not found.' % dst_dir
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # copy file
        username = request.user.username
        dst_obj_name = check_filename_with_rename(dst_repo_id, dst_dir,
                src_obj_name)
        try:
            seafile_api.copy_file(src_repo_id, src_dir, src_obj_name, dst_repo_id,
                      dst_dir, dst_obj_name, username, need_progress=0, synchronous=1)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({'success': True, 'dst_item_name': dst_obj_name})
Exemple #2
0
def personal_wiki(request, page_name="home"):
    username = request.user.username
    wiki_exists = True
    try:
        content, repo, dirent = get_personal_wiki_page(username, page_name)
    except WikiDoesNotExist:
        wiki_exists = False
        owned_repos = seafile_api.get_owned_repo_list(username)
        owned_repos = [r for r in owned_repos if not r.encrypted]
        return render_to_response("wiki/personal_wiki.html", {
            "wiki_exists": wiki_exists,
            "owned_repos": owned_repos,
        },
                                  context_instance=RequestContext(request))
    except WikiPageMissing:
        repo = get_personal_wiki_repo(username)
        filename = page_name_to_file_name(clean_page_name(page_name))
        if not seaserv.post_empty_file(repo.id, "/", filename, username):
            return render_error(
                request, _("Failed to create wiki page. Please retry later."))
        return HttpResponseRedirect(reverse('personal_wiki', args=[page_name]))
    else:
        url_prefix = reverse('personal_wiki', args=[])

        # fetch file modified time and modifier
        path = '/' + dirent.obj_name
        try:
            dirent = seafile_api.get_dirent_by_path(repo.id, path)
            if dirent:
                latest_contributor, last_modified = dirent.modifier, dirent.mtime
            else:
                latest_contributor, last_modified = None, 0
        except SearpcError as e:
            logger.error(e)
            latest_contributor, last_modified = None, 0

        wiki_index_exists = True
        index_pagename = 'index'
        index_content = None
        try:
            index_content, index_repo, index_dirent = get_personal_wiki_page(
                username, index_pagename)
        except (WikiDoesNotExist, WikiPageMissing) as e:
            wiki_index_exists = False

        return render_to_response(
            "wiki/personal_wiki.html", {
                "wiki_exists": wiki_exists,
                "content": content,
                "page": os.path.splitext(dirent.obj_name)[0],
                "last_modified": last_modified,
                "latest_contributor": latest_contributor or _("Unknown"),
                "path": path,
                "repo_id": repo.id,
                "search_repo_id": repo.id,
                "search_wiki": True,
                "wiki_index_exists": wiki_index_exists,
                "index_content": index_content,
            },
            context_instance=RequestContext(request))
Exemple #3
0
def get_tagged_files(repo, repo_tag_id):

    # get tagged files
    tagged_file_objs = FileTags.objects.filter(
        repo_tag__id=repo_tag_id).select_related('repo_tag', 'file_uuid')

    tagged_files = defaultdict(list)
    for tagged_file_obj in tagged_file_objs:
        parent_path = tagged_file_obj.file_uuid.parent_path
        filename = tagged_file_obj.file_uuid.filename
        file_path = posixpath.join(parent_path, filename)

        tagged_file = dict()
        file_obj = seafile_api.get_dirent_by_path(repo.store_id, file_path)
        tagged_file["parent_path"] = parent_path
        tagged_file["filename"] = filename
        tagged_file["size"] = file_obj.size
        tagged_file["last_modified"] = timestamp_to_isoformat_timestr(
            file_obj.mtime)
        tagged_file["modifier_email"] = file_obj.modifier
        tagged_file["modifier_contact_email"] = email2contact_email(
            file_obj.modifier)
        tagged_file["modifier_name"] = email2nickname(file_obj.modifier)
        tagged_files["tagged_files"].append(tagged_file)

    return tagged_files
Exemple #4
0
    def get_file_info(self, username, repo_id, file_path):

        repo = seafile_api.get_repo(repo_id)
        file_obj = seafile_api.get_dirent_by_path(repo_id, file_path)
        file_name = file_obj.obj_name
        file_size = file_obj.size

        can_preview, error_msg = can_preview_file(file_name, file_size, repo)
        can_edit, error_msg  = can_edit_file(file_name, file_size, repo)

        try:
            is_locked, locked_by_me = check_file_lock(repo_id, file_path, username)
        except Exception as e:
            logger.error(e)
            is_locked = False

        file_info = {
            'type': 'file',
            'repo_id': repo_id,
            'parent_dir': os.path.dirname(file_path),
            'obj_name': file_name,
            'obj_id': file_obj.obj_id,
            'size': file_size,
            'mtime': timestamp_to_isoformat_timestr(file_obj.mtime),
            'is_locked': is_locked,
            'can_preview': can_preview,
            'can_edit': can_edit,
        }

        return file_info
Exemple #5
0
    def put(self, request, repo_id):
        """ Copy a single file/folder to other place.
        """

        # check parameter for src
        path = request.GET.get('path', None)
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        try:
            dirent = seafile_api.get_dirent_by_path(repo_id, path)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if not dirent:
            error_msg = 'File or folder %s not found.' % path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if path == '/':
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # normalize path to '/1/2/3' format
        # NOT ends with '/'
        path = normalize_file_path(path)

        # now get `src_dir` and `obj_name` according to normalized path
        src_repo_id = repo_id
        src_dir = os.path.dirname(path)
        src_obj_name = os.path.basename(path)

        # check parameter for dst
        dst_repo_id = request.data.get('dst_repo_id', src_repo_id)
        if dst_repo_id != src_repo_id and not seafile_api.get_repo(dst_repo_id):
            error_msg = 'Library %s not found.' % dst_repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        dst_dir = request.data.get('dst_dir', '/')
        if dst_dir != '/':
            dst_dir = normalize_dir_path(dst_dir)
            if not seafile_api.get_dir_id_by_path(dst_repo_id, dst_dir):
                error_msg = 'Folder %s not found.' % dst_dir
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # copy file
        username = request.user.username
        dst_obj_name = check_filename_with_rename(dst_repo_id, dst_dir,
                src_obj_name)
        try:
            seafile_api.copy_file(src_repo_id, src_dir, src_obj_name, dst_repo_id,
                      dst_dir, dst_obj_name, username, need_progress=0, synchronous=1)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({'success': True, 'dst_item_name': dst_obj_name})
Exemple #6
0
def search_files(repos_map, search_path, keyword, obj_desc, start, size, org_id=None):
    # search file
    if len(repos_map) > 1:
        search_path = None
    files_found, total = es_search(repos_map, search_path, keyword, obj_desc, start, size)

    result = []
    for f in files_found:
        repo = repos_map.get(f['repo_id'].encode('UTF-8'), None)
        if not repo:
            continue

        if repo.origin_path:
            if not f['fullpath'].startswith(repo.origin_path):
                # this operation will reduce the result items, but it will not happen now
                continue
            else:
                f['repo_id'] = repo.repo_id
                f['fullpath'] = f['fullpath'].split(repo.origin_path)[-1]

        if not repo.owner:
            if org_id:
                repo.owner = seafile_api.get_org_repo_owner(repo.id)
            else:
                repo.owner = seafile_api.get_repo_owner(repo.id)

        # if match multiple files, keep the lookup only once.
        if not hasattr(repo, 'owner_nickname') or not repo.owner_nickname:
            repo.owner_nickname = email2nickname(repo.owner)

        if not hasattr(repo, 'owner_contact_email') or not repo.owner_contact_email:
            repo.owner_contact_email = email2contact_email(repo.owner)

        if f['fullpath'] == '/':
            f['last_modified_by'] = repo.last_modifier
            f['last_modified'] = repo.last_modify
            f['size'] = repo.size
        else:
            try:
                dirent = seafile_api.get_dirent_by_path(f['repo_id'], f['fullpath'])
            except Exception as e:
                logger.error(e)
                continue

            if not dirent:
                continue

            f['last_modified_by'] = dirent.modifier
            f['last_modified'] = dirent.mtime
            f['size'] = dirent.size

        f['repo'] = repo
        f['repo_name'] = repo.name
        f['repo_owner_email'] = repo.owner
        f['repo_owner_name'] = repo.owner_nickname
        f['repo_owner_contact_email'] = repo.owner_contact_email

        result.append(f)

    return result, total
Exemple #7
0
    def get_file_info(self, username, repo_id, file_path):

        repo = seafile_api.get_repo(repo_id)
        file_obj = seafile_api.get_dirent_by_path(repo_id, file_path)
        file_name = file_obj.obj_name
        file_size = file_obj.size

        can_preview, error_msg = can_preview_file(file_name, file_size, repo)
        can_edit, error_msg  = can_edit_file(file_name, file_size, repo)

        try:
            is_locked, locked_by_me = check_file_lock(repo_id, file_path, username)
        except Exception as e:
            logger.error(e)
            is_locked = False

        file_info = {
            'type': 'file',
            'repo_id': repo_id,
            'parent_dir': os.path.dirname(file_path),
            'obj_name': file_name,
            'obj_id': file_obj.obj_id,
            'size': file_size,
            'mtime': timestamp_to_isoformat_timestr(file_obj.mtime),
            'is_locked': is_locked,
            'can_preview': can_preview,
            'can_edit': can_edit,
        }

        return file_info
Exemple #8
0
def get_tagged_files(repo, repo_tag_id):

    # get tagged files
    tagged_file_objs = FileTags.objects.filter(
        repo_tag__id=repo_tag_id).select_related('repo_tag', 'file_uuid')

    tagged_files = defaultdict(list)
    for tagged_file_obj in tagged_file_objs:
        file_tag_id = tagged_file_obj.pk
        parent_path = tagged_file_obj.file_uuid.parent_path
        filename = tagged_file_obj.file_uuid.filename
        file_path = posixpath.join(parent_path, filename)

        tagged_file = dict()
        file_obj = seafile_api.get_dirent_by_path(repo.store_id, file_path)
        if not file_obj:
            exception = "Can't find tagged file. Repo_id: %s, Path: %s." % (repo.id, file_path)
            logger.warning(exception)
            tagged_file["file_deleted"] = True
            tagged_file["file_tag_id"] = file_tag_id
            tagged_file["filename"] = filename
            tagged_files["tagged_files"].append(tagged_file)
            continue

        tagged_file["parent_path"] = parent_path
        tagged_file["filename"] = filename
        tagged_file["size"] = file_obj.size
        tagged_file["mtime"] = file_obj.mtime
        tagged_file["last_modified"] = timestamp_to_isoformat_timestr(file_obj.mtime)
        tagged_file["modifier_email"] = file_obj.modifier
        tagged_file["modifier_contact_email"] = email2contact_email(file_obj.modifier)
        tagged_file["modifier_name"] = email2nickname(file_obj.modifier)
        tagged_files["tagged_files"].append(tagged_file)

    return tagged_files
Exemple #9
0
    def get(self, request, repo_id):
        """ get info of a single file/folder in a library
        """

        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if not can_view_sys_admin_repo(repo):
            error_msg = 'Feature disabled.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        path = request.GET.get('path', None)
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if path[0] != '/':
            path = '/' + path

        try:
            dirent = seafile_api.get_dirent_by_path(repo_id, path)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if not dirent:
            error_msg = 'file/folder %s not found.' % path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if stat.S_ISDIR(dirent.mode):
            is_file = False
        else:
            is_file = True

        username = request.user.username
        if is_file and request.GET.get('dl', '0') == '1':

            token = seafile_api.get_fileserver_access_token(repo_id,
                                                            dirent.obj_id,
                                                            'download',
                                                            username,
                                                            use_onetime=True)

            if not token:
                error_msg = 'Internal Server Error'
                return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
                                 error_msg)

            dl_url = gen_file_get_url(token, dirent.obj_name)
            send_file_access_msg(request, repo, path, 'web')
            return Response({'download_url': dl_url})

        dirent_info = get_dirent_info(dirent)

        return Response(dirent_info)
Exemple #10
0
def personal_wiki(request, page_name="home"):
    username = request.user.username
    wiki_exists = True
    try:
        content, repo, dirent = get_personal_wiki_page(username, page_name)
    except WikiDoesNotExist:
        wiki_exists = False
        owned_repos = seafile_api.get_owned_repo_list(username)
        owned_repos = [r for r in owned_repos if not r.encrypted]
        return render_to_response("wiki/personal_wiki.html", {
                "wiki_exists": wiki_exists,
                "owned_repos": owned_repos,
                }, context_instance=RequestContext(request))
    except WikiPageMissing:
        repo = get_personal_wiki_repo(username)
        filename = clean_page_name(page_name) + '.md'
        if not seaserv.post_empty_file(repo.id, "/", filename, username):
            return render_error(request, _("Failed to create wiki page. Please retry later."))
        return HttpResponseRedirect(reverse('personal_wiki', args=[page_name]))
    else:
        url_prefix = reverse('personal_wiki', args=[])
        content = convert_wiki_link(content, url_prefix, repo.id, username)
        
        # fetch file modified time and modifier
        path = '/' + dirent.obj_name
        try:
            dirent = seafile_api.get_dirent_by_path(repo.id, path)
            if dirent:
                latest_contributor, last_modified = dirent.modifier, dirent.mtime
            else:
                latest_contributor, last_modified = None, 0
        except SearpcError as e:
            logger.error(e)
            latest_contributor, last_modified = None, 0

        wiki_index_exists = True
        index_pagename = 'index'
        index_content = None
        try:
            index_content, index_repo, index_dirent = get_personal_wiki_page(username, index_pagename)
        except (WikiDoesNotExist, WikiPageMissing) as e:
            wiki_index_exists = False
        else:
            index_content = convert_wiki_link(index_content, url_prefix, index_repo.id, username)

        return render_to_response("wiki/personal_wiki.html", { 
            "wiki_exists": wiki_exists,
            "content": content,
            "page": os.path.splitext(dirent.obj_name)[0],
            "last_modified": last_modified,
            "latest_contributor": latest_contributor or _("Unknown"),
            "path": path,
            "repo_id": repo.id,
            "search_repo_id": repo.id,
            "search_wiki": True,
            "wiki_index_exists": wiki_index_exists,
            "index_content": index_content,
            }, context_instance=RequestContext(request))
Exemple #11
0
def get_share_link_info(fileshare):
    data = {}
    token = fileshare.token

    repo_id = fileshare.repo_id
    try:
        repo = seafile_api.get_repo(repo_id)
    except Exception as e:
        logger.error(e)
        repo = None

    path = fileshare.path
    if path:
        obj_name = '/' if path == '/' else os.path.basename(path.rstrip('/'))
    else:
        obj_name = ''

    if fileshare.expire_date:
        expire_date = datetime_to_isoformat_timestr(fileshare.expire_date)
    else:
        expire_date = ''

    if fileshare.ctime:
        ctime = datetime_to_isoformat_timestr(fileshare.ctime)
    else:
        ctime = ''

    data['username'] = fileshare.username
    data['repo_id'] = repo_id
    data['repo_name'] = repo.repo_name if repo else ''

    data['path'] = path
    data['obj_name'] = obj_name
    data['is_dir'] = True if fileshare.s_type == 'd' else False

    data['token'] = token
    data['link'] = gen_shared_link(token, fileshare.s_type)
    data['view_cnt'] = fileshare.view_cnt
    data['ctime'] = ctime
    data['expire_date'] = expire_date
    data['is_expired'] = fileshare.is_expired()
    data['permissions'] = fileshare.get_permissions()

    data['can_edit'] = False
    if repo and path != '/' and not data['is_dir']:
        dirent = seafile_api.get_dirent_by_path(repo_id, path)
        if dirent:
            try:
                can_edit, error_msg = can_edit_file(obj_name, dirent.size,
                                                    repo)
                data['can_edit'] = can_edit
            except Exception as e:
                logger.error(e)
        else:
            data['can_edit'] = False

    return data
Exemple #12
0
    def get(self, request, repo_id):
        """ get info of a single file/folder in a library
        """

        if not request.user.admin_permissions.can_manage_library():
            return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')

        repo = seafile_api.get_repo(repo_id)

        path = request.GET.get('path', None)
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        path = normalize_file_path(path)

        try:
            dirent = seafile_api.get_dirent_by_path(repo_id, path)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if not dirent:
            error_msg = 'File or folder %s not found.' % path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if stat.S_ISDIR(dirent.mode):
            is_file = False
        else:
            is_file = True

        username = request.user.username
        if is_file and request.GET.get('dl', '0') == '1':

            token = seafile_api.get_fileserver_access_token(
                repo_id,
                dirent.obj_id,
                'download',
                username,
                use_onetime=settings.FILESERVER_TOKEN_ONCE_ONLY)

            if not token:
                error_msg = 'Internal Server Error'
                return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
                                 error_msg)

            dl_url = gen_file_get_url(token, dirent.obj_name)
            send_file_access_msg(request, repo, path, 'web')
            return Response({'download_url': dl_url})

        dirent_info = get_dirent_info(dirent)

        return Response(dirent_info)
Exemple #13
0
    def get(self, request, repo_id):
        """ Get dir info.

        Permission checking:
        1. user with either 'r' or 'rw' permission.
        """

        # parameter check
        path = request.GET.get('path', None)
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        path = normalize_dir_path(path)
        if path == '/':
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # resource check
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        dir_id = seafile_api.get_dir_id_by_path(repo_id, path)
        if not dir_id:
            error_msg = 'Folder %s not found.' % path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission check
        if not check_folder_permission(request, repo_id, path):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        try:
            dir_obj = seafile_api.get_dirent_by_path(repo_id, path)
            count_info = seafile_api.get_file_count_info_by_path(repo_id, path)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        dir_info = {
            'repo_id': repo_id,
            'path': path,
            'name': dir_obj.obj_name,
            'file_count': count_info.file_count,
            'dir_count': count_info.dir_count,
            'size': count_info.size,
            'mtime': timestamp_to_isoformat_timestr(dir_obj.mtime),
        }

        return Response(dir_info)
Exemple #14
0
 def get_related_file(self, r_repo_id, r_file_path, r_uuid):
     related_file = dict()
     related_file["name"] = r_uuid.filename
     related_file["repo_id"] = r_repo_id
     r_repo = seafile_api.get_repo(r_repo_id)
     if not r_repo:
         related_file["repo_name"] = ""
     related_file["repo_name"] = r_repo.name
     related_file["path"] = r_file_path
     file_obj = seafile_api.get_dirent_by_path(r_repo_id, r_file_path)
     related_file["size"] = file_obj.size
     related_file["last_modified"] = timestamp_to_isoformat_timestr(file_obj.mtime)
     return related_file
Exemple #15
0
    def get_dir_info(self, repo_id, dir_path):

        dir_obj = seafile_api.get_dirent_by_path(repo_id, dir_path)
        dir_info = {
            'type': 'dir',
            'repo_id': repo_id,
            'parent_dir': os.path.dirname(dir_path.rstrip('/')),
            'obj_name': dir_obj.obj_name,
            'obj_id': dir_obj.obj_id,
            'mtime': timestamp_to_isoformat_timestr(dir_obj.mtime),
        }

        return dir_info
Exemple #16
0
    def get_dir_info(self, repo_id, dir_path):

        dir_obj = seafile_api.get_dirent_by_path(repo_id, dir_path)
        dir_info = {
            'type': 'dir',
            'repo_id': repo_id,
            'parent_dir': os.path.dirname(dir_path.rstrip('/')),
            'obj_name': dir_obj.obj_name,
            'obj_id': dir_obj.obj_id,
            'mtime': timestamp_to_isoformat_timestr(dir_obj.mtime),
        }

        return dir_info
Exemple #17
0
    def get(self, request, repo_id):
        """ Get dir info.

        Permission checking:
        1. user with either 'r' or 'rw' permission.
        """

        # parameter check
        path = request.GET.get('path', None)
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        path = normalize_dir_path(path)
        if path == '/':
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # resource check
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        dir_id = seafile_api.get_dir_id_by_path(repo_id, path)
        if not dir_id:
            error_msg = 'Folder %s not found.' % path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission check
        if not check_folder_permission(request, repo_id, path):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        try:
            dir_obj = seafile_api.get_dirent_by_path(repo_id, path)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        dir_info = {
            'repo_id': repo_id,
            'path': path,
            'name': dir_obj.obj_name,
            'mtime': timestamp_to_isoformat_timestr(dir_obj.mtime),
        }

        return Response(dir_info)
    def get(self, request, repo_id):
        """ get info of a single file/folder in a library
        """

        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if not can_view_sys_admin_repo(repo):
            error_msg = 'Feature disabled.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        path = request.GET.get('path', None)
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if path[0] != '/':
            path = '/' + path

        try:
            dirent = seafile_api.get_dirent_by_path(repo_id, path)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if not dirent:
            error_msg = 'file/folder %s not found.' % path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if stat.S_ISDIR(dirent.mode):
            is_file = False
        else:
            is_file = True

        username = request.user.username
        if is_file and request.GET.get('dl', '0') == '1':

            token = seafile_api.get_fileserver_access_token(repo_id,
                dirent.obj_id, 'download', username, use_onetime=True)
            dl_url = gen_file_get_url(token, dirent.obj_name)
            send_file_access_msg(request, repo, path, 'web')
            return Response({'download_url': dl_url})

        dirent_info = get_dirent_info(dirent)

        return Response(dirent_info)
Exemple #19
0
    def get_file_info(self, username, repo_id, file_path):

        file_obj = seafile_api.get_dirent_by_path(repo_id, file_path)
        is_locked, locked_by_me = check_file_lock(repo_id, file_path, username)
        file_info = {
            'type': 'file',
            'repo_id': repo_id,
            'parent_dir': os.path.dirname(file_path),
            'obj_name': file_obj.obj_name,
            'obj_id': file_obj.obj_id,
            'size': file_obj.size,
            'mtime': timestamp_to_isoformat_timestr(file_obj.mtime),
            'is_locked': is_locked,
        }

        return file_info
Exemple #20
0
    def get_file_info(self, username, repo_id, file_path):

        file_obj = seafile_api.get_dirent_by_path(repo_id, file_path)
        is_locked, locked_by_me = check_file_lock(repo_id, file_path, username)
        file_info = {
            'type': 'file',
            'repo_id': repo_id,
            'parent_dir': os.path.dirname(file_path),
            'obj_name': file_obj.obj_name,
            'obj_id': file_obj.obj_id,
            'size': file_obj.size,
            'mtime': timestamp_to_isoformat_timestr(file_obj.mtime),
            'is_locked': is_locked,
        }

        return file_info
    def post(self, request, repo_id, format=None):
        """ create file/folder in a library
        """

        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if not can_view_sys_admin_repo(repo):
            error_msg = 'Feature disabled.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        parent_dir = request.GET.get('parent_dir', '/')
        if not parent_dir:
            error_msg = 'parent_dir invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if parent_dir[-1] != '/':
            parent_dir = parent_dir + '/'

        dir_id = seafile_api.get_dir_id_by_path(repo_id, parent_dir)
        if not dir_id:
            error_msg = 'Folder %s not found.' % parent_dir
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        obj_name = request.data.get('obj_name', None)
        if not obj_name or not seafile_api.is_valid_filename(
                repo_id, obj_name):
            error_msg = 'obj_name invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        obj_name = check_filename_with_rename(repo_id, parent_dir, obj_name)

        username = request.user.username
        try:
            seafile_api.post_dir(repo_id, parent_dir, obj_name, username)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        dirent_path = posixpath.join(parent_dir, obj_name)
        dirent = seafile_api.get_dirent_by_path(repo_id, dirent_path)
        dirent_info = get_dirent_info(dirent)

        return Response(dirent_info)
Exemple #22
0
    def get(self, request, repo_id):
        """ get info of a single file/folder in a library
        """

        repo = seafile_api.get_repo(repo_id)

        path = request.GET.get('path', None)
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        path = normalize_file_path(path)

        try:
            dirent = seafile_api.get_dirent_by_path(repo_id, path)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if not dirent:
            error_msg = 'File or folder %s not found.' % path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if stat.S_ISDIR(dirent.mode):
            is_file = False
        else:
            is_file = True

        username = request.user.username
        if is_file and request.GET.get('dl', '0') == '1':

            token = seafile_api.get_fileserver_access_token(
                repo_id, dirent.obj_id, 'download', username,
                use_onetime=settings.FILESERVER_TOKEN_ONCE_ONLY)

            if not token:
                error_msg = 'Internal Server Error'
                return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

            dl_url = gen_file_get_url(token, dirent.obj_name)
            send_file_access_msg(request, repo, path, 'web')
            return Response({'download_url': dl_url})

        dirent_info = get_dirent_info(dirent)

        return Response(dirent_info)
    def post(self, request, repo_id, format=None):
        """ create file/folder in a library
        """

        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if not can_view_sys_admin_repo(repo):
            error_msg = 'Feature disabled.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        parent_dir = request.GET.get('parent_dir', '/')
        if not parent_dir:
            error_msg = 'parent_dir invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if parent_dir[-1] != '/':
            parent_dir = parent_dir + '/'

        dir_id = seafile_api.get_dir_id_by_path(repo_id, parent_dir)
        if not dir_id:
            error_msg = 'Folder %s not found.' % parent_dir
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        obj_name = request.data.get('obj_name', None)
        if not obj_name or not seafile_api.is_valid_filename(repo_id, obj_name):
            error_msg = 'obj_name invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        obj_name = check_filename_with_rename(repo_id, parent_dir, obj_name)

        username = request.user.username
        try:
            seafile_api.post_dir(repo_id, parent_dir, obj_name, username)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        dirent_path = posixpath.join(parent_dir, obj_name)
        dirent = seafile_api.get_dirent_by_path(repo_id, dirent_path)
        dirent_info = get_dirent_info(dirent)

        return Response(dirent_info)
Exemple #24
0
    def get(self, request, repo_id):
        """ Get dir info.

        Permission checking:
        1. user with either 'r' or 'rw' permission.
        """

        # parameter check
        path = request.GET.get('path', None)
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        path = normalize_dir_path(path)
        if path == '/':
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # resource check
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        dir_id = seafile_api.get_dir_id_by_path(repo_id, path)
        if not dir_id:
            error_msg = 'Folder %s not found.' % path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission check
        permission = check_folder_permission(request, repo_id, path)
        if not permission:
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        dir_obj = seafile_api.get_dirent_by_path(repo_id, path)
        dir_info = {
            'repo_id': repo_id,
            'path': path,
            'name': dir_obj.obj_name if dir_obj else '',
            'mtime':
            timestamp_to_isoformat_timestr(dir_obj.mtime) if dir_obj else '',
            'permission': permission,
        }

        return Response(dir_info)
Exemple #25
0
def get_wiki_page_object(wiki_object, page_name):
    page_name = clean_page_name(page_name)
    filepath = "/" + page_name + ".md"
    repo_id = wiki_object.repo_id

    try:
        dirent = seafile_api.get_dirent_by_path(repo_id, filepath)
        if dirent:
            latest_contributor, last_modified = dirent.modifier, dirent.mtime
        else:
            latest_contributor, last_modified = None, 0
    except SearpcError as e:
        logger.error(e)
        latest_contributor, last_modified = None, 0

    try:
        repo = seafile_api.get_repo(wiki_object.repo_id)
    except SearpcError as e:
        logger.error(e)

    file_url = get_inner_file_url(repo, dirent.obj_id, dirent.obj_name)

    edit_url = get_site_scheme_and_netloc().rstrip('/') + "%s?p=%s" % (
        reverse('file_edit', args=[repo_id]),
        urlquote(filepath.encode('utf-8')))

    slug = wiki_object.slug
    page_url = get_site_scheme_and_netloc().rstrip('/') + reverse('wiki:slug',
                                                                  args=[slug, page_name])

    # FIX ME: move to top after wiki code refactor
    from seahub.base.templatetags.seahub_tags import email2nickname, \
        email2contact_email

    return {"name": page_name,
            "link": page_url,
            "file_link": file_url,
            "file_edit_link": edit_url,
            "updated_at": timestamp_to_isoformat_timestr(last_modified),
            "last_modifier": latest_contributor,
            "last_modifier_contact_email": email2contact_email(latest_contributor),
            "last_modifier_name": email2nickname(latest_contributor),
            }
Exemple #26
0
def get_wiki_page_object(wiki_object, page_name):
    page_name = clean_page_name(page_name)
    filepath = "/" + page_name + ".md"
    repo_id = wiki_object.repo_id

    try:
        dirent = seafile_api.get_dirent_by_path(repo_id, filepath)
        if dirent:
            latest_contributor, last_modified = dirent.modifier, dirent.mtime
        else:
            latest_contributor, last_modified = None, 0
    except SearpcError as e:
        logger.error(e)
        latest_contributor, last_modified = None, 0

    try:
        repo = seafile_api.get_repo(wiki_object.repo_id)
    except SearpcError as e:
        logger.error(e)

    file_url = get_inner_file_url(repo, dirent.obj_id, dirent.obj_name)

    edit_url = get_site_scheme_and_netloc().rstrip('/') + "%s?p=%s" % (reverse(
        'file_edit', args=[repo_id]), urlquote(filepath.encode('utf-8')))

    slug = wiki_object.slug
    page_url = get_site_scheme_and_netloc().rstrip('/') + reverse(
        'wiki:slug', args=[slug, page_name])

    # FIX ME: move to top after wiki code refactor
    from seahub.base.templatetags.seahub_tags import email2nickname, \
        email2contact_email

    return {
        "name": page_name,
        "link": page_url,
        "file_link": file_url,
        "file_edit_link": edit_url,
        "updated_at": timestamp_to_isoformat_timestr(last_modified),
        "last_modifier": latest_contributor,
        "last_modifier_contact_email": email2contact_email(latest_contributor),
        "last_modifier_name": email2nickname(latest_contributor),
    }
Exemple #27
0
    def post(self, request, repo_id, format=None):
        """ create file/folder in a library
        """

        if not request.user.admin_permissions.can_manage_library():
            return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')

        parent_dir = request.GET.get('parent_dir', '/')
        parent_dir = normalize_dir_path(parent_dir)
        dir_id = seafile_api.get_dir_id_by_path(repo_id, parent_dir)
        if not dir_id:
            error_msg = 'Folder %s not found.' % parent_dir
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        obj_name = request.data.get('obj_name', None)
        if not obj_name or not is_valid_dirent_name(obj_name):
            error_msg = 'obj_name invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        is_file = request.data.get('is_file', 'false')
        is_file = is_file.lower()
        if is_file not in ('true', 'false'):
            error_msg = 'is_file invalid.'

        username = request.user.username
        obj_name = check_filename_with_rename(repo_id, parent_dir, obj_name)
        try:
            if is_file == 'true':
                seafile_api.post_empty_file(repo_id, parent_dir, obj_name,
                                            username)
            else:
                seafile_api.post_dir(repo_id, parent_dir, obj_name, username)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        dirent_path = posixpath.join(parent_dir, obj_name)
        dirent = seafile_api.get_dirent_by_path(repo_id, dirent_path)
        dirent_info = get_dirent_info(dirent)

        return Response(dirent_info)
Exemple #28
0
    def post(self, request):
        repo_id = request.POST.get('repo_id', '')
        file_path = request.POST.get('file_path', '')

        # new draft
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # perm check
        perm = check_folder_permission(request, repo.id, file_path)
        if perm is None:
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        file_id = seafile_api.get_file_id_by_path(repo.id, file_path)
        if not file_id:
            return api_error(status.HTTP_404_NOT_FOUND,
                             "File %s not found" % file_path)

        username = request.user.username
        dirent = seafile_api.get_dirent_by_path(repo_id, file_path)

        try:
            d = Draft.objects.add(dirent.modifier, repo, file_path, file_id)
        except (DraftFileExist, IntegrityError):
            return api_error(status.HTTP_409_CONFLICT, 'Draft already exists.')

        # new review
        try:
            r = DraftReview.objects.add(creator=dirent.modifier, draft=d)
        except (DraftReviewExist):
            return api_error(status.HTTP_409_CONFLICT,
                             'Draft review already exists.')

        # new reviewer
        if username != d.username:
            ReviewReviewer.objects.add(username, r)

        return Response(r.to_dict())
Exemple #29
0
    def get(self, request, workspace_id, name):
        """
        check wether an asset exists by path
        """

        table_name = name

        path = request.query_params.get('path', '').lstrip('/')
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # resource check
        workspace = Workspaces.objects.get_workspace_by_id(workspace_id)
        if not workspace:
            error_msg = 'Workspace %s not found.' % workspace_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        repo_id = workspace.repo_id
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        dtable = DTables.objects.get_dtable(workspace, table_name)
        if not dtable:
            error_msg = 'dtable %s not found.' % table_name
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        asset_path = os.path.join('/asset', str(dtable.uuid), path)
        try:
            dir = seafile_api.get_dirent_by_path(repo_id, asset_path)
        except Exception as e:
            logger.error(e)
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
                             'Internal Server Error')

        res = {}
        res['is_exist'] = True if dir else False
        return Response(res)
Exemple #30
0
    def post(self, request, repo_id, format=None):
        """ create file/folder in a library
        """

        parent_dir = request.GET.get('parent_dir', '/')
        parent_dir = normalize_dir_path(parent_dir)
        dir_id = seafile_api.get_dir_id_by_path(repo_id, parent_dir)
        if not dir_id:
            error_msg = 'Folder %s not found.' % parent_dir
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        obj_name = request.data.get('obj_name', None)
        if not obj_name or not is_valid_dirent_name(obj_name):
            error_msg = 'obj_name invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        is_file = request.data.get('is_file', 'false')
        is_file = is_file.lower()
        if is_file not in ('true', 'false'):
            error_msg = 'is_file invalid.'

        username = request.user.username
        obj_name = check_filename_with_rename(repo_id, parent_dir, obj_name)
        try:
            if is_file == 'true':
                seafile_api.post_empty_file(repo_id, parent_dir, obj_name, username)
            else:
                seafile_api.post_dir(repo_id, parent_dir, obj_name, username)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        dirent_path = posixpath.join(parent_dir, obj_name)
        dirent = seafile_api.get_dirent_by_path(repo_id, dirent_path)
        dirent_info = get_dirent_info(dirent)

        return Response(dirent_info)
Exemple #31
0
def get_tagged_files(repo, repo_tag_id):

    # get tagged files
    tagged_file_objs = FileTags.objects.filter(
        repo_tag__id=repo_tag_id).select_related('repo_tag', 'file_uuid')

    tagged_files = defaultdict(list)
    for tagged_file_obj in tagged_file_objs:
        file_tag_id = tagged_file_obj.pk
        parent_path = tagged_file_obj.file_uuid.parent_path
        filename = tagged_file_obj.file_uuid.filename
        file_path = posixpath.join(parent_path, filename)

        tagged_file = dict()
        file_obj = seafile_api.get_dirent_by_path(repo.store_id, file_path)
        if not file_obj:
            exception = "Can't find tagged file. Repo_id: %s, Path: %s." % (repo.id, file_path)
            logger.warning(exception)
            tagged_file["file_deleted"] = True
            tagged_file["file_tag_id"] = file_tag_id
            tagged_file["filename"] = filename
            tagged_files["tagged_files"].append(tagged_file)
            continue

        tagged_file["file_tag_id"] = file_tag_id
        tagged_file["parent_path"] = parent_path
        tagged_file["filename"] = filename
        tagged_file["size"] = file_obj.size
        tagged_file["mtime"] = file_obj.mtime
        tagged_file["last_modified"] = timestamp_to_isoformat_timestr(file_obj.mtime)
        tagged_file["modifier_email"] = file_obj.modifier
        tagged_file["modifier_contact_email"] = email2contact_email(file_obj.modifier)
        tagged_file["modifier_name"] = email2nickname(file_obj.modifier)
        tagged_files["tagged_files"].append(tagged_file)

    return tagged_files
Exemple #32
0
    def get_starred_item_info(self, repo, starred_item):

        item_info = {}

        repo_id = starred_item.repo_id
        item_info['repo_id'] = repo_id
        item_info['repo_name'] = repo.repo_name if repo else ''
        item_info['repo_encrypted'] = repo.encrypted
        item_info['is_dir'] = starred_item.is_dir

        path = starred_item.path

        item_info['path'] = path
        if path == '/':
            item_info['obj_name'] = repo.repo_name if repo else ''
            item_info['mtime'] = timestamp_to_isoformat_timestr(repo.last_modified) if \
                    repo else ''
        else:
            item_info['obj_name'] = os.path.basename(path.rstrip('/'))
            dirent = seafile_api.get_dirent_by_path(repo_id, path)
            item_info['mtime'] = timestamp_to_isoformat_timestr(dirent.mtime) if \
                    dirent else ''

        return item_info
    def get_starred_item_info(self, repo, starred_item):

        item_info = {}

        repo_id = starred_item.repo_id
        item_info['repo_id'] = repo_id
        item_info['repo_name'] = repo.repo_name if repo else ''
        item_info['repo_encrypted'] = repo.encrypted
        item_info['is_dir'] = starred_item.is_dir

        path = starred_item.path

        item_info['path'] = path
        if path == '/':
            item_info['obj_name'] = repo.repo_name if repo else ''
            item_info['mtime'] = timestamp_to_isoformat_timestr(repo.last_modified) if \
                    repo else ''
        else:
            item_info['obj_name'] = os.path.basename(path.rstrip('/'))
            dirent = seafile_api.get_dirent_by_path(repo_id, path)
            item_info['mtime'] = timestamp_to_isoformat_timestr(dirent.mtime) if \
                    dirent else ''

        return item_info
Exemple #34
0
    def get_starred_item_info(self, repo, starred_item):

        item_info = {}

        repo_id = starred_item.repo_id
        item_info['repo_id'] = repo_id
        item_info['repo_name'] = repo.repo_name if repo else ''
        item_info['repo_encrypted'] = repo.encrypted
        item_info['is_dir'] = starred_item.is_dir

        path = starred_item.path

        item_info['path'] = path
        if path == '/':
            item_info['obj_name'] = repo.repo_name if repo else ''
            item_info['mtime'] = timestamp_to_isoformat_timestr(repo.last_modified) if \
                    repo else ''
        else:
            item_info['obj_name'] = os.path.basename(path.rstrip('/'))
            dirent = seafile_api.get_dirent_by_path(repo_id, path)
            item_info['mtime'] = timestamp_to_isoformat_timestr(dirent.mtime) if \
                    dirent else ''
            if not starred_item.is_dir:
                file_type, file_ext = get_file_type_and_ext(
                    item_info['obj_name'])
                if file_type in (IMAGE, XMIND) or \
                        (file_type == VIDEO and ENABLE_VIDEO_THUMBNAIL):
                    thumbnail_size = THUMBNAIL_DEFAULT_SIZE
                    thumbnail_file_path = os.path.join(THUMBNAIL_ROOT,
                                                       str(thumbnail_size),
                                                       dirent.obj_id)
                    if os.path.exists(thumbnail_file_path):
                        src = get_thumbnail_src(repo_id, thumbnail_size, path)
                        item_info['encoded_thumbnail_src'] = urlquote(src)

        return item_info
Exemple #35
0
    def get(self, request, file_id, format=None):
        """ WOPI endpoint for check file info
        """

        token = request.GET.get('access_token', None)

        info_dict = get_file_info_by_token(token)
        request_user = info_dict['request_user']
        repo_id = info_dict['repo_id']
        file_path = info_dict['file_path']
        obj_id = info_dict['obj_id']
        can_edit = info_dict['can_edit']
        can_download = info_dict['can_download']

        repo = seafile_api.get_repo(repo_id)

        if not obj_id:
            # if not cache file obj_id, then get it from seafile_api
            obj_id = seafile_api.get_file_id_by_path(repo_id, file_path)

        try:
            file_size = seafile_api.get_file_size(repo.store_id, repo.version,
                                                  obj_id)
        except SearpcError as e:
            logger.error(e)
            return HttpResponse(json.dumps({}),
                                status=500,
                                content_type=json_content_type)

        if file_size == -1:
            logger.error('File %s not found.' % file_path)
            return HttpResponse(json.dumps({}),
                                status=401,
                                content_type=json_content_type)

        result = {}
        # necessary
        result['BaseFileName'] = os.path.basename(file_path)
        result['Size'] = file_size
        result['UserId'] = request_user
        result['Version'] = obj_id
        result['LastModifiedTime'] = ''

        try:
            if is_pro_version():
                result['OwnerId'] = seafile_api.get_repo_owner(repo_id) or \
                        seafile_api.get_org_repo_owner(repo_id)
            else:
                result['OwnerId'] = seafile_api.get_repo_owner(repo_id)

            dirent = seafile_api.get_dirent_by_path(repo_id, file_path)
            if dirent:
                last_modified = datetime.datetime.utcfromtimestamp(
                    dirent.mtime)
                result['LastModifiedTime'] = last_modified.isoformat()
        except Exception as e:
            logger.error(e)
            return HttpResponse(json.dumps({}),
                                status=500,
                                content_type=json_content_type)

        # optional
        if request_user != ANONYMOUS_EMAIL:
            result['UserFriendlyName'] = email2nickname(request_user)
            result['IsAnonymousUser'] = False
        else:
            result['IsAnonymousUser'] = True

        absolute_uri = request.build_absolute_uri('/')
        result['PostMessageOrigin'] = urllib.parse.urljoin(
            absolute_uri, SITE_ROOT).strip('/')
        result['HideSaveOption'] = True
        result['HideExportOption'] = True
        result['EnableOwnerTermination'] = True
        result['SupportsLocks'] = True
        result['SupportsGetLock'] = True

        result['DisablePrint'] = True if not can_download else False
        result['HidePrintOption'] = True if not can_download else False

        result['SupportsUpdate'] = True if can_edit else False
        result['UserCanWrite'] = True if can_edit else False
        result['ReadOnly'] = True if not can_edit else False

        # new file creation feature is not implemented on wopi host(seahub)
        # hide save as button on view/edit file page
        result['UserCanNotWriteRelative'] = True

        return HttpResponse(json.dumps(result),
                            status=200,
                            content_type=json_content_type)
Exemple #36
0
    def get(self, request, name=None):
        username = request.user.username
        org_id = request.user.org.org_id if is_org_context(request) else None
        owned_repos, shared_repos, groups_repos, public_repos = get_user_repos(
            username, org_id=org_id)
        repo_id_list =\
            [repo.id for repo in owned_repos] + \
            [repo.id for repo in shared_repos] + \
            [repo.id for repo in groups_repos] + \
            [repo.id for repo in public_repos]

        if name is None:

            def with_quotes(s):
                return "'" + s + "'"

            # sql = """
            #     SELECT DISTINCT t.* FROM tags_tags t
            #       LEFT JOIN tags_filetag f ON t.id = f.tag_id
            #         LEFT JOIN tags_fileuuidmap m ON f.uuid_id = m.uuid
            #     WHERE m.repo_id IN (%(repo_id_list)s)
            #     """
            # tag_list = Tags.objects.raw(sql, {'repo_id_list': repo_id_list})

            repo_id_text = ', '.join(map(with_quotes, repo_id_list))
            sql = """
                SELECT DISTINCT t.* FROM tags_tags t
                LEFT JOIN tags_filetag f ON t.id = f.tag_id
                    LEFT JOIN tags_fileuuidmap m ON f.uuid_id = m.uuid
                WHERE m.repo_id IN ({})
                """.format(repo_id_text)
            tag_list = Tags.objects.raw(sql)
            tag_list = [tag.to_dict() for tag in tag_list]

            return Response(tag_list, status=status.HTTP_200_OK)
        else:
            tag = get_object_or_404(Tags, name=name)
            fileuuidmap_list = tag.fileuuidmap_set.all()

            repo = None
            dir_list = []
            file_list = []
            for fileuuidmap in fileuuidmap_list:
                if repo is None or repo.id != fileuuidmap.repo_id:
                    repo = seafile_api.get_repo(fileuuidmap.repo_id)

                fullpath = posixpath.join(fileuuidmap.parent_path,
                                          fileuuidmap.filename)
                dirent = seafile_api.get_dirent_by_path(
                    fileuuidmap.repo_id, fullpath)

                dirent.repo_id = repo.id
                dirent.parent_path = fileuuidmap.parent_path
                dirent.fullpath = fullpath
                dirent.last_modified = dirent.mtime
                if stat.S_ISDIR(dirent.mode):
                    dir_list.append(dirent)
                else:
                    if repo.version == 0:
                        file_size = seafile_api.get_file_size(
                            repo.store_id, repo.version, dirent.obj_id)
                    else:
                        file_size = dirent.size
                    dirent.file_size = file_size if file_size else 0

                    can_preview, err_msg = can_preview_file(
                        dirent.obj_name, file_size, repo)
                    dirent.can_preview = can_preview

                    file_list.append(dirent)

            dirent_list = []
            for d in dir_list:
                d_ = {
                    'is_dir': True,
                    'obj_name': d.obj_name,
                    'last_modified': d.last_modified,
                    'last_update': translate_seahub_time(d.last_modified),
                    'p_dpath': d.fullpath,
                    'perm': d.permission,
                    'repo_id': d.repo_id,
                    'parent_path': d.parent_path,
                }
                dirent_list.append(d_)

            size = int(
                request.GET.get('thumbnail_size', THUMBNAIL_DEFAULT_SIZE))

            for f in file_list:
                f_ = {
                    'is_file': True,
                    'obj_name': f.obj_name,
                    'last_modified': f.last_modified,
                    'last_update': translate_seahub_time(f.last_modified),
                    'file_size': filesizeformat(f.file_size),
                    'obj_id': f.obj_id,
                    'perm': f.permission,
                    'can_preview': f.can_preview,
                    'repo_id': f.repo_id,
                    'parent_path': f.parent_path,
                }

                if not repo.encrypted and ENABLE_THUMBNAIL:
                    file_ext = os.path.splitext(f.obj_name)[1][1:].lower()
                    file_type = FILEEXT_TYPE_MAP.get(file_ext)
                    if file_type == IMAGE:
                        f_['is_img'] = True

                    if file_type == VIDEO and ENABLE_VIDEO_THUMBNAIL:
                        f_['is_video'] = True

                    if file_type == IMAGE or file_type == VIDEO and ENABLE_VIDEO_THUMBNAIL:
                        thumbnail_file_path = os.path.join(
                            THUMBNAIL_ROOT, str(size), f.obj_id)
                        thumbnail_exist = os.path.exists(thumbnail_file_path)
                        if thumbnail_exist:
                            src = get_thumbnail_src(f.repo_id, size,
                                                    f.fullpath)
                            f_['encoded_thumbnail_src'] = urlquote(src)

                dirent_list.append(f_)

            return Response(dirent_list, status=status.HTTP_200_OK)
Exemple #37
0
    def put(self, request, token):
        """ Update share link, currently only available for permission.

        Permission checking:
        share link creater
        """

        # argument check
        try:
            perm = check_permissions_arg(request)
        except Exception:
            error_msg = 'permissions invalud.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # resource check
        try:
            fs = FileShare.objects.get(token=token)
        except FileShare.DoesNotExist:
            error_msg = 'token %s not found.' % token
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        repo_id = fs.repo_id
        repo = seafile_api.get_repo(repo_id)
        if not repo_id:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if fs.path != '/':
            dirent = seafile_api.get_dirent_by_path(repo_id, fs.path)
            if not dirent:
                error_msg = 'Dirent %s not found.' % repo_id
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission check
        username = request.user.username
        if not fs.is_owner(username):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        # get permission of origin repo/folder
        if fs.s_type == 'd':
            folder_path = normalize_dir_path(fs.path)
        else:
            file_path = normalize_file_path(fs.path)
            folder_path = os.path.dirname(file_path)

        username = request.user.username
        repo_folder_permission = seafile_api.check_permission_by_path(repo_id,
                folder_path, username)
        if not repo_folder_permission:
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        if repo_folder_permission in (PERMISSION_PREVIEW_EDIT, PERMISSION_PREVIEW) \
                and perm != FileShare.PERM_VIEW_ONLY:
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        if repo_folder_permission in (PERMISSION_READ) \
                and perm not in (FileShare.PERM_VIEW_DL, FileShare.PERM_VIEW_ONLY):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        if fs.s_type == 'f':
            file_name = os.path.basename(fs.path.rstrip('/'))
            can_edit, error_msg = can_edit_file(file_name, dirent.size, repo)
            if not can_edit and perm in (FileShare.PERM_EDIT_DL, FileShare.PERM_EDIT_ONLY):
                error_msg = 'Permission denied.'
                return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        # update share link permission
        fs.permission = perm
        fs.save()

        link_info = get_share_link_info(fs)
        return Response(link_info)
Exemple #38
0
    def post(self, request):
        """ Create share link.

        Permission checking:
        1. default(NOT guest) user;
        """

        # argument check
        repo_id = request.data.get('repo_id', None)
        if not repo_id:
            error_msg = 'repo_id invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        path = request.data.get('path', None)
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        password = request.data.get('password', None)
        if password and len(password) < config.SHARE_LINK_PASSWORD_MIN_LENGTH:
            error_msg = _('Password is too short.')
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        expire_days = request.data.get('expire_days', '')
        expiration_time = request.data.get('expiration_time', '')
        if expire_days and expiration_time:
            error_msg = 'Can not pass expire_days and expiration_time at the same time.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        expire_date = None
        if expire_days:
            try:
                expire_days = int(expire_days)
            except ValueError:
                error_msg = 'expire_days invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            if expire_days <= 0:
                error_msg = 'expire_days invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            if SHARE_LINK_EXPIRE_DAYS_MIN > 0:
                if expire_days < SHARE_LINK_EXPIRE_DAYS_MIN:
                    error_msg = _('Expire days should be greater or equal to %s') % \
                            SHARE_LINK_EXPIRE_DAYS_MIN
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            if SHARE_LINK_EXPIRE_DAYS_MAX > 0:
                if expire_days > SHARE_LINK_EXPIRE_DAYS_MAX:
                    error_msg = _('Expire days should be less than or equal to %s') % \
                            SHARE_LINK_EXPIRE_DAYS_MAX
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            expire_date = timezone.now() + relativedelta(days=expire_days)

        elif expiration_time:

            try:
                expire_date = dateutil.parser.isoparse(expiration_time)
            except Exception as e:
                logger.error(e)
                error_msg = 'expiration_time invalid, should be iso format, for example: 2020-05-17T10:26:22+08:00'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            expire_date = expire_date.astimezone(get_current_timezone()).replace(tzinfo=None)

            if SHARE_LINK_EXPIRE_DAYS_MIN > 0:
                expire_date_min_limit = timezone.now() + relativedelta(days=SHARE_LINK_EXPIRE_DAYS_MIN)
                expire_date_min_limit = expire_date_min_limit.replace(hour=0).replace(minute=0).replace(second=0)

                if expire_date < expire_date_min_limit:
                    error_msg = _('Expiration time should be later than %s.') % \
                            expire_date_min_limit.strftime("%Y-%m-%d %H:%M:%S")
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            if SHARE_LINK_EXPIRE_DAYS_MAX > 0:
                expire_date_max_limit = timezone.now() + relativedelta(days=SHARE_LINK_EXPIRE_DAYS_MAX)
                expire_date_max_limit = expire_date_max_limit.replace(hour=23).replace(minute=59).replace(second=59)

                if expire_date > expire_date_max_limit:
                    error_msg = _('Expiration time should be earlier than %s.') % \
                            expire_date_max_limit.strftime("%Y-%m-%d %H:%M:%S")
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        else:
            if SHARE_LINK_EXPIRE_DAYS_DEFAULT > 0:
                expire_date = timezone.now() + relativedelta(days=SHARE_LINK_EXPIRE_DAYS_DEFAULT)

        try:
            perm = check_permissions_arg(request)
        except Exception:
            error_msg = 'permissions invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # resource check
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if path != '/':
            dirent = seafile_api.get_dirent_by_path(repo_id, path)
            if not dirent:
                error_msg = 'Dirent %s not found.' % path
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission check
        if repo.encrypted:
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        username = request.user.username
        repo_folder_permission = seafile_api.check_permission_by_path(repo_id, path, username)
        if parse_repo_perm(repo_folder_permission).can_generate_share_link is False:
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        if repo_folder_permission in (PERMISSION_PREVIEW_EDIT, PERMISSION_PREVIEW) \
                and perm != FileShare.PERM_VIEW_ONLY:
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        if repo_folder_permission in (PERMISSION_READ) \
                and perm not in (FileShare.PERM_VIEW_DL, FileShare.PERM_VIEW_ONLY):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        # can_upload requires rw repo permission
        if perm == FileShare.PERM_VIEW_DL_UPLOAD and \
                repo_folder_permission != PERMISSION_READ_WRITE:
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        if path != '/':
            s_type = 'd' if stat.S_ISDIR(dirent.mode) else 'f'
            if s_type == 'f':
                file_name = os.path.basename(path.rstrip('/'))
                can_edit, error_msg = can_edit_file(file_name, dirent.size, repo)
                if not can_edit and perm in (FileShare.PERM_EDIT_DL, FileShare.PERM_EDIT_ONLY):
                    error_msg = 'Permission denied.'
                    return api_error(status.HTTP_403_FORBIDDEN, error_msg)
        else:
            s_type = 'd'

        # create share link
        org_id = request.user.org.org_id if is_org_context(request) else None
        if s_type == 'f':
            fs = FileShare.objects.get_file_link_by_path(username, repo_id, path)
            if fs:
                error_msg = _('Share link %s already exists.' % fs.token)
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
            fs = FileShare.objects.create_file_link(username, repo_id, path,
                                                    password, expire_date,
                                                    permission=perm, org_id=org_id)

        elif s_type == 'd':
            fs = FileShare.objects.get_dir_link_by_path(username, repo_id, path)
            if fs:
                error_msg = _('Share link %s already exists.' % fs.token)
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
            fs = FileShare.objects.create_dir_link(username, repo_id, path,
                                                    password, expire_date,
                                                    permission=perm, org_id=org_id)

        link_info = get_share_link_info(fs)
        return Response(link_info)
Exemple #39
0
    def get(self, request):
        """ Get all share links of a user.

        Permission checking:
        1. default(NOT guest) user;
        """

        username = request.user.username

        repo_id = request.GET.get('repo_id', '')
        path = request.GET.get('path', '')

        fileshares = []
        # get all share links of current user
        if not repo_id and not path:
            fileshares = FileShare.objects.filter(username=username)

        # share links in repo
        if repo_id and not path:
            repo = seafile_api.get_repo(repo_id)
            if not repo:
                error_msg = 'Library %s not found.' % repo_id
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)

            fileshares = FileShare.objects.filter(username=username) \
                                          .filter(repo_id=repo_id)

        # share links by repo and path
        if repo_id and path:
            repo = seafile_api.get_repo(repo_id)
            if not repo:
                error_msg = 'Library %s not found.' % repo_id
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)

            if path != '/':
                dirent = seafile_api.get_dirent_by_path(repo_id, path)
                if not dirent:
                    error_msg = 'Dirent %s not found.' % path
                    return api_error(status.HTTP_404_NOT_FOUND, error_msg)

                if stat.S_ISDIR(dirent.mode):
                    path = normalize_dir_path(path)
                else:
                    path = normalize_file_path(path)

            fileshares = FileShare.objects.filter(username=username) \
                                          .filter(repo_id=repo_id) \
                                          .filter(path=path)

        repo_folder_permission_dict = {}
        for fileshare in fileshares:

            if fileshare.s_type == 'd':
                folder_path = normalize_dir_path(fileshare.path)
            else:
                file_path = normalize_file_path(fileshare.path)
                folder_path = os.path.dirname(file_path)

            repo_id = fileshare.repo_id
            if repo_id not in repo_folder_permission_dict:

                try:
                    permission = seafile_api.check_permission_by_path(repo_id,
                            folder_path, fileshare.username)
                except Exception as e:
                    logger.error(e)
                    permission = ''

                repo_folder_permission_dict[repo_id] = permission

        links_info = []
        for fs in fileshares:
            link_info = get_share_link_info(fs)
            link_info['repo_folder_permission'] = \
                    repo_folder_permission_dict.get(link_info['repo_id'], '')
            links_info.append(link_info)

        if len(links_info) == 1:
            result = links_info
        else:
            dir_list = [x for x in links_info if x['is_dir']]
            file_list = [x for x in links_info if not x['is_dir']]

            dir_list.sort(key=lambda x: x['obj_name'])
            file_list.sort(key=lambda x: x['obj_name'])

            result = dir_list + file_list

        return Response(result)
Exemple #40
0
    def get_starred_files_by_username(self, username):
        """Get a user's starred files.

        Arguments:
        - `self`:
        - `username`:
        """
        starred_files = super(UserStarredFilesManager, self).filter(
            email=username, org_id=-1)

        ret = []
        repo_cache = {}
        for sfile in starred_files:
            # repo still exists?
            if repo_cache.has_key(sfile.repo_id):
                repo = repo_cache[sfile.repo_id]
            else:
                try:
                    repo = seafile_api.get_repo(sfile.repo_id)
                except SearpcError:
                    continue
                if repo is not None:
                    repo_cache[sfile.repo_id] = repo
                else:
                    sfile.delete()
                    continue

            # file still exists?
            file_id = ''
            size = -1
            if sfile.path != "/":
                try:
                    file_id = seafile_api.get_file_id_by_path(sfile.repo_id,
                                                              sfile.path)
                    # size = seafile_api.get_file_size(file_id)
                except SearpcError:
                    continue
                if not file_id:
                    sfile.delete()
                    continue

            f = StarredFile(sfile.org_id, repo, file_id, sfile.path,
                            sfile.is_dir, 0) # TODO: remove ``size`` from StarredFile
            ret.append(f)

        '''Calculate files last modification time'''
        for sfile in ret:
            if sfile.is_dir:
                continue

            try:
                # get real path for sub repo
                real_path = sfile.repo.origin_path + sfile.path if sfile.repo.origin_path else sfile.path
                dirent = seafile_api.get_dirent_by_path(sfile.repo.store_id,
                                                        real_path)
                if dirent:
                    sfile.last_modified = dirent.mtime
                else:
                    sfile.last_modified = 0
            except SearpcError as e:
                logger.error(e)
                sfile.last_modified = 0

        ret.sort(lambda x, y: cmp(y.last_modified, x.last_modified))

        return ret
Exemple #41
0
def react_fake_view(request, **kwargs):

    username = request.user.username

    if resolve(request.path).url_name == 'lib_view':

        repo_id = kwargs.get('repo_id', '')
        path = kwargs.get('path', '')

        if repo_id and path and \
                not check_folder_permission(request, repo_id, path):

            converted_repo_path = seafile_api.convert_repo_path(
                repo_id, path, username)
            if not converted_repo_path:
                error_msg = 'Permission denied.'
                return render_error(request, error_msg)

            repo_path_dict = json.loads(converted_repo_path)

            converted_repo_id = repo_path_dict['repo_id']
            converted_repo = seafile_api.get_repo(converted_repo_id)
            if not converted_repo:
                error_msg = 'Library %s not found.' % converted_repo_id
                return render_error(request, error_msg)

            converted_path = repo_path_dict['path']
            if not seafile_api.get_dirent_by_path(converted_repo_id,
                                                  converted_path):
                error_msg = 'Dirent %s not found.' % converted_path
                return render_error(request, error_msg)

            if not check_folder_permission(request, converted_repo_id,
                                           converted_path):
                error_msg = 'Permission denied.'
                return render_error(request, error_msg)

            next_url = reverse('lib_view',
                               args=[
                                   converted_repo_id, converted_repo.repo_name,
                                   converted_path.strip('/')
                               ])
            return HttpResponseRedirect(next_url)

    guide_enabled = UserOptions.objects.is_user_guide_enabled(username)
    if guide_enabled:
        create_default_library(request)

    try:
        expire_days = seafile_api.get_server_config_int(
            'library_trash', 'expire_days')
    except Exception as e:
        logger.error(e)
        expire_days = -1

    folder_perm_enabled = True if is_pro_version(
    ) and ENABLE_FOLDER_PERM else False

    try:
        max_upload_file_size = seafile_api.get_server_config_int(
            'fileserver', 'max_upload_size')
    except Exception as e:
        logger.error(e)
        max_upload_file_size = -1

    return render(
        request, "react_app.html", {
            "onlyoffice_desktop_editors_portal_login":
            ONLYOFFICE_DESKTOP_EDITORS_PORTAL_LOGIN,
            "guide_enabled": guide_enabled,
            'trash_repos_expire_days': expire_days if expire_days > 0 else 30,
            'dtable_web_server': DTABLE_WEB_SERVER,
            'max_upload_file_size': max_upload_file_size,
            'seafile_collab_server': SEAFILE_COLLAB_SERVER,
            'storages': get_library_storages(request),
            'library_templates': list(LIBRARY_TEMPLATES.keys()),
            'enable_repo_snapshot_label': settings.ENABLE_REPO_SNAPSHOT_LABEL,
            'resumable_upload_file_block_size':
            settings.RESUMABLE_UPLOAD_FILE_BLOCK_SIZE,
            'max_number_of_files_for_fileupload':
            settings.MAX_NUMBER_OF_FILES_FOR_FILEUPLOAD,
            'share_link_expire_days_default': SHARE_LINK_EXPIRE_DAYS_DEFAULT,
            'share_link_expire_days_min': SHARE_LINK_EXPIRE_DAYS_MIN,
            'share_link_expire_days_max': SHARE_LINK_EXPIRE_DAYS_MAX,
            'upload_link_expire_days_default': UPLOAD_LINK_EXPIRE_DAYS_DEFAULT,
            'upload_link_expire_days_min': UPLOAD_LINK_EXPIRE_DAYS_MIN,
            'upload_link_expire_days_max': UPLOAD_LINK_EXPIRE_DAYS_MAX,
            'enable_encrypted_library': config.ENABLE_ENCRYPTED_LIBRARY,
            'enable_repo_history_setting': config.ENABLE_REPO_HISTORY_SETTING,
            'enable_reset_encrypted_repo_password':
            ENABLE_RESET_ENCRYPTED_REPO_PASSWORD,
            'enableFileComment': settings.ENABLE_FILE_COMMENT,
            'is_email_configured': IS_EMAIL_CONFIGURED,
            'can_add_public_repo':
            request.user.permissions.can_add_public_repo(),
            'folder_perm_enabled': folder_perm_enabled,
            'file_audit_enabled': FILE_AUDIT_ENABLED,
            'custom_nav_items': json.dumps(CUSTOM_NAV_ITEMS),
            'enable_show_contact_email_when_search_user':
            settings.ENABLE_SHOW_CONTACT_EMAIL_WHEN_SEARCH_USER,
            'additional_share_dialog_note': ADDITIONAL_SHARE_DIALOG_NOTE,
            'additional_app_bottom_links': ADDITIONAL_APP_BOTTOM_LINKS,
            'additional_about_dialog_links': ADDITIONAL_ABOUT_DIALOG_LINKS,
            'enable_ocm': ENABLE_OCM,
            'ocm_remote_servers': OCM_REMOTE_SERVERS,
            'enable_share_to_department': settings.ENABLE_SHARE_TO_DEPARTMENT,
            'enable_video_thumbnail': settings.ENABLE_VIDEO_THUMBNAIL,
            'group_import_members_extra_msg': GROUP_IMPORT_MEMBERS_EXTRA_MSG,
        })
Exemple #42
0
    def get(self, request, repo_id, format=None):
        """ Get file server token for download-dir and download-multi.

        Permission checking:
        1. user with 'r' or 'rw' permission;
        """

        # argument check
        parent_dir = request.GET.get('parent_dir', None)
        if not parent_dir:
            error_msg = 'parent_dir invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        dirent_name_list = request.GET.getlist('dirents', None)
        if not dirent_name_list:
            error_msg = 'dirents invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if len(dirent_name_list) == 1:
            download_type = 'download-dir'
        elif len(dirent_name_list) > 1:
            download_type = 'download-multi'
        else:
            error_msg = 'dirents invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # recourse check
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if not seafile_api.get_dir_id_by_path(repo_id, parent_dir):
            error_msg = 'Folder %s not found.' % parent_dir
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission check
        if not check_folder_permission(request, repo_id, parent_dir):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        # get file server access token
        is_windows = 0
        if is_windows_operating_system(request):
            is_windows = 1

        if download_type == 'download-dir':
            dir_name = dirent_name_list[0].strip('/')
            full_dir_path = posixpath.join(parent_dir, dir_name)

            dir_id = seafile_api.get_dir_id_by_path(repo_id, full_dir_path)
            if not dir_id:
                error_msg = 'Folder %s not found.' % full_dir_path
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)

            dir_size = seafile_api.get_dir_size(
                    repo.store_id, repo.version, dir_id)

            if dir_size > seaserv.MAX_DOWNLOAD_DIR_SIZE:
                error_msg = 'Unable to download directory "%s": size is too large.' % dir_name
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            fake_obj_id = {
                'obj_id': dir_id,
                'dir_name': dir_name,
                'is_windows': is_windows
            }

        if download_type == 'download-multi':
            dirent_list = []
            total_size = 0
            for dirent_name in dirent_name_list:
                dirent_name = dirent_name.strip('/')
                dirent_list.append(dirent_name)

                full_dirent_path = posixpath.join(parent_dir, dirent_name)
                current_dirent = seafile_api.get_dirent_by_path(repo_id, full_dirent_path)
                if not current_dirent:
                    continue

                if stat.S_ISDIR(current_dirent.mode):
                    total_size += seafile_api.get_dir_size(repo.store_id,
                        repo.version, current_dirent.obj_id)
                else:
                    total_size += current_dirent.size

            if total_size > seaserv.MAX_DOWNLOAD_DIR_SIZE:
                error_msg = _('Total size exceeds limit.')
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            fake_obj_id = {
                'parent_dir': parent_dir,
                'file_list': dirent_list,
                'is_windows': is_windows
            }

        username = request.user.username
        try:
            zip_token = seafile_api.get_fileserver_access_token(
                    repo_id, json.dumps(fake_obj_id), download_type, username)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if len(dirent_name_list) > 10:
            send_file_access_msg(request, repo, parent_dir, 'web')
        else:
            for dirent_name in dirent_name_list:
                full_dirent_path = posixpath.join(parent_dir, dirent_name)
                send_file_access_msg(request, repo, full_dirent_path, 'web')

        return Response({'zip_token': zip_token})
    def get(self, request, repo_id, format=None):

        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # argument checking
        parent_dir = request.GET.get('parent_dir', None)
        dirent_name_string = request.GET.get('dirents', None)

        if not parent_dir:
            error_msg = 'parent_dir invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if not dirent_name_string:
            error_msg = 'dirents invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # folder exist checking
        if not seafile_api.get_dir_id_by_path(repo_id, parent_dir):
            error_msg = 'Folder %s not found.' % parent_dir
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission checking
        if check_folder_permission(request, repo_id, parent_dir) is None:
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        dirent_name_list = string2list(dirent_name_string)
        dirent_list = []
        total_size = 0
        for dirent_name in dirent_name_list:
            dirent_name = dirent_name.strip('/')
            dirent_list.append(dirent_name)

            full_dirent_path = posixpath.join(parent_dir, dirent_name)
            current_dirent = seafile_api.get_dirent_by_path(repo_id, full_dirent_path)
            if stat.S_ISDIR(current_dirent.mode):
                total_size += seafile_api.get_dir_size(repo.store_id,
                    repo.version, current_dirent.obj_id)
            else:
                total_size += current_dirent.size

        if total_size > seaserv.MAX_DOWNLOAD_DIR_SIZE:
            error_msg = _('Total size exceeds limit.')
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        fake_obj_id = {}
        fake_obj_id['file_list'] = dirent_list
        fake_obj_id['parent_dir'] = parent_dir

        username = request.user.username
        try:
            token = seafile_api.get_fileserver_access_token(repo_id,
                json.dumps(fake_obj_id), 'download-multi', username, False)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if len(dirent_list) > 10:
            send_file_access_msg(request, repo, parent_dir, 'web')
        else:
            for dirent_name in dirent_list:
                full_dirent_path = posixpath.join(parent_dir, dirent_name)
                send_file_access_msg(request, repo, full_dirent_path, 'web')

        download_url = '%s/files/%s' % (get_fileserver_root(), token)
        return Response({'url': download_url})
Exemple #44
0
    def get_starred_files_by_username(self, username):
        """Get a user's starred files.

        Arguments:
        - `self`:
        - `username`:
        """
        starred_files = super(UserStarredFilesManager,
                              self).filter(email=username, org_id=-1)

        ret = []
        repo_cache = {}
        for sfile in starred_files:
            # repo still exists?
            if repo_cache.has_key(sfile.repo_id):
                repo = repo_cache[sfile.repo_id]
            else:
                try:
                    repo = seafile_api.get_repo(sfile.repo_id)
                except SearpcError:
                    continue
                if repo is not None:
                    repo_cache[sfile.repo_id] = repo
                else:
                    sfile.delete()
                    continue

            # file still exists?
            file_id = ''
            size = -1
            if sfile.path != "/":
                try:
                    file_id = seafile_api.get_file_id_by_path(
                        sfile.repo_id, sfile.path)
                    # size = seafile_api.get_file_size(file_id)
                except SearpcError:
                    continue
                if not file_id:
                    sfile.delete()
                    continue

            f = StarredFile(sfile.org_id, repo, file_id, sfile.path,
                            sfile.is_dir,
                            0)  # TODO: remove ``size`` from StarredFile
            ret.append(f)
        '''Calculate files last modification time'''
        for sfile in ret:
            if sfile.is_dir:
                continue

            try:
                # get real path for sub repo
                real_path = sfile.repo.origin_path + sfile.path if sfile.repo.origin_path else sfile.path
                dirent = seafile_api.get_dirent_by_path(
                    sfile.repo.store_id, real_path)
                if dirent:
                    sfile.last_modified = dirent.mtime
                else:
                    sfile.last_modified = 0
            except SearpcError as e:
                logger.error(e)
                sfile.last_modified = 0

        ret.sort(lambda x, y: cmp(y.last_modified, x.last_modified))

        return ret
Exemple #45
0
def personal_wiki(request, page_name="home"):
    username = request.user.username

    if request.cloud_mode and request.user.org is not None:
        org_id = request.user.org.org_id
        joined_groups = seaserv.get_org_groups_by_user(org_id, username)
    else:
        joined_groups = seaserv.get_personal_groups_by_user(username)

    if joined_groups:
        joined_groups.sort(lambda x, y: cmp(x.group_name.lower(), y.group_name.lower()))

    wiki_exists = True
    try:
        content, repo, dirent = get_personal_wiki_page(username, page_name)
    except WikiDoesNotExist:
        wiki_exists = False
        owned_repos = seafile_api.get_owned_repo_list(username)
        owned_repos = [r for r in owned_repos if not r.encrypted]
        return render_to_response("wiki/personal_wiki.html", {
                "wiki_exists": wiki_exists,
                "owned_repos": owned_repos,
                "grps": joined_groups,
                }, context_instance=RequestContext(request))
    except WikiPageMissing:
        repo = get_personal_wiki_repo(username)
        filename = page_name_to_file_name(clean_page_name(page_name))
        if not seaserv.post_empty_file(repo.id, "/", filename, username):
            return render_error(request, _("Failed to create wiki page. Please retry later."))
        return HttpResponseRedirect(reverse('personal_wiki', args=[page_name]))
    else:
        # fetch file modified time and modifier
        path = '/' + dirent.obj_name
        try:
            dirent = seafile_api.get_dirent_by_path(repo.id, path)
            if dirent:
                latest_contributor, last_modified = dirent.modifier, dirent.mtime
            else:
                latest_contributor, last_modified = None, 0
        except SearpcError as e:
            logger.error(e)
            latest_contributor, last_modified = None, 0

        wiki_index_exists = True
        index_pagename = 'index'
        index_content = None
        try:
            index_content, index_repo, index_dirent = get_personal_wiki_page(username, index_pagename)
        except (WikiDoesNotExist, WikiPageMissing) as e:
            wiki_index_exists = False

        return render_to_response("wiki/personal_wiki.html", { 
            "wiki_exists": wiki_exists,
            "content": content,
            "page": os.path.splitext(dirent.obj_name)[0],
            "last_modified": last_modified,
            "latest_contributor": latest_contributor or _("Unknown"),
            "path": path,
            "repo_id": repo.id,
            "search_repo_id": repo.id,
            "search_wiki": True,
            "wiki_index_exists": wiki_index_exists,
            "index_content": index_content,
            "grps": joined_groups,
            }, context_instance=RequestContext(request))
Exemple #46
0
    def get(self, request, slug):
        """Get content of a wiki
        """
        path = request.GET.get('p', '/')
        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
        if not wiki.check_access_wiki(request):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        if request.user.username:
            parent_dir = os.path.dirname(path)
            permission = check_folder_permission(request, wiki.repo_id,
                                                 parent_dir)
        else:
            permission = 'r'

        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)

        file_id = None
        try:
            file_id = seafile_api.get_file_id_by_path(repo.repo_id, path)
        except SearpcError as e:
            logger.error(e)
            return api_error(HTTP_520_OPERATION_FAILED,
                             "Failed to get file id by path.")
        if not file_id:
            return api_error(status.HTTP_404_NOT_FOUND, "File not found")

        # send stats message
        send_file_access_msg(request, repo, path, 'api')

        file_name = os.path.basename(path)
        token = seafile_api.get_fileserver_access_token(
            repo.repo_id, file_id, 'download', request.user.username, 'False')

        if not token:
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        url = gen_inner_file_get_url(token, file_name)
        file_response = urllib2.urlopen(url)
        content = file_response.read()

        try:
            dirent = seafile_api.get_dirent_by_path(repo.repo_id, path)
            if dirent:
                latest_contributor, last_modified = dirent.modifier, dirent.mtime
            else:
                latest_contributor, last_modified = None, 0
        except SearpcError as e:
            logger.error(e)
            latest_contributor, last_modified = None, 0

        return Response({
            "content":
            content,
            "latest_contributor":
            email2nickname(latest_contributor),
            "last_modified":
            last_modified,
            "permission":
            permission,
        })
Exemple #47
0
def group_wiki(request, group, page_name="home"):
    username = request.user.username

    # get available modules(wiki, etc)
    mods_available = get_available_mods_by_group(group.id)
    mods_enabled = get_enabled_mods_by_group(group.id)

    wiki_exists = True
    try:
        content, repo, dirent = get_group_wiki_page(username, group, page_name)
    except WikiDoesNotExist:
        wiki_exists = False
        group_repos = get_group_repos(group.id, username)
        group_repos = [r for r in group_repos if not r.encrypted]
        return render_to_response(
            "group/group_wiki.html",
            {
                "group": group,
                "is_staff": group.is_staff,
                "wiki_exists": wiki_exists,
                "mods_enabled": mods_enabled,
                "mods_available": mods_available,
                "group_repos": group_repos,
            },
            context_instance=RequestContext(request),
        )
    except WikiPageMissing:
        """create that page for user if he/she is a group member"""
        if not is_group_user(group.id, username):
            raise Http404

        repo = get_group_wiki_repo(group, username)
        # No need to check whether repo is none, since repo is already created

        filename = page_name_to_file_name(clean_page_name(page_name))
        if not post_empty_file(repo.id, "/", filename, username):
            return render_error(request, _("Failed to create wiki page. Please retry later."))
        return HttpResponseRedirect(reverse("group_wiki", args=[group.id, page_name]))
    else:
        url_prefix = reverse("group_wiki", args=[group.id])

        # fetch file modified time and modifier
        path = "/" + dirent.obj_name
        try:
            dirent = seafile_api.get_dirent_by_path(repo.id, path)
            if dirent:
                latest_contributor, last_modified = dirent.modifier, dirent.mtime
            else:
                latest_contributor, last_modified = None, 0
        except SearpcError as e:
            logger.error(e)
            latest_contributor, last_modified = None, 0

        repo_perm = seafile_api.check_repo_access_permission(repo.id, username)

        wiki_index_exists = True
        index_pagename = "index"
        index_content = None
        try:
            index_content, index_repo, index_dirent = get_group_wiki_page(username, group, index_pagename)
        except (WikiDoesNotExist, WikiPageMissing) as e:
            wiki_index_exists = False

        return render_to_response(
            "group/group_wiki.html",
            {
                "group": group,
                "is_staff": group.is_staff,
                "wiki_exists": wiki_exists,
                "content": content,
                "page": os.path.splitext(dirent.obj_name)[0],
                "last_modified": last_modified,
                "latest_contributor": latest_contributor or _("Unknown"),
                "path": path,
                "repo_id": repo.id,
                "search_repo_id": repo.id,
                "search_wiki": True,
                "mods_enabled": mods_enabled,
                "mods_available": mods_available,
                "repo_perm": repo_perm,
                "wiki_index_exists": wiki_index_exists,
                "index_content": index_content,
            },
            context_instance=RequestContext(request),
        )
Exemple #48
0
def group_wiki(request, group, page_name="home"):
    username = request.user.username

    # get available modules(wiki, etc)
    mods_available = get_available_mods_by_group(group.id)
    mods_enabled = get_enabled_mods_by_group(group.id)

    wiki_exists = True
    try:
        content, repo, dirent = get_group_wiki_page(username, group, page_name)
    except WikiDoesNotExist:
        wiki_exists = False
        group_repos = get_group_repos(group.id, username)
        group_repos = [r for r in group_repos if not r.encrypted]
        return render_to_response("group/group_wiki.html", {
            "group": group,
            "is_staff": group.is_staff,
            "wiki_exists": wiki_exists,
            "mods_enabled": mods_enabled,
            "mods_available": mods_available,
            "group_repos": group_repos,
        },
                                  context_instance=RequestContext(request))
    except WikiPageMissing:
        '''create that page for user if he/she is a group member'''
        if not is_group_user(group.id, username):
            raise Http404

        repo = get_group_wiki_repo(group, username)
        # No need to check whether repo is none, since repo is already created

        filename = page_name_to_file_name(clean_page_name(page_name))
        if not post_empty_file(repo.id, "/", filename, username):
            return render_error(
                request, _("Failed to create wiki page. Please retry later."))
        return HttpResponseRedirect(
            reverse('group_wiki', args=[group.id, page_name]))
    else:
        # fetch file modified time and modifier
        path = '/' + dirent.obj_name
        try:
            dirent = seafile_api.get_dirent_by_path(repo.id, path)
            if dirent:
                latest_contributor, last_modified = dirent.modifier, dirent.mtime
            else:
                latest_contributor, last_modified = None, 0
        except SearpcError as e:
            logger.error(e)
            latest_contributor, last_modified = None, 0

        if is_registered_user(username):
            repo_perm = seafile_api.check_permission_by_path(
                repo.id, '/', username)
        else:
            # when anonymous user visit public group wiki, set permission as 'r'
            repo_perm = 'r'

        wiki_index_exists = True
        index_pagename = 'index'
        index_content = None
        try:
            index_content, index_repo, index_dirent = get_group_wiki_page(
                username, group, index_pagename)
        except (WikiDoesNotExist, WikiPageMissing) as e:
            wiki_index_exists = False

        return render_to_response(
            "group/group_wiki.html", {
                "group": group,
                "is_staff": group.is_staff,
                "wiki_exists": wiki_exists,
                "content": content,
                "page": os.path.splitext(dirent.obj_name)[0],
                "last_modified": last_modified,
                "latest_contributor": latest_contributor or _("Unknown"),
                "path": path,
                "repo_id": repo.id,
                "search_repo_id": repo.id,
                "search_wiki": True,
                "mods_enabled": mods_enabled,
                "mods_available": mods_available,
                "repo_perm": repo_perm,
                "wiki_index_exists": wiki_index_exists,
                "index_content": index_content,
            },
            context_instance=RequestContext(request))
Exemple #49
0
    def get(self, request, slug):
        """Get content of a wiki
        """
        path = request.GET.get('p', '/')
        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
        if not wiki.has_read_perm(request):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)
        
        if request.user.username:
            parent_dir = os.path.dirname(path)
            permission = check_folder_permission(request, wiki.repo_id, parent_dir)
        else:
            permission = 'r'

        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)

        file_id = None
        try:
            file_id = seafile_api.get_file_id_by_path(repo.repo_id, path)
        except SearpcError as e:
            logger.error(e)
            return api_error(HTTP_520_OPERATION_FAILED,
                             "Failed to get file id by path.")
        if not file_id:
            return api_error(status.HTTP_404_NOT_FOUND, "File not found")

        # send stats message
        send_file_access_msg(request, repo, path, 'api')

        file_name = os.path.basename(path)
        token = seafile_api.get_fileserver_access_token(repo.repo_id,
                file_id, 'download', request.user.username, 'False')

        if not token:
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        url = gen_inner_file_get_url(token, file_name)
        file_response = urllib2.urlopen(url)
        content = file_response.read()
        
        try:
            dirent = seafile_api.get_dirent_by_path(repo.repo_id, path)
            if dirent:
                latest_contributor, last_modified = dirent.modifier, dirent.mtime
            else:
                latest_contributor, last_modified = None, 0
        except SearpcError as e:
            logger.error(e)
            latest_contributor, last_modified = None, 0

        return Response({
            "content": content,
            "latest_contributor": email2nickname(latest_contributor),
            "last_modified": last_modified,
            "permission": permission,
            })