def mv_dirents(request, src_repo_id, src_path, dst_repo_id, dst_path, obj_file_names, obj_dir_names): result = {} content_type = 'application/json; charset=utf-8' username = request.user.username failed = [] allowed_files = [] allowed_dirs = [] # check parent dir perm for files if check_folder_permission(request, src_repo_id, src_path) != 'rw': allowed_files = [] failed += obj_file_names else: allowed_files = obj_file_names for obj_name in obj_dir_names: src_dir = posixpath.join(src_path, obj_name) if dst_path.startswith(src_dir + '/'): error_msg = _(u'Can not move directory %(src)s to its subdirectory %(des)s') \ % {'src': escape(src_dir), 'des': escape(dst_path)} result['error'] = error_msg return HttpResponse(json.dumps(result), status=400, content_type=content_type) # check every folder perm if check_folder_permission(request, src_repo_id, src_dir) != 'rw': failed.append(obj_name) else: allowed_dirs.append(obj_name) success = [] url = None for obj_name in allowed_files + allowed_dirs: new_obj_name = check_filename_with_rename(dst_repo_id, dst_path, obj_name) try: res = seafile_api.move_file(src_repo_id, src_path, obj_name, dst_repo_id, dst_path, new_obj_name, replace=False, username=username, need_progress=1) except SearpcError as e: logger.error(e) res = None if not res: failed.append(obj_name) else: success.append(obj_name) if len(success) > 0: url = reverse("view_common_lib_dir", args=[dst_repo_id, dst_path.strip('/')]) result = {'success': success, 'failed': failed, 'url': url} return HttpResponse(json.dumps(result), content_type=content_type)
def delete(self, request, repo_id, file_tag_id): """delete a tag from a file """ # 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) file_tag = FileTags.objects.get_file_tag_by_id(file_tag_id) if not file_tag: error_msg = 'file_tag %s not found.' % file_tag_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if check_folder_permission(request, repo_id, '/') != PERMISSION_READ_WRITE: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) try: FileTags.objects.delete_file_tag(file_tag_id) 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({"success": "true"}, status=status.HTTP_200_OK)
def get_file_view_path_and_perm( request, repo_id, obj_id, path, use_onetime=settings.FILESERVER_TOKEN_ONCE_ONLY): """ Get path and the permission to view file. Returns: outer fileserver file url, inner fileserver file url, permission """ username = request.user.username filename = os.path.basename(path) user_perm = check_folder_permission(request, repo_id, '/') if user_perm is None: return ('', '', user_perm) else: # Get a token to visit file token = seafile_api.get_fileserver_access_token( repo_id, obj_id, 'view', username, use_onetime=use_onetime) if not token: return ('', '', None) outer_url = gen_file_get_url(token, filename) inner_url = gen_inner_file_get_url(token, filename) return (outer_url, inner_url, user_perm)
def post(self, request, org_id, format=None): """Create a file draft if the user has read-write permission to the origin file """ repo_id = request.POST.get('repo_id', '') file_path = request.POST.get('file_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) # perm check perm = check_folder_permission(request, repo.id, file_path) if perm != PERMISSION_READ_WRITE: 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 try: d = Draft.objects.add(username, repo, file_path, file_id) return Response(d.to_dict()) except DraftFileExist: return api_error(status.HTTP_409_CONFLICT, 'Draft already exists.') except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)
def post(self, request, format=None): """Create a draft review if the user has read permission to the repo """ draft_id = request.data.get('draft_id', '') try: d = Draft.objects.get(pk=draft_id) except Draft.DoesNotExist: return api_error(status.HTTP_404_NOT_FOUND, 'Draft %s not found.' % draft_id) origin_repo_id = d.origin_repo_id file_path = d.draft_file_path draft_file = seafile_api.get_file_id_by_path(origin_repo_id, file_path) if not draft_file: error_msg = 'Draft file not found.' return api_error(status.HTTP_404_NOT_FOUND, error_msg) # perm check perm = check_folder_permission(request, origin_repo_id, '/') if perm is None: return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') username = request.user.username try: d_r = DraftReview.objects.add(creator=username, draft=d) except (DraftReviewExist): return api_error(status.HTTP_409_CONFLICT, 'Draft review already exists.') # send review status change message send_review_status_msg(request, d_r) return Response(d_r.to_dict())
def get(self, request, repo_id): """ Get file history within certain commits. Controlled by path(rev_renamed_old_path), commit_id and next_start_commit. """ # argument check path = request.GET.get('path', '') if not 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) commit_id = repo.head_cmmt_id try: avatar_size = int(request.GET.get('avatar_size', 32)) page = int(request.GET.get('page', '1')) per_page = int(request.GET.get('per_page', '25')) except ValueError: avatar_size = 32 page = 1 per_page = 25 # Don't use seafile_api.get_file_id_by_path() # if path parameter is `rev_renamed_old_path`. # seafile_api.get_file_id_by_path() will return None. file_id = seafile_api.get_file_id_by_commit_and_path( repo_id, commit_id, path) if not file_id: error_msg = 'File %s not found.' % path return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if not check_folder_permission(request, repo_id, '/'): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) start = (page - 1) * per_page count = per_page try: file_revisions, total_count = get_file_history( repo_id, path, start, count) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) data = [ get_new_file_history_info(ent, avatar_size) for ent in file_revisions ] result = {"data": data, "page": page, "total_count": total_count} return Response(result)
def get(self, request, repo_id, permission_id): """get a custom share permission """ # permission check if not check_folder_permission(request, repo_id, '/'): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') # 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) # main try: permission_obj = CustomSharePermissions.objects.get( id=permission_id) if not permission_obj: return api_error(status.HTTP_404_NOT_FOUND, 'Permission %s not found.' % permission_id) res = permission_obj.to_dict() 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({'permission': res})
def get(self, request, repo_id): """list all tags of a file. """ # argument check file_path = request.GET.get('file_path') if not file_path: error_msg = 'file_path invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) file_path = normalize_file_path(file_path) # 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) file_id = seafile_api.get_file_id_by_path(repo_id, file_path) if not file_id: error_msg = 'File not found.' return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if not check_folder_permission(request, repo_id, '/'): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) try: file_tags = FileTags.objects.get_file_tag_by_path(repo_id, file_path) 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({"file_tags": file_tags}, status=status.HTTP_200_OK)
def group_wiki_use_lib(request, group): if group.view_perm == "pub": raise Http404 if request.method != 'POST': raise Http404 repo_id = request.POST.get('dst_repo', '') username = request.user.username next = reverse('group_wiki', args=[group.id]) repo = seafile_api.get_repo(repo_id) if repo is None: messages.error(request, _('Failed to set wiki library.')) return HttpResponseRedirect(next) if check_folder_permission(request, repo_id, '/') != 'rw': messages.error(request, _('Permission denied.')) return HttpResponseRedirect(next) GroupWiki.objects.save_group_wiki(group_id=group.id, repo_id=repo_id) # create home page if not exist page_name = "home.md" if not seaserv.get_file_id_by_path(repo_id, "/" + page_name): if not seaserv.post_empty_file(repo_id, "/", page_name, username): messages.error(request, _('Failed to create home page. Please retry later')) return HttpResponseRedirect(next)
def delete(self, request, repo_id, format=None): # delete file 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) path = request.GET.get('p', None) if not path: error_msg = 'p invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) file_id = seafile_api.get_file_id_by_path(repo_id, path) if not file_id: return Response({'success': True}) parent_dir = os.path.dirname(path) if check_folder_permission(request, repo_id, parent_dir) != 'rw': error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) parent_dir = os.path.dirname(path) file_name = os.path.basename(path) try: seafile_api.del_file(repo_id, parent_dir, file_name, request.user.username) except SearpcError as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) if request.GET.get('reloaddir', '').lower() == 'true': return reloaddir(request, repo, parent_dir) else: return Response({'success': True})
def view_lib_as_wiki(request, repo_id, path): if not path.startswith('/'): path = '/' + path repo = seafile_api.get_repo(repo_id) is_dir = None file_id = seafile_api.get_file_id_by_path(repo.id, path) if file_id: is_dir = False dir_id = seafile_api.get_dir_id_by_path(repo.id, path) if dir_id: is_dir = True user_perm = check_folder_permission(request, repo.id, '/') if user_perm is None: return render_error(request, _(u'Permission denied')) if user_perm == 'rw': user_can_write = True else: user_can_write = False return render( request, 'view_lib_as_wiki.html', { 'repo_id': repo_id, 'service_url': get_service_url().rstrip('/'), 'initial_path': path, 'is_dir': is_dir, 'repo_name': repo.name, 'permission': user_can_write })
def delete(self, request, repo_id, org_id, format=None): """ User delete a repo shared to him/her. """ 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 check_folder_permission(request, repo_id, '/'): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) username = request.user.username repo_owner = get_repo_owner(request, repo_id) try: if org_id: is_org = True seafile_api.org_remove_share(org_id, repo_id, repo_owner, username) else: is_org = False seafile_api.remove_share(repo_id, repo_owner, username) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) permission = check_user_share_in_permission(repo_id, username, is_org) send_perm_audit_msg('delete-repo-perm', repo_owner, username, repo_id, '/', permission) return Response({'success': True})
def repo_history_view(request, repo_id): """View repo in history. """ repo = get_repo(repo_id) if not repo: raise Http404 username = request.user.username path = get_path_from_request(request) user_perm = check_folder_permission(request, repo.id, '/') if user_perm is None: return render_error(request, _(u'Permission denied')) 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 reverse_url = HASH_URLS["VIEW_COMMON_LIB_DIR"] % { 'repo_id': repo_id, 'path': '' } if repo.encrypted and \ (repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)) \ and not is_password_set(repo.id, username): return render( request, 'decrypt_repo_form.html', { 'repo': repo, 'next': get_next_url_from_request(request) or reverse_url, }) commit_id = request.GET.get('commit_id', None) if commit_id is None: return HttpResponseRedirect(reverse_url) current_commit = get_commit(repo.id, repo.version, commit_id) if not current_commit: current_commit = get_commit(repo.id, repo.version, repo.head_cmmt_id) file_list, dir_list, dirent_more = get_repo_dirents( request, repo, current_commit, path) zipped = get_nav_path(path, repo.name) repo_owner = seafile_api.get_repo_owner(repo.id) is_repo_owner = True if username == repo_owner else False referer = request.GET.get('referer', '') return render( request, 'repo_history_view.html', { 'repo': repo, "is_repo_owner": is_repo_owner, 'user_perm': user_perm, 'current_commit': current_commit, 'dir_list': dir_list, 'file_list': file_list, 'path': path, 'zipped': zipped, 'referer': referer, })
def get(self, request, repo_id): """list all tags of a file. """ # argument check file_path = request.GET.get('file_path') if not file_path: error_msg = 'file_path invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) file_path = normalize_file_path(file_path) # 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) file_id = seafile_api.get_file_id_by_path(repo_id, file_path) if not file_id: error_msg = 'File not found.' return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if not check_folder_permission(request, repo_id, '/'): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) try: file_tags = FileTags.objects.get_file_tag_by_path( repo_id, file_path) 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({"file_tags": file_tags}, status=status.HTTP_200_OK)
def delete(self, request, repo_id, file_tag_id): """delete a tag from a file """ # 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) file_tag = FileTags.objects.get_file_tag_by_id(file_tag_id) if not file_tag: error_msg = 'file_tag %s not found.' % file_tag_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if check_folder_permission(request, repo_id, '/') != PERMISSION_READ_WRITE: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) try: FileTags.objects.delete_file_tag(file_tag_id) 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({"success": "true"}, status=status.HTTP_200_OK)
def get(self, request, token): """ Get library/file/folder info via smart link token. """ uuid_map = FileUUIDMap.objects.get_fileuuidmap_by_uuid(token) if not uuid_map: error_msg = 'token invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) repo_id = uuid_map.repo_id parent_path = uuid_map.parent_path filename = uuid_map.filename is_dir = uuid_map.is_dir # permission check if not check_folder_permission(request, repo_id, parent_path): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) full_path = posixpath.join(parent_path, filename) result = {} result['repo_id'] = repo_id result['path'] = full_path result['is_dir'] = is_dir return Response(result)
def thumbnail_get(request, repo_id, size, path): """ handle thumbnail src from repo file list return thumbnail file to web """ try: size = int(size) except ValueError as e: logger.error(e) return HttpResponse() obj_id = get_file_id_by_path(repo_id, path) if check_folder_permission(request, repo_id, path) is None \ or obj_id is None: return HttpResponse() thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id) if not os.path.exists(thumbnail_file) and \ allow_generate_thumbnail(request, repo_id, path): generate_thumbnail(request, repo_id, size, path) try: with open(thumbnail_file, 'rb') as f: thumbnail = f.read() return HttpResponse(content=thumbnail, mimetype='image/' + THUMBNAIL_EXTENSION) except IOError as e: logger.error(e) return HttpResponse()
def personal_wiki_use_lib(request): if request.method != 'POST': raise Http404 repo_id = request.POST.get('dst_repo', '') username = request.user.username next = reverse('personal_wiki', args=[]) repo = seafile_api.get_repo(repo_id) if repo is None: messages.error(request, _('Failed to set wiki library.')) return HttpResponseRedirect(next) if check_folder_permission(request, repo_id, '/') != 'rw': messages.error(request, _('Permission denied.')) return HttpResponseRedirect(next) PersonalWiki.objects.save_personal_wiki(username=username, repo_id=repo_id) # create home page if not exist page_name = "home.md" if not seaserv.get_file_id_by_path(repo_id, "/" + page_name): if not seaserv.post_empty_file(repo_id, "/", page_name, username): messages.error(request, _('Failed to create home page. Please retry later')) return HttpResponseRedirect(next)
def put(self, request, pk, format=None): """Publish a draft if the user has read-write permission to the origin file """ op = request.data.get('operation', '') if op != 'publish': return api_error(status.HTTP_400_BAD_REQUEST, 'Operation invalid.') try: d = Draft.objects.get(pk=pk) except Draft.DoesNotExist: return api_error(status.HTTP_404_NOT_FOUND, 'Draft %s not found.' % pk) # perm check repo_id = d.origin_repo_id uuid = d.origin_file_uuid perm = check_folder_permission(request, repo_id, uuid.parent_path) if perm != PERMISSION_READ_WRITE: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) username = request.user.username try: d.publish(operator=username) d.delete(operator=username) return Response(status.HTTP_200_OK) except DraftFileConflict: return api_error( status.HTTP_409_CONFLICT, 'There is a conflict between the draft and the original file') except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)
def repo_history_changes(request, repo_id): changes = {} content_type = 'application/json; charset=utf-8' repo = get_repo(repo_id) if not repo: err_msg = _('Library does not exist.') return HttpResponse(json.dumps({'error': err_msg}), status=400, content_type=content_type) # perm check if check_folder_permission(request, repo_id, '/') is None: if request.user.is_staff is True: pass # Allow system staff to check repo changes else: err_msg = _("Permission denied") return HttpResponse(json.dumps({"error": err_msg}), status=403, content_type=content_type) 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 if repo.encrypted and \ (repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)) \ and not seafile_api.is_password_set(repo_id, username): err_msg = _('Library is encrypted.') return HttpResponse(json.dumps({'error': err_msg}), status=403, content_type=content_type) commit_id = request.GET.get('commit_id', '') if not commit_id: err_msg = _('Argument missing') return HttpResponse(json.dumps({'error': err_msg}), status=400, content_type=content_type) changes = get_diff(repo_id, '', commit_id) c = get_commit(repo.id, repo.version, commit_id) if c.parent_id is None: # A commit is a first commit only if it's parent id is None. changes['cmt_desc'] = repo.desc elif c.second_parent_id is None: # Normal commit only has one parent. if c.desc.startswith('Changed library'): changes['cmt_desc'] = _('Changed library name or description') else: # A commit is a merge only if it has two parents. changes['cmt_desc'] = _('No conflict in the merge.') changes['date_time'] = tsstr_sec(c.ctime) return HttpResponse(json.dumps(changes), content_type=content_type)
def delete_dirents(request, repo_id): """ Delete multi files/dirs with ajax. """ content_type = 'application/json; charset=utf-8' repo = get_repo(repo_id) if not repo: err_msg = _(u'Library does not exist.') return HttpResponse(json.dumps({'error': err_msg}), status=400, content_type=content_type) # argument checking parent_dir = request.GET.get("parent_dir") dirents_names = request.POST.getlist('dirents_names') if not (parent_dir and dirents_names): err_msg = _(u'Argument missing.') return HttpResponse(json.dumps({'error': err_msg}), status=400, content_type=content_type) # permission checking username = request.user.username deleted = [] undeleted = [] for dirent_name in dirents_names: full_path = posixpath.join(parent_dir, dirent_name) if check_folder_permission(request, repo.id, full_path) != 'rw': undeleted.append(dirent_name) continue try: seafile_api.del_file(repo_id, parent_dir, dirent_name, username) deleted.append(dirent_name) except SearpcError, e: logger.error(e) undeleted.append(dirent_name)
def repo_history_view(request, repo_id): """View repo in history. """ repo = get_repo(repo_id) if not repo: raise Http404 username = request.user.username path = get_path_from_request(request) user_perm = check_folder_permission(request, repo.id, '/') if user_perm is None: return render_error(request, _(u'Permission denied')) 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 if repo.encrypted and \ (repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)) \ and not is_password_set(repo.id, username): return render_to_response( 'decrypt_repo_form.html', { 'repo': repo, 'next': get_next_url_from_request(request) or reverse('repo', args=[repo.id]), 'force_server_crypto': FORCE_SERVER_CRYPTO, }, context_instance=RequestContext(request)) commit_id = request.GET.get('commit_id', None) if commit_id is None: return HttpResponseRedirect(reverse('repo', args=[repo.id])) current_commit = get_commit(repo.id, repo.version, commit_id) if not current_commit: current_commit = get_commit(repo.id, repo.version, repo.head_cmmt_id) file_list, dir_list, dirent_more = get_repo_dirents( request, repo, current_commit, path) zipped = get_nav_path(path, repo.name) repo_owner = seafile_api.get_repo_owner(repo.id) is_repo_owner = True if username == repo_owner else False return render_to_response( 'repo_history_view.html', { 'repo': repo, "is_repo_owner": is_repo_owner, 'user_perm': user_perm, 'current_commit': current_commit, 'dir_list': dir_list, 'file_list': file_list, 'path': path, 'zipped': zipped, }, context_instance=RequestContext(request))
def delete(self, request, pk): """Delete a reviewer """ try: r = DraftReview.objects.get(pk=pk) except DraftReview.DoesNotExist: return api_error(status.HTTP_404_NOT_FOUND, 'Review %s not found' % pk) perm = check_folder_permission(request, r.origin_repo_id, '/') if perm is None: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) reviewer = request.GET.get('username') if reviewer is None: return api_error(status.HTTP_400_BAD_REQUEST, 'Email %s invalid.' % reviewer) try: reviewer_obj = ReviewReviewer.objects.get(reviewer=reviewer, review_id=r) except ReviewReviewer.DoesNotExist: return Response(status.HTTP_200_OK) reviewer_obj.delete() return Response(status.HTTP_200_OK)
def delete(self, request, pk): """Delete a reviewer """ try: d = Draft.objects.get(pk=pk) except Draft.DoesNotExist: return api_error(status.HTTP_404_NOT_FOUND, 'Draft %s not found' % pk) perm = check_folder_permission(request, d.origin_repo_id, '/') if perm is None: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) reviewer = request.GET.get('username') if reviewer is None: return api_error(status.HTTP_400_BAD_REQUEST, 'Email %s invalid.' % reviewer) try: reviewer = DraftReviewer.objects.get(reviewer=reviewer, draft=d) except DraftReviewer.DoesNotExist: return Response(status.HTTP_200_OK) reviewer.delete() return Response(status.HTTP_200_OK)
def slug(request, slug, page_name="home"): """Show wiki page. """ # get wiki object or 404 wiki = get_object_or_404(Wiki, slug=slug) # perm check if not wiki.has_read_perm(request.user): raise Http404 req_user = request.user.username if req_user == wiki.username or check_folder_permission( request, wiki.repo_id, '/') == 'rw': user_can_write = True else: user_can_write = False return render( request, "wiki/wiki.html", { "wiki": wiki, "page_name": page_name, "user_can_write": user_can_write, "path": '/' + page_name + '.md', "repo_id": wiki.repo_id, "search_repo_id": wiki.repo_id, "search_wiki": True, })
def put(self, request, repo_id, repo_tag_id): """update one repo_tag """ # argument check tag_name = request.data.get('name') if not tag_name: error_msg = 'name invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) tag_color = request.data.get('color') if not tag_color: error_msg = 'color invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # resource check repo_tag = RepoTags.objects.get_repo_tag_by_id(repo_tag_id) if not repo_tag: error_msg = 'repo_tag not found.' return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if check_folder_permission(request, repo_id, '/') != PERMISSION_READ_WRITE: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) try: repo_tag.name = tag_name repo_tag.color = tag_color repo_tag.save() 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({"repo_tag": repo_tag.to_dict()}, status=status.HTTP_200_OK)
def post(self, request, repo_id, format=None): """Post a comments of a file. """ # argument check path = request.GET.get('p', '/').rstrip('/') if not path: return api_error(status.HTTP_400_BAD_REQUEST, 'Wrong path.') comment = request.data.get('comment', '') if not comment: return api_error(status.HTTP_400_BAD_REQUEST, 'Comment can not be empty.') try: avatar_size = int(request.GET.get('avatar_size', AVATAR_DEFAULT_SIZE)) except ValueError: avatar_size = AVATAR_DEFAULT_SIZE # resource check try: file_id = seafile_api.get_file_id_by_path(repo_id, path) except SearpcError as e: logger.error(e) return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Internal Server Error') if not file_id: return api_error(status.HTTP_404_NOT_FOUND, 'File not found.') # permission check if check_folder_permission(request, repo_id, '/') is None: return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') detail = request.data.get('detail', '') username = request.user.username file_comment = FileComment.objects.add_by_file_path( repo_id=repo_id, file_path=path, author=username, comment=comment, detail=detail) repo = seafile_api.get_repo(repo_id) repo_owner = get_repo_owner(request, repo.id) if is_draft_file(repo_id, path): draft = Draft.objects.filter(origin_repo_id=repo_id, draft_file_path=path) if draft: draft = draft[0] comment_draft_successful.send(sender=None, draft=draft, comment=comment, author=username) else: Draft.DoesNotExist else: comment_file_successful.send(sender=None, repo=repo, repo_owner=repo_owner, file_path=path, comment=comment, author=username) comment = file_comment.to_dict() comment.update(user_to_dict(username, request=request, avatar_size=avatar_size)) return Response(comment, status=201)
def delete(self, request): """ Unstar a file/folder. Permission checking: 1. all authenticated user can perform this action. 2. r/rw permission """ # argument check repo_id = request.GET.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.GET.get('path', None) if not path: error_msg = 'path invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # permission check if not check_folder_permission(request, repo_id, '/'): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # unstar a item email = request.user.username try: UserStarredFiles.objects.delete_starred_item(email, 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) return Response({'success': True})
def put(self, request, pk, format=None): """Publish a draft if the user has read-write permission to the origin file """ op = request.data.get('operation', '') if op != 'publish': return api_error(status.HTTP_400_BAD_REQUEST, 'Operation invalid.') try: d = Draft.objects.get(pk=pk) except Draft.DoesNotExist: return api_error(status.HTTP_404_NOT_FOUND, 'Draft %s not found.' % pk) # perm check repo_id = d.origin_repo_id uuid = d.origin_file_uuid file_path = posixpath.join(uuid.parent_path, uuid.filename) perm = check_folder_permission(request, repo_id, file_path) if perm != PERMISSION_READ_WRITE: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) try: d.publish() d.delete() return Response(status.HTTP_200_OK) except (DraftFileConflict, IntegrityError): return api_error( status.HTTP_409_CONFLICT, 'There is a conflict between the draft and the original file')
def get(self, request, repo_id, format=None): """List all users who can view this library. Not support public repo """ # 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 not check_folder_permission(request, repo_id, '/'): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') # org check org_id = None if is_org_context(request): org_id = request.user.org.org_id # main user_list = list() try: related_user_list = get_related_users_by_repo(repo_id, org_id) for email in related_user_list: user_info = get_user_common_info(email) user_list.append(user_info) except Exception as e: logger.error(e) return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Internal Server Error') return Response({'user_list': user_list})
def review(request, pk): d_r = get_object_or_404(DraftReview, pk=pk) # check perm uuid = d_r.origin_file_uuid file_path = posixpath.join(uuid.parent_path, uuid.filename) origin_repo_id = d_r.origin_repo_id permission = check_folder_permission(request, origin_repo_id, '/') if not permission: return render_permission_error(request, _(u'Permission denied.')) draft_file_name = os.path.basename(d_r.draft_file_path) user_info = user_to_dict(d_r.creator, avatar_size=32) return render(request, "draft_review.html", { "draft_id": d_r.draft_id_id, "review_id": pk, "draft_repo_id": d_r.origin_repo_id, "draft_origin_repo_id": d_r.origin_repo_id, "draft_origin_file_path": file_path, "draft_file_path": d_r.draft_file_path, "draft_file_name": draft_file_name, "origin_file_version": d_r.origin_file_version, "publish_file_version": d_r.publish_file_version, "status": d_r.status, "permission": permission, "author": user_info['user_name'], 'author_avatar_url': user_info['avatar_url'] })
def get(self, request, repo_id): """list all repo_tags by repo_id. """ # 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) tags = [] try: tag_list = RepoTags.objects.get_all_by_repo_id(repo_id) except Exception as e: logger.error(e) error_msg = 'Internal Server Error.' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) for tag in tag_list: tags.append(tag.to_dict()) return Response({"repo_tags": tags}, status=status.HTTP_200_OK)
def get(self, request, repo_id): """ Get file history within certain commits. Controlled by path(rev_renamed_old_path), commit_id and next_start_commit. """ # argument check path = request.GET.get('path', '') if not 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) commit_id = repo.head_cmmt_id try: avatar_size = int(request.GET.get('avatar_size', 32)) page = int(request.GET.get('page', '1')) per_page = int(request.GET.get('per_page', '25')) except ValueError: avatar_size = 32 page = 1 per_page = 25 # Don't use seafile_api.get_file_id_by_path() # if path parameter is `rev_renamed_old_path`. # seafile_api.get_file_id_by_path() will return None. file_id = seafile_api.get_file_id_by_commit_and_path(repo_id, commit_id, path) if not file_id: error_msg = 'File %s not found.' % path return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if not check_folder_permission(request, repo_id, '/'): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) start = (page - 1) * per_page count = per_page try: file_revisions, total_count = get_file_history(repo_id, path, start, count) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) data = [get_new_file_history_info(ent, avatar_size) for ent in file_revisions] result = { "data": data, "page": page, "total_count": total_count } return Response(result)
def post(self, request, org_id, format=None): """Create a file draft if the user has read permission to the origin file """ repo_id = request.POST.get('repo_id', '') file_path = request.POST.get('file_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) # 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 try: d = Draft.objects.add(username, repo, file_path, file_id) return Response(d.to_dict()) except (DraftFileExist, IntegrityError): return api_error(status.HTTP_409_CONFLICT, 'Draft already exists.')
def delete_dirent(request, repo_id): """ Delete a file/dir with ajax. """ content_type = 'application/json; charset=utf-8' repo = get_repo(repo_id) if not repo: err_msg = _(u'Library does not exist.') return HttpResponse(json.dumps({'error': err_msg}), status=400, content_type=content_type) # argument checking parent_dir = request.GET.get("parent_dir", None) dirent_name = request.GET.get("name", None) if not (parent_dir and dirent_name): err_msg = _(u'Argument missing.') return HttpResponse(json.dumps({'error': err_msg}), status=400, content_type=content_type) full_path = posixpath.join(parent_dir, dirent_name) username = request.user.username if seafile_api.get_dir_id_by_path(repo.id, full_path) is not None: # when dirent is a dir, check current dir perm if check_folder_permission(request, repo.id, full_path) != 'rw': err_msg = _('Permission denied') return HttpResponse(json.dumps({'error': err_msg}), status=403, content_type=content_type) if seafile_api.get_file_id_by_path(repo.id, full_path) is not None: # when dirent is a file, check parent dir perm if check_folder_permission(request, repo.id, parent_dir) != 'rw': err_msg = _('Permission denied') return HttpResponse(json.dumps({'error': err_msg}), status=403, content_type=content_type) # delete file/dir try: seafile_api.del_file(repo_id, parent_dir, dirent_name, username) return HttpResponse(json.dumps({'success': True}), content_type=content_type) except SearpcError, e: logger.error(e) err_msg = _(u'Internal error. Failed to delete %s.') % escape(dirent_name) return HttpResponse(json.dumps({'error': err_msg}), status=500, content_type=content_type)
def put(self, request, review_id, comment_id, format=None): """Update a comment, only comment author or review creator can perform this op 1.Change resolved of comment 2.Add comment_detail """ # argument check resolved = request.data.get('resolved') if resolved not in ('true', 'false', None): error_msg = 'resolved invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) detail = request.data.get('detail', '') # resource check try: r = DraftReview.objects.get(pk=review_id) except DraftReview.DoesNotExist: return api_error(status.HTTP_404_NOT_FOUND, 'Review %s not found' % review_id) try: review_comment = ReviewComment.objects.get(pk=comment_id) except ReviewComment.DoesNotExist: error_msg = 'Review comment %s not found.' % comment_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if check_folder_permission(request, r.origin_repo_id, '/') is None: return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') if resolved is not None: comment_resolved = to_python_boolean(resolved) try: review_comment.resolved = comment_resolved review_comment.save() except Exception as e: logger.error(e) return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Internal error.') if detail is not None: try: review_comment.detail = detail review_comment.save() except Exception as e: logger.error(e) return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Internal error.') try: avatar_size = int(request.GET.get('avatar_size', AVATAR_DEFAULT_SIZE)) except ValueError: avatar_size = AVATAR_DEFAULT_SIZE username = request.user.username comment = review_comment.to_dict() comment.update(user_to_dict(username, request=request, avatar_size=avatar_size)) return Response(comment)
def get_upload_url(request, repo_id): username = request.user.username if check_folder_permission(request, repo_id, '/') == 'rw': token = seafile_api.get_fileserver_access_token(repo_id, 'dummy', 'upload', username) return gen_file_upload_url(token, 'upload') else: return ''
def post(self, request): """ Create upload link. Permission checking: 1. default(NOT guest) user; 2. user with 'rw' permission; """ # 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) # 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) try: dir_id = seafile_api.get_dir_id_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 dir_id: error_msg = 'folder %s not found.' % path return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if not self._can_generate_shared_link(request): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if check_folder_permission(request, repo_id, path) != 'rw': error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) username = request.user.username uls = UploadLinkShare.objects.get_upload_link_by_path(username, repo_id, path) if not uls: uls = UploadLinkShare.objects.create_upload_link_share(username, repo_id, path, password) link_info = self._get_upload_link_info(uls) return Response(link_info)
def get(self, request, repo_id): """ Return repo info 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 permission = check_folder_permission(request, repo_id, '/') if permission is None: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) username = request.user.username lib_need_decrypt = False if repo.encrypted \ and not seafile_api.is_password_set(repo.id, username): lib_need_decrypt = True repo_owner = get_repo_owner(request, repo_id) try: has_been_shared_out = repo_has_been_shared_out(request, repo_id) except Exception as e: has_been_shared_out = False logger.error(e) result = { "repo_id": repo.id, "repo_name": repo.name, "owner_email": repo_owner, "owner_name": email2nickname(repo_owner), "owner_contact_email": email2contact_email(repo_owner), "size": repo.size, "encrypted": repo.encrypted, "file_count": repo.file_count, "permission": permission, "no_quota": True if seafile_api.check_quota(repo_id) < 0 else False, "is_admin": is_repo_admin(username, repo_id), "is_virtual": repo.is_virtual, "has_been_shared_out": has_been_shared_out, "lib_need_decrypt": lib_need_decrypt, "last_modified": timestamp_to_isoformat_timestr(repo.last_modify), } return Response(result)
def post(self, request, repo_id, format=None): """Post a comments of a file. """ # argument check path = request.GET.get('p', '/').rstrip('/') if not path: return api_error(status.HTTP_400_BAD_REQUEST, 'Wrong path.') comment = request.data.get('comment', '') if not comment: return api_error(status.HTTP_400_BAD_REQUEST, 'Comment can not be empty.') try: avatar_size = int(request.GET.get('avatar_size', AVATAR_DEFAULT_SIZE)) except ValueError: avatar_size = AVATAR_DEFAULT_SIZE # resource check try: file_id = seafile_api.get_file_id_by_path(repo_id, path) except SearpcError as e: logger.error(e) return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Internal error.') if not file_id: return api_error(status.HTTP_404_NOT_FOUND, 'File not found.') # permission check if check_folder_permission(request, repo_id, '/') is None: return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') detail = request.data.get('detail', '') username = request.user.username file_comment = FileComment.objects.add_by_file_path( repo_id=repo_id, file_path=path, author=username, comment=comment, detail=detail) repo = seafile_api.get_repo(repo_id) repo_owner = get_repo_owner(request, repo.id) if is_draft_file(repo_id, path): draft = Draft.objects.get(origin_repo_id=repo_id, draft_file_path=path) comment_draft_successful.send(sender=None, draft=draft, comment=comment, author=username) else: comment_file_successful.send(sender=None, repo=repo, repo_owner=repo_owner, file_path=path, comment=comment, author=username) comment = file_comment.to_dict() comment.update(user_to_dict(username, request=request, avatar_size=avatar_size)) return Response(comment, status=201)
def delete(self, request, repo_id, format=None): """ Delete file. Permission checking: 1. user with 'rw' permission. """ # argument check path = request.GET.get('p', None) if not path: error_msg = 'p invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) path = normalize_file_path(path) # 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) file_id = seafile_api.get_file_id_by_path(repo_id, path) if not file_id: return Response({'success': True}) # permission check parent_dir = os.path.dirname(path) username = request.user.username if check_folder_permission(request, repo_id, parent_dir) != PERMISSION_READ_WRITE: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # check file lock try: is_locked, locked_by_me = check_file_lock(repo_id, path, 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 is_locked and not locked_by_me: error_msg = _("File is locked") return api_error(status.HTTP_403_FORBIDDEN, error_msg) # delete file file_name = os.path.basename(path) try: seafile_api.del_file(repo_id, parent_dir, file_name, request.user.username) except SearpcError as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) return Response({'success': True})
def put(self, request, repo_id, format=None): """ Currently only for lock and unlock file operation. Permission checking: 1. user with 'rw' permission for current file; """ if not is_pro_version(): error_msg = 'file lock feature only supported in professional edition.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # argument check path = request.GET.get('p', None) if not path: error_msg = 'p invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) operation = request.data.get('operation', None) if not operation: error_msg = 'operation invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) operation = operation.lower() if operation not in ('lock', 'unlock'): error_msg = "operation can only be 'lock', or 'unlock'." 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) file_id = seafile_api.get_file_id_by_path(repo_id, path) if not file_id: error_msg = 'File %s not found.' % path return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check parent_dir = os.path.dirname(path) if check_folder_permission(request, repo_id, parent_dir) != 'rw': error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) username = request.user.username is_locked, locked_by_me = check_file_lock(repo_id, path, username) if operation == 'lock': if not is_locked: # lock file expire = request.data.get('expire', FILE_LOCK_EXPIRATION_DAYS) try: seafile_api.lock_file(repo_id, path.lstrip('/'), username, expire) except SearpcError, e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)
def get(self, request, repo_id, format=None): # list dir 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) path = request.GET.get('p', '/') if path[-1] != '/': path = path + '/' try: dir_id = seafile_api.get_dir_id_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 dir_id: error_msg = 'Folder %s not found.' % path return api_error(status.HTTP_404_NOT_FOUND, error_msg) if check_folder_permission(request, repo_id, path) is None: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) old_oid = request.GET.get('oid', None) if old_oid and old_oid == dir_id: resp = Response({'success': True}) resp["oid"] = dir_id return resp else: request_type = request.GET.get('t', None) if request_type and request_type not in ('f', 'd'): error_msg = "'t'(type) should be 'f' or 'd'." return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if request_type == 'd': recursive = request.GET.get('recursive', '0') if recursive not in ('1', '0'): error_msg = "If you want to get recursive dir entries, you should set 'recursive' argument as '1'." return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if recursive == '1': username = request.user.username dir_list = get_dir_recursively(username, repo_id, path, []) dir_list.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower())) resp = Response(dir_list) resp["oid"] = dir_id resp["dir_perm"] = seafile_api.check_permission_by_path(repo_id, path, username) return resp return get_dir_entrys_by_id(request, repo, path, dir_id, request_type)
def has_read_perm(self, request): from seahub.views import check_folder_permission if self.permission == 'public': return True else: # private if not request.user.is_authenticated(): return False repo_perm = check_folder_permission(request, self.repo_id, '/') if not repo_perm: return False return True
def get_shared_upload_link(request): """ Handle ajax request to generate dir upload link. """ content_type = 'application/json; charset=utf-8' repo_id = request.GET.get('repo_id', '') path = request.GET.get('p', '') use_passwd = True if int(request.POST.get('use_passwd', '0')) == 1 else False passwd = request.POST.get('passwd') if use_passwd else None if not (repo_id and path): err = _('Invalid arguments') data = json.dumps({'error': err}) return HttpResponse(data, status=400, content_type=content_type) if path == '/': # can not share root dir err = _('You cannot share the library in this way.') data = json.dumps({'error': err}) return HttpResponse(data, status=400, content_type=content_type) else: if path[-1] != '/': # append '/' at end of path path += '/' repo = seaserv.get_repo(repo_id) if not repo: messages.error(request, _(u'Library does not exist')) return HttpResponse(status=400, content_type=content_type) user_perm = check_folder_permission(repo.id, path, request.user.username) if user_perm == 'r': messages.error(request, _(u'Permission denied')) return HttpResponse(status=403, content_type=content_type) elif user_perm == 'rw': l = UploadLinkShare.objects.filter(repo_id=repo_id).filter( username=request.user.username).filter(path=path) if len(l) > 0: upload_link = l[0] token = upload_link.token else: username = request.user.username uls = UploadLinkShare.objects.create_upload_link_share( username, repo_id, path, passwd) token = uls.token shared_upload_link = gen_shared_upload_link(token) data = json.dumps({'token': token, 'shared_upload_link': shared_upload_link}) return HttpResponse(data, status=200, content_type=content_type) else: messages.error(request, _(u'Operation failed')) return HttpResponse(json.dumps(), status=500, content_type=content_type)
def get(self, request, repo_id): """list all repo_tags by repo_id. """ # argument check include_file_count = request.GET.get('include_file_count', 'true') if include_file_count not in ['true', 'false']: error_msg = 'include_file_count invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) include_file_count = to_python_boolean(include_file_count) # 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 not check_folder_permission(request, repo_id, '/'): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # get files tags files_count = defaultdict(int) if include_file_count: try: files_tags = FileTags.objects.select_related('repo_tag').filter(repo_tag__repo_id=repo_id) except Exception as e: logger.error(e) error_msg = 'Internal Server Error.' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) for file_tag in files_tags: files_count[file_tag.repo_tag_id] += 1 repo_tags = [] try: repo_tag_list = RepoTags.objects.get_all_by_repo_id(repo_id) except Exception as e: logger.error(e) error_msg = 'Internal Server Error.' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) for repo_tag in repo_tag_list: res = repo_tag.to_dict() repo_tag_id = res["repo_tag_id"] if files_count.has_key(repo_tag_id): res["files_count"] = files_count[repo_tag_id] else: res["files_count"] = 0 repo_tags.append(res) return Response({"repo_tags": repo_tags}, status=status.HTTP_200_OK)
def get(self, request, repo_id, format=None): """List all comments of a file. """ path = request.GET.get('p', '/').rstrip('/') if not path: return api_error(status.HTTP_400_BAD_REQUEST, 'Wrong path.') resolved = request.GET.get('resolved', None) if resolved not in ('true', 'false', None): error_msg = 'resolved invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # permission check if check_folder_permission(request, repo_id, '/') is None: return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') try: avatar_size = int(request.GET.get('avatar_size', AVATAR_DEFAULT_SIZE)) page = int(request.GET.get('page', '1')) per_page = int(request.GET.get('per_page', '25')) except ValueError: avatar_size = AVATAR_DEFAULT_SIZE page = 1 per_page = 25 start = (page - 1) * per_page end = page * per_page total_count = FileComment.objects.get_by_file_path(repo_id, path).count() comments = [] if resolved is None: file_comments = FileComment.objects.get_by_file_path(repo_id, path)[start: end] else: comment_resolved = to_python_boolean(resolved) file_comments = FileComment.objects.get_by_file_path(repo_id, path).filter(resolved=comment_resolved)[start: end] for file_comment in file_comments: comment = file_comment.to_dict() comment.update(user_to_dict(file_comment.author, request=request, avatar_size=avatar_size)) comments.append(comment) result = {'comments': comments, 'total_count': total_count} resp = Response(result) base_url = reverse('api2-file-comments', args=[repo_id]) links_header = generate_links_header_for_paginator(base_url, page, per_page, total_count) resp['Links'] = links_header return resp
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 post(self, request, repo_id): """ Check if repo password is correct. Permission checking: 1. User can access current repo. """ # argument check password = request.data.get('password', None) if not password: error_msg = 'password 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 not repo.encrypted: error_msg = 'Library %s is not encrypted.' % repo_id return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # permission check if not check_folder_permission(request, repo_id, '/'): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # check the password is correct try: seafile_api.set_passwd(repo_id, request.user.username, password) except SearpcError as e: if e.msg == 'Bad arguments': error_msg = 'Bad arguments' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) elif e.msg == 'Incorrect password': error_msg = _(u'Wrong password') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) elif e.msg == 'Internal server error': error_msg = _(u'Internal server error') return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) else: error_msg = _(u'Decrypt library error') return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) if ENABLE_RESET_ENCRYPTED_REPO_PASSWORD: add_encrypted_repo_secret_key_to_database(repo_id, password) return Response({'success': True})
def delete(self, request, repo_id, format=None): """ Delete dir. Permission checking: 1. user with 'rw' permission. """ # argument check path = request.GET.get('p', None) if not path: error_msg = 'p invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if path == '/': error_msg = 'Can not delete root path.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # resource check 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) 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, path) != 'rw': error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if path[-1] == '/': path = path[:-1] path = path.rstrip('/') username = request.user.username parent_dir = os.path.dirname(path) dir_name = os.path.basename(path) try: seafile_api.del_file(repo_id, parent_dir, dir_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) return Response({'success': True})
def post(self, request, repo_id): """add a tag for a file. """ # argument check file_path = request.data.get('file_path') if not file_path: error_msg = 'file_path invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) file_path = normalize_file_path(file_path) repo_tag_id = request.data.get('repo_tag_id') if not repo_tag_id: error_msg = 'repo_tag_id 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) file_id = seafile_api.get_file_id_by_path(repo_id, file_path) if not file_id: error_msg = 'File not found.' return api_error(status.HTTP_404_NOT_FOUND, error_msg) repo_tag = RepoTags.objects.get_repo_tag_by_id(repo_tag_id) if not repo_tag: error_msg = 'repo_tag not found.' return api_error(status.HTTP_404_NOT_FOUND, error_msg) file_tag = FileTags.objects.get_file_tag(repo_id, repo_tag_id, file_path) if file_tag: error_msg = 'file tag %s already exist.' % repo_tag_id return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # permission check if check_folder_permission(request, repo_id, '/') != PERMISSION_READ_WRITE: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) try: file_tag = FileTags.objects.add_file_tag(repo_id, repo_tag_id, file_path) 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({"file_tag": file_tag.to_dict()}, status=status.HTTP_201_CREATED)
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) # check perm perm = check_folder_permission(request, repo_id, '/') if not perm: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) result = {} # get draft counts result['draft_counts'] = Draft.objects.get_draft_counts_by_repo_id(repo_id) return Response(result)
def thumbnail_create(request, repo_id): """create thumbnail from repo file list return thumbnail src """ content_type = 'application/json; charset=utf-8' result = {} repo = get_repo(repo_id) path = request.GET.get('path', None) if not repo: err_msg = _(u"Library does not exist.") return HttpResponse(json.dumps({"error": err_msg}), status=403, content_type=content_type) if not path: err_msg = _(u"Invalid arguments.") return HttpResponse(json.dumps({"error": err_msg}), status=403, content_type=content_type) if check_folder_permission(request, repo_id, path) is None: err_msg = _(u"Permission denied.") return HttpResponse(json.dumps({"error": err_msg}), status=403, content_type=content_type) if not allow_generate_thumbnail(request, repo_id, path): err_msg = _(u"Not allowed to generate thumbnail.") return HttpResponse(json.dumps({"error": err_msg}), status=403, content_type=content_type) size = request.GET.get('size', THUMBNAIL_DEFAULT_SIZE) if generate_thumbnail(request, repo_id, size, path): src = get_thumbnail_src(repo_id, size, path) result['encoded_thumbnail_src'] = urlquote(src) return HttpResponse(json.dumps(result), content_type=content_type) else: err_msg = _('Failed to create thumbnail.') return HttpResponse(json.dumps({'err_msg': err_msg}), status=500, content_type=content_type)
def get(self, request, repo_id, format=None): """Get file comment count. """ # recource 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) path = request.GET.get('p', '/') if seafile_api.get_dir_id_by_path(repo_id, path): is_dir = True elif seafile_api.get_file_id_by_path(repo_id, path): is_dir = False else: error_msg = 'Dirent %s not found.' % path return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if not check_folder_permission(request, repo_id, '/'): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if is_dir: ''' SELECT `tags_fileuuidmap`.`filename`, COUNT(`tags_fileuuidmap`.`filename`) AS `total` FROM `base_filecomment` INNER JOIN `tags_fileuuidmap` ON ( `base_filecomment`.`uuid_id` = `tags_fileuuidmap`.`uuid` ) WHERE (`base_filecomment`.`uuid_id`) IN (SELECT U0.`uuid` FROM `tags_fileuuidmap` U0 WHERE (U0.`parent_path` = '/' AND U0.`repo_id` = '4674c2bb-3702-4dd0-b768-8952db27ac87')) GROUP BY `tags_fileuuidmap`.`filename` ORDER BY NULL LIMIT 21 ''' # get comment count of all files in folder qs = FileComment.objects.get_by_parent_path(repo_id, path).values( 'uuid__filename').annotate(total=Count('uuid__filename')) ret = [] for e in qs: ret.append({e['uuid__filename']: e['total']}) else: count = FileComment.objects.get_by_file_path(repo_id, path).count() ret = {} ret[os.path.basename(path)] = count return Response(ret)
def thumbnail_get(request, repo_id, size, path): """ handle thumbnail src from repo file list return thumbnail file to web """ repo = get_repo(repo_id) obj_id = get_file_id_by_path(repo_id, path) # check if file exist if not repo or not obj_id: return HttpResponse() # check if is allowed if repo.encrypted or not ENABLE_THUMBNAIL or \ check_folder_permission(request, repo_id, path) is None: return HttpResponse() try: size = int(size) except ValueError as e: logger.error(e) return HttpResponse() success = True thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), obj_id) if not os.path.exists(thumbnail_file): success, status_code = generate_thumbnail(request, repo_id, size, path) if success: try: with open(thumbnail_file, 'rb') as f: thumbnail = f.read() return HttpResponse(content=thumbnail, content_type='image/' + THUMBNAIL_EXTENSION) except IOError as e: logger.error(e) return HttpResponse() else: return HttpResponse()