def check_filename_with_rename(repo_id, parent_dir, filename): cmmts = seafile_api.get_commit_list(repo_id, 0, 1) latest_commit = cmmts[0] if cmmts else None if not latest_commit: return '' # TODO: what if parrent_dir does not exist? dirents = seafile_api.list_dir_by_commit_and_path(repo_id, latest_commit.id, parent_dir.encode('utf-8')) def no_duplicate(name): for dirent in dirents: if dirent.obj_name == name: return False return True def make_new_name(filename, i): base, ext = os.path.splitext(filename) if ext: new_base = "%s (%d)" % (base, i) return new_base + ext else: return "%s (%d)" % (filename, i) if no_duplicate(filename): return filename else: i = 1 while True: new_name = make_new_name (filename, i) if no_duplicate(new_name): return new_name else: i += 1
def check_filename_with_rename(repo_id, parent_dir, filename): cmmts = seafile_api.get_commit_list(repo_id, 0, 1) latest_commit = cmmts[0] if cmmts else None if not latest_commit: return '' # TODO: what if parrent_dir does not exist? dirents = seafile_api.list_dir_by_commit_and_path( repo_id, latest_commit.id, parent_dir.encode('utf-8')) def no_duplicate(name): for dirent in dirents: if dirent.obj_name == name: return False return True def make_new_name(filename, i): base, ext = os.path.splitext(filename) if ext: new_base = "%s (%d)" % (base, i) return new_base + ext else: return "%s (%d)" % (filename, i) if no_duplicate(filename): return filename else: i = 1 while True: new_name = make_new_name(filename, i) if no_duplicate(new_name): return new_name else: i += 1
def generate_certificate_by_repo(repo): """ Generate Cared Data Certificate by repo """ commits = seafile_api.get_commit_list(repo.id, 0, 1) commit = commit_mgr.load_commit(repo.id, repo.version, commits[0].id) return generate_certificate(repo, commit)
def get_stats_repo(repo_id): ''' Get single repo stats ''' try: repo = seafile_api.get_repo(repo_id) except Exception as e: print ('Error: {}'.format(e)) return # print(repo.__dict__) # group_ids = seafile_api.get_shared_group_ids_by_repo(repo_id) # group = ccnet_api.get_group(int(group_ids[0])) # print( # ccnet_api.get_group(int(group_ids[0])).group_name # ) # return print(HEADER) print(FORMATTER.format( repo_id, repo.name.encode('utf-8'), seafile_api.get_repo_owner(repo_id), repo.encrypted, repo.file_count, len(seafile_api.get_commit_list(repo_id, 0, -1)), repo.size, ))
def get_root_dir(repo): """ Get root commit dir """ commits = seafile_api.get_commit_list(repo.id, 0, 1) commit = commit_mgr.load_commit(repo.id, repo.version, commits[0].id) return fs_mgr.load_seafdir(repo.id, repo.version, commit.root_id)
def get_repo_root_dir(repo_id): """ Get repo root dir from object storage """ repo = get_repo(repo_id) commits = seafile_api.get_commit_list(repo.id, 0, 1) commit = commit_mgr.load_commit(repo.id, repo.version, commits[0].id) dir = fs_mgr.load_seafdir(repo.id, repo.version, commit.root_id) return dir
def check_filename_with_rename(repo_id, parent_dir, obj_name): cmmts = seafile_api.get_commit_list(repo_id, 0, 1) latest_commit = cmmts[0] if cmmts else None if not latest_commit: return '' # TODO: what if parrent_dir does not exist? dirents = seafile_api.list_dir_by_commit_and_path( repo_id, latest_commit.id, parent_dir.encode('utf-8')) exist_obj_names = [dirent.obj_name for dirent in dirents] return get_no_duplicate_obj_name(obj_name, exist_obj_names)
def post(self, request): repo_id = request.POST.get('repo_id') tag_names = request.POST.get('tag_names').split(',') repo = seafile_api.get_repo(repo_id) if repo.head_commit_id is not None: commit_id = repo.head_commit_id else: commit_id = seafile_api.get_commit_list(repo_id, 0, 1)[0].id for name in tag_names: revision_tag, created = RevisionTags.objects.create_revision_tag( repo_id, commit_id, name.strip(), request.user.username) return Response({"success": True}, status=status.HTTP_200_OK)
def test_revert_folder_with_invalid_user_permission(self): # first rename dir new_name = randstring(6) seafile_api.rename_file(self.repo_id, '/', self.folder_name, new_name, self.user_name) new_dir_path = '/' + new_name # get commit list commits = seafile_api.get_commit_list(self.repo_id, -1, -1) # then revert dir data = {'operation': 'revert', 'commit_id': commits[0].id} resp = self.client.post(self.url + '?p=' + new_dir_path, data) self.assertEqual(403, resp.status_code)
def get_repo_last_modify(repo): """ Get last modification time for a repo. If head commit id of a repo is provided, we use that commit as last commit, otherwise falls back to getting last commit of a repo which is time consuming. """ if repo.head_cmmt_id is not None: last_cmmt = seaserv.get_commit(repo.id, repo.version, repo.head_cmmt_id) else: logger = logging.getLogger(__name__) logger.info('[repo %s] head_cmmt_id is missing.' % repo.id) last_cmmt = seafile_api.get_commit_list(repo.id, 0, 1)[0] return last_cmmt.ctime if last_cmmt else 0
def get_commit(repo, commit_id=None): """ Get commit """ try: if commit_id is not None: commit = commit_mgr.load_commit(repo.id, repo.version, commit_id) else: commits = seafile_api.get_commit_list(repo.id, 0, 1) commit = commit_mgr.load_commit(repo.id, repo.version, commits[0].id) except Exception as e: # TODO: logger.error('exception: {}'.format(e)) return commit
def test_revert_folder_with_invalid_user_permission(self): # first rename dir new_name = randstring(6) seafile_api.rename_file(self.repo_id, '/', self.folder_name, new_name, self.user_name) new_dir_path = '/' + new_name # get commit list commits = seafile_api.get_commit_list(self.repo_id, -1, -1) # then revert dir data = { 'operation': 'revert', 'commit_id': commits[0].id } resp = self.client.post(self.url + '?p=' + new_dir_path, data) self.assertEqual(403, resp.status_code)
def get(self, request): """get dtable latest commit id Permission: 1. use dtable_uuid verify jwt from dtable-server """ # argument check dtable_uuid = request.GET.get('dtable_uuid', None) if not dtable_uuid: error_msg = 'dtable_uuid invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # permission check auth = request.META.get('HTTP_AUTHORIZATION', '').split() if not is_valid_jwt(auth, dtable_uuid): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # resource check dtable = DTables.objects.get_dtable_by_uuid(dtable_uuid) if not dtable: error_msg = 'dtable %s not found.' % dtable_uuid return api_error(status.HTTP_404_NOT_FOUND, error_msg) workspace = Workspaces.objects.get_workspace_by_id(dtable.workspace.id) if not workspace: error_msg = 'Workspace not found.' 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) try: current_commit = seafile_api.get_commit_list(repo_id, 0, 1)[0] except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) return Response({'latest_commit_id': current_commit.id})
def get_stats_repo_list(): ''' Get stats for complete list of keeper repos Sorted by number of commits, desc ''' try: repo_list = seafile_api.get_repo_list(0, -1) except Exception as e: print ('Error: {}'.format(e)) return # print("KEEPER repos #: {} ".format(len(repo_list))) repos = [] for r in repo_list: repos.append({"repo": r, "owner": seafile_api.get_repo_owner(r.id), "commits_num": len(seafile_api.get_commit_list(r.id, 0, -1)), } ) repos_sorted_commits_num = sorted(repos, key = lambda i: i['commits_num'],reverse=True) # print(repos_sorted_commits_num) print(HEADER) for r in repos_sorted_commits_num: rr = r['repo'] # print(vars(rr)) print(FORMATTER.format( rr.id, rr.name.encode('utf-8'), r['owner'], rr.encrypted, rr.file_count, r['commits_num'], rr.size, ))
def get_blocks(repo_id, fname, commit_id=None): """Print out blocks of file for repo and commit repo_id: repo id commit_id: commit id """ repo = get_repo(repo_id) commits = seafile_api.get_commit_list(repo.id, 0, MAX_INT) print "commits:", [(c.id, c.ctime) for c in commits] commit_id = commit_id if commit_id else commits[0].id commit = commit_mgr.load_commit(repo.id, repo.version, commit_id) dir = fs_mgr.load_seafdir(repo.id, repo.version, commit.root_id) file = dir.lookup(fname) print "File: %s, commit id: %s, root_id: %s" % (fname, commit_id, commit.root_id) if file: print "blocks: ", file.blocks else: print "No file for this commit!"
def get_latest_commit_root_id(repo): commits = seafile_api.get_commit_list(repo.id, 0, 1) commit = commit_mgr.load_commit(repo.id, repo.version, commits[0].id) return commit.root_id
def get(self, request, repo_id, format=None): """ Return history of library Permission checking: 1. all authenticated user can perform this action. """ # 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) # permission check if check_folder_permission(request, repo_id, '/') is None: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) username = request.user.username try: server_crypto = UserOptions.objects.is_server_crypto(username) except CryptoOptionNotSetError: # Assume server_crypto is ``False`` if this option is not set. server_crypto = False password_set = False if repo.encrypted and \ (repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)): try: ret = seafile_api.is_passwd_set(repo_id, username) if ret == 1: password_set = True 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 password_set: error_msg = 'Library is encrypted, but password is not set in server.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) try: page = int(request.GET.get('page', '1')) per_page = int(request.GET.get('per_page', '100')) except ValueError: page = 1 per_page = 100 if page <= 0: error_msg = 'page invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if per_page <= 0: error_msg = 'per_page invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) start = (page - 1) * per_page limit = per_page + 1 try: all_commits = seafile_api.get_commit_list(repo_id, start, limit) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) items = [] commits = all_commits[:per_page] for commit in commits: if new_merge_with_no_conflict(commit): continue item_info = self.get_item_info(commit) items.append(item_info) result = { 'data': items, 'more': True if len(all_commits) == per_page + 1 else False } return Response(result)
def get_commit_id(repo_id): repo = seafile_api.get_repo(repo_id) commits = seafile_api.get_commit_list(repo.id, 0, 1) return commits[0].id
def do_work(self): self._current_commit_position = 0 repo = seafile_api.get_repo_list(self._current_repo_position, 1) if not repo: return -1 repo = repo[0] logging.info('Start processing repo :%s', repo.repo_id) org_id = get_org_id_by_repo_id(repo.repo_id) repo_id = repo.repo_id if org_id > 0: users_obj = seafile_api.org_get_shared_users_by_repo( org_id, repo_id) owner = seafile_api.get_org_repo_owner(repo_id) else: users_obj = seafile_api.get_shared_users_by_repo(repo_id) owner = seafile_api.get_repo_owner(repo_id) users = [e.user for e in users_obj] + [owner] self._last_commit_id = None if repo_id in self._history_repo.keys(): commit_ids = self.get_repo_last_commits(repo_id) count = 0 k = 0 bk = False while True: temp = [ e.id for e in seafile_api.get_commit_list( repo_id, k * 100, 100) ] if not temp: break # avoid two commit at the same time for commit_id in commit_ids: if commit_id[0] in temp: count += 1 if count == len(commit_ids): self._current_commit_position = k * 100 + temp.index( commit_id[0]) + 1 self._last_commit_id = commit_id[0] bk = True break if bk: break k += 1 else: # keeping _current_commit_position zero will restore all activity records of the repo commit_objs = seafile_api.get_commit_list( repo_id, self._current_commit_position, 1) current_commit_id = [e.id for e in commit_objs][0] self._last_commit_id = current_commit_id self.diff_and_update(repo_id, current_commit_id, org_id, users) start_commit_position = self._current_commit_position count_offest = 0 while True: # get last commit and another commits # avoid current_commit_position expired by generate new record commit_objs = seafile_api.get_commit_list( repo_id, self._current_commit_position - 1, 5) commit_ids = [e.id for e in commit_objs] if not commit_objs or len(commit_objs) == 1: break if self._last_commit_id not in commit_ids or commit_objs[ -1].id == self._last_commit_id: self._current_commit_position += 4 count_offest = 4 else: offset = commit_ids.index(self._last_commit_id) self._current_commit_position += offset current_commit_id = commit_ids[offset + 1] self._last_commit_id = commit_ids[offset + 1] self.diff_and_update(repo_id, current_commit_id, org_id, users) count_offest = 1 count = self._current_commit_position - start_commit_position - count_offest logging.info("%s recover %s activity records" % (repo_id, count))
def get(self, request, repo_id, format=None): """ Return history of library Permission checking: 1. all authenticated user can perform this action. """ # 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) # permission check if check_folder_permission(request, repo_id, '/') is None: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) username = request.user.username try: server_crypto = UserOptions.objects.is_server_crypto(username) except CryptoOptionNotSetError: # Assume server_crypto is ``False`` if this option is not set. server_crypto = False password_set = False if repo.encrypted and \ (repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)): try: ret = seafile_api.is_password_set(repo_id, username) if ret == 1: password_set = True 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 password_set: error_msg = 'Library is encrypted, but password is not set in server.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) try: page = int(request.GET.get('page', '1')) per_page = int(request.GET.get('per_page', '100')) except ValueError: page = 1 per_page = 100 if page <= 0: error_msg = 'page invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if per_page <= 0: error_msg = 'per_page invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) start = (page - 1) * per_page limit = per_page + 1 try: all_commits = seafile_api.get_commit_list(repo_id, start, limit) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) items = [] commits = all_commits[:per_page] for commit in commits: if new_merge_with_no_conflict(commit): continue item_info = self.get_item_info(commit) items.append(item_info) result = { 'data': items, 'more': True if len(all_commits) == per_page + 1 else False } return Response(result)
def test_repo_manipulation(): #test get_system_default_repo_id t_default_repo_id = api.get_system_default_repo_id() assert t_default_repo_id #test create_repo t_repo_id = api.create_repo('test_repo_manipulation', '', USER, passwd=None) assert t_repo_id #test counts_repo t_repo_count = 0 t_repo_count = api.count_repos() assert t_repo_count != 0 #test get_repo ,edit_repo t_new_name = 'n_name' t_new_desc = 'n_desc' t_repo_version = 1 t_repo = api.get_repo(t_repo_id) assert t_repo api.edit_repo(t_repo_id, t_new_name, t_new_desc, USER) t_repo = api.get_repo(t_repo_id) assert t_repo.name == t_new_name and t_repo.desc == t_new_desc #test revert_repo and get_commit t_commit_id_before_changing = t_repo.head_cmmt_id api.post_dir(t_repo_id, '/', 'dir1', USER) t_repo = api.get_repo(t_repo_id) api.revert_repo(t_repo_id, t_commit_id_before_changing, USER) t_repo = api.get_repo(t_repo_id) t_commit_id_after_revert = t_repo.head_cmmt_id t_commit_before_changing = api.get_commit(t_repo_id, t_repo_version, t_commit_id_before_changing) t_commit_after_revert = api.get_commit(t_repo_id, t_repo_version, t_commit_id_after_revert) assert t_commit_before_changing.root_id == t_commit_after_revert.root_id #test is_repo_owner assert api.is_repo_owner(USER, t_repo_id) assert api.is_repo_owner(USER2, t_repo_id) == 0 #test get_repo_owner owner_get = api.get_repo_owner(t_repo_id) assert owner_get == USER #test set_repo_owner api.set_repo_owner(t_repo_id, USER2) assert api.is_repo_owner(USER2, t_repo_id) #test create_enc_repo t_enc_repo_id = '826d1b7b-f110-46f2-8d5e-7b5ac3e11f4d' t_enc_version = 2 t_passwd = '123' magic_and_random_key = api.generate_magic_and_random_key( t_enc_version, t_enc_repo_id, t_passwd) t_magic = magic_and_random_key.magic t_random_key = magic_and_random_key.random_key t_enc_repo_id = api.create_enc_repo(t_enc_repo_id, 'test_encrypted_repo', '', USER, t_magic, t_random_key, t_enc_version) assert t_enc_repo_id == '826d1b7b-f110-46f2-8d5e-7b5ac3e11f4d' #test get_repo_list t_start = -1 t_limit = -1 t_repo_list = api.get_repo_list(t_start, t_limit) assert t_repo_list and len(t_repo_list) t_start = 1 t_limit = 1 t_repo_list = api.get_repo_list(t_start, t_limit) assert t_repo_list and len(t_repo_list) == 1 #test get_owned_repo_list t_repo_list = api.get_owned_repo_list(USER2) assert t_repo_list and len(t_repo_list) #test get_commit_list t_offset = 0 t_limit = 0 t_commit_list = api.get_commit_list(t_repo_id, t_offset, t_limit) assert t_commit_list and len(t_commit_list) == 4 t_offset = 1 t_limit = 1 t_commit_list = api.get_commit_list(t_repo_id, t_offset, t_limit) assert t_commit_list and len(t_commit_list) == 1 #test remove_repo api.remove_repo(t_repo_id) t_repo = api.get_repo(t_repo_id) assert t_repo == None
def get(self, request, token): """ Only used for get dirents in a folder share link. Permission checking: 1, If enable SHARE_LINK_LOGIN_REQUIRED, user must have been authenticated. 2, If enable ENABLE_SHARE_LINK_AUDIT, user must have been authenticated, or have been audited. 3, If share link is encrypted, share link password must have been checked. """ # argument check thumbnail_size = request.GET.get('thumbnail_size', 48) try: thumbnail_size = int(thumbnail_size) except ValueError: error_msg = 'thumbnail_size invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # permission check # check if login required if SHARE_LINK_LOGIN_REQUIRED and \ not request.user.is_authenticated(): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # check share link audit if is_pro_version() and ENABLE_SHARE_LINK_AUDIT and \ not request.user.is_authenticated() and \ not request.session.get('anonymous_email'): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # resource check try: share_link = FileShare.objects.get(token=token) except FileShare.DoesNotExist: error_msg = 'Share link %s not found.' % token return api_error(status.HTTP_404_NOT_FOUND, error_msg) # check share link password if share_link.is_encrypted() and not check_share_link_access(request, token): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if share_link.s_type != 'd': error_msg = 'Share link %s is not a folder share link.' % token return api_error(status.HTTP_400_BAD_REQUEST, error_msg) repo_id = share_link.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) share_link_path = share_link.path request_path = request.GET.get('path', '/') if request_path == '/': path = share_link_path else: path = posixpath.join(share_link_path, request_path.strip('/')) path = normalize_dir_path(path) dir_id = seafile_api.get_dir_id_by_path(repo_id, path) if not dir_id: error_msg = 'Folder %s not found.' % request_path return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: current_commit = seafile_api.get_commit_list(repo_id, 0, 1)[0] dirent_list = seafile_api.list_dir_by_commit_and_path(repo_id, current_commit.id, path, -1, -1) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) result = [] for dirent in dirent_list: # don't return parent folder(share link path) info to user # so use request_path here dirent_path = posixpath.join(request_path, dirent.obj_name) dirent_info = {} dirent_info['size'] = dirent.size dirent_info['last_modified'] = timestamp_to_isoformat_timestr(dirent.mtime) if stat.S_ISDIR(dirent.mode): dirent_info['is_dir'] = True dirent_info['folder_path'] = normalize_dir_path(dirent_path) dirent_info['folder_name'] = dirent.obj_name else: dirent_info['is_dir'] = False dirent_info['file_path'] = normalize_file_path(dirent_path) dirent_info['file_name'] = dirent.obj_name file_type, file_ext = get_file_type_and_ext(dirent.obj_name) if file_type in (IMAGE, XMIND) or \ file_type == VIDEO and ENABLE_VIDEO_THUMBNAIL: if os.path.exists(os.path.join(THUMBNAIL_ROOT, str(thumbnail_size), dirent.obj_id)): req_image_path = posixpath.join(request_path, dirent.obj_name) src = get_share_link_thumbnail_src(token, thumbnail_size, req_image_path) dirent_info['encoded_thumbnail_src'] = urlquote(src) result.append(dirent_info) return Response({'dirent_list': result})
def get_latest_commit_id(repo): commits = seafile_api.get_commit_list(repo.id, 0, 1) return commits[0].id
def get(self, request, token): """ Get dirents of shared download dir. Permission checking: 1. only admin can perform this action. """ try: sharelink = FileShare.objects.get(token=token) except FileShare.DoesNotExist: error_msg = 'Share link %s not found.' % token return api_error(status.HTTP_404_NOT_FOUND, error_msg) repo_id = sharelink.repo_id repo = seafile_api.get_repo(repo_id) if not repo: error_msg = 'Library not found.' return api_error(status.HTTP_404_NOT_FOUND, error_msg) obj_path = sharelink.path obj_id = seafile_api.get_dir_id_by_path(repo_id, obj_path) if not obj_id: error_msg = 'Folder not found.' return api_error(status.HTTP_404_NOT_FOUND, error_msg) req_path = request.GET.get('path', '/') if req_path == '/': real_path = obj_path else: real_path = posixpath.join(obj_path, req_path.strip('/')) if real_path[-1] != '/': real_path += '/' real_obj_id = seafile_api.get_dir_id_by_path(repo_id, real_path) if not real_obj_id: error_msg = 'Folder %s not found.' % req_path return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: current_commit = seafile_api.get_commit_list(repo_id, 0, 1)[0] dirent_list = seafile_api.list_dir_by_commit_and_path( repo_id, current_commit.id, real_path, -1, -1) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) result = [] for dirent in dirent_list: dirent_info = {} dirent_info['obj_name'] = dirent.obj_name dirent_info['path'] = posixpath.join(req_path, dirent.obj_name) dirent_info['size'] = dirent.size dirent_info['last_modified'] = timestamp_to_isoformat_timestr( dirent.mtime) if stat.S_ISDIR(dirent.mode): dirent_info['is_dir'] = True else: dirent_info['is_dir'] = False result.append(dirent_info) return Response(result)
def get(self, request, token): """ Only used for get dirents in a folder share link. Permission checking: 1, If enable SHARE_LINK_LOGIN_REQUIRED, user must have been authenticated. 2, If enable ENABLE_SHARE_LINK_AUDIT, user must have been authenticated, or have been audited. 3, If share link is encrypted, share link password must have been checked. """ # argument check thumbnail_size = request.GET.get('thumbnail_size', 48) try: thumbnail_size = int(thumbnail_size) except ValueError: error_msg = 'thumbnail_size invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # permission check # check if login required if SHARE_LINK_LOGIN_REQUIRED and \ not request.user.is_authenticated(): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # check share link audit if is_pro_version() and ENABLE_SHARE_LINK_AUDIT and \ not request.user.is_authenticated() and \ not request.session.get('anonymous_email'): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # resource check try: share_link= FileShare.objects.get(token=token) except FileShare.DoesNotExist: error_msg = 'Share link %s not found.' % token return api_error(status.HTTP_404_NOT_FOUND, error_msg) # check share link password if share_link.is_encrypted() and not check_share_link_access(request, token): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if share_link.s_type != 'd': error_msg = 'Share link %s is not a folder share link.' % token return api_error(status.HTTP_400_BAD_REQUEST, error_msg) repo_id = share_link.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) share_link_path = share_link.path request_path = request.GET.get('path', '/') if request_path == '/': path = share_link_path else: path = posixpath.join(share_link_path, request_path.strip('/')) path = normalize_dir_path(path) dir_id = seafile_api.get_dir_id_by_path(repo_id, path) if not dir_id: error_msg = 'Folder %s not found.' % request_path return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: current_commit = seafile_api.get_commit_list(repo_id, 0, 1)[0] dirent_list = seafile_api.list_dir_by_commit_and_path(repo_id, current_commit.id, path, -1, -1) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) result = [] for dirent in dirent_list: # don't return parent folder(share link path) info to user # so use request_path here dirent_path = posixpath.join(request_path, dirent.obj_name) dirent_info = {} dirent_info['size'] = dirent.size dirent_info['last_modified'] = timestamp_to_isoformat_timestr(dirent.mtime) if stat.S_ISDIR(dirent.mode): dirent_info['is_dir'] = True dirent_info['folder_path'] = normalize_dir_path(dirent_path) dirent_info['folder_name'] = dirent.obj_name else: dirent_info['is_dir'] = False dirent_info['file_path'] = normalize_file_path(dirent_path) dirent_info['file_name'] = dirent.obj_name file_type, file_ext = get_file_type_and_ext(dirent.obj_name) if file_type in (IMAGE, XMIND) or \ file_type == VIDEO and ENABLE_VIDEO_THUMBNAIL: if os.path.exists(os.path.join(THUMBNAIL_ROOT, str(thumbnail_size), dirent.obj_id)): req_image_path = posixpath.join(request_path, dirent.obj_name) src = get_share_link_thumbnail_src(token, thumbnail_size, req_image_path) dirent_info['encoded_thumbnail_src'] = urlquote(src) result.append(dirent_info) return Response({'dirent_list': result})