def repo_remove_share(request): """ If repo is shared from one person to another person, only these two peson can remove share. If repo is shared from one person to a group, then only the one share the repo and group staff can remove share. """ repo_id = request.GET.get('repo_id', '') group_id = request.GET.get('gid', '') from_email = request.GET.get('from', '') if not is_valid_username(from_email): return render_error(request, _(u'Argument is not valid')) username = request.user.username # if request params don't have 'gid', then remove repos that share to # to other person; else, remove repos that share to groups if not group_id: to_email = request.GET.get('to', '') if not is_valid_username(to_email): return render_error(request, _(u'Argument is not valid')) if username != from_email and username != to_email: return render_permission_error(request, _(u'Failed to remove share')) if is_org_context(request): org_id = request.user.org.org_id org_remove_share(org_id, repo_id, from_email, to_email) else: seaserv.remove_share(repo_id, from_email, to_email) else: try: group_id = int(group_id) except: return render_error(request, _(u'group id is not valid')) group = seaserv.get_group(group_id) if not group: return render_error( request, _(u"Failed to unshare: the group doesn't exist.")) if not seaserv.check_group_staff(group_id, username) \ and username != from_email: return render_permission_error(request, _(u'Failed to remove share')) if is_org_group(group_id): org_id = get_org_id_by_group(group_id) del_org_group_repo(repo_id, org_id, group_id) else: seafile_api.unset_group_repo(repo_id, group_id, from_email) messages.success(request, _('Successfully removed share')) next = request.META.get('HTTP_REFERER', SITE_ROOT) return HttpResponseRedirect(next)
def repo_remove_share(request): """ If repo is shared from one person to another person, only these two peson can remove share. If repo is shared from one person to a group, then only the one share the repo and group staff can remove share. """ repo_id = request.GET.get('repo_id', '') group_id = request.GET.get('gid', '') from_email = request.GET.get('from', '') if not is_valid_username(from_email): return render_error(request, _(u'Argument is not valid')) username = request.user.username # if request params don't have 'gid', then remove repos that share to # to other person; else, remove repos that share to groups if not group_id: to_email = request.GET.get('to', '') if not is_valid_username(to_email): return render_error(request, _(u'Argument is not valid')) if username != from_email and username != to_email: return render_permission_error(request, _(u'Failed to remove share')) if is_org_context(request): org_id = request.user.org.org_id org_remove_share(org_id, repo_id, from_email, to_email) else: seaserv.remove_share(repo_id, from_email, to_email) else: try: group_id = int(group_id) except: return render_error(request, _(u'group id is not valid')) group = seaserv.get_group(group_id) if not group: return render_error(request, _(u"Failed to unshare: the group doesn't exist.")) if not seaserv.check_group_staff(group_id, username) \ and username != from_email: return render_permission_error(request, _(u'Failed to remove share')) if is_org_group(group_id): org_id = get_org_id_by_group(group_id) del_org_group_repo(repo_id, org_id, group_id) else: seafile_api.unset_group_repo(repo_id, group_id, from_email) messages.success(request, _('Successfully removed share')) next = request.META.get('HTTP_REFERER', SITE_ROOT) return HttpResponseRedirect(next)
def repo_remove_share(request): """ If repo is shared from one person to another person, only these two peson can remove share. If repo is shared from one person to a group, then only the one share the repo and group staff can remove share. """ repo_id = request.GET.get('repo_id', '') group_id = request.GET.get('gid', '') from_email = request.GET.get('from', '') if not is_valid_username(from_email): return render_error(request, _(u'Argument is not valid')) # if request params don't have 'gid', then remove repos that share to # to other person; else, remove repos that share to groups if not group_id: to_email = request.GET.get('to', '') if not is_valid_username(to_email): return render_error(request, _(u'Argument is not valid')) if request.user.username != from_email and \ request.user.username != to_email: return render_permission_error(request, _(u'Failed to remove share')) remove_share(repo_id, from_email, to_email) else: try: group_id_int = int(group_id) except: return render_error(request, _(u'group id is not valid')) if not check_group_staff(group_id_int, request.user.username) \ and request.user.username != from_email: return render_permission_error(request, _(u'Failed to remove share')) if is_org_group(group_id_int): org_id = get_org_id_by_group(group_id_int) del_org_group_repo(repo_id, org_id, group_id_int) else: from seahub.group.views import group_unshare_repo group_unshare_repo(request, repo_id, group_id_int, from_email) messages.success(request, _('Successfully removed share')) next = request.META.get('HTTP_REFERER', None) if not next: next = SITE_ROOT return HttpResponseRedirect(next)
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 group_dismiss(request, group_id): """ Dismiss a group, only group staff can perform this operation. """ next = request.META.get('HTTP_REFERER', None) if not next: next = SITE_ROOT try: group_id_int = int(group_id) except ValueError: return HttpResponseRedirect(next) # Check whether user is group staff user = request.user.username if not ccnet_threaded_rpc.check_group_staff(group_id_int, user): return render_permission_error(request, _(u'Only administrators can dismiss the group')) try: ccnet_threaded_rpc.remove_group(group_id_int, user) seafserv_threaded_rpc.remove_repo_group(group_id_int, None) if request.user.org: org_id = request.user.org['org_id'] url_prefix = request.user.org['url_prefix'] ccnet_threaded_rpc.remove_org_group(org_id, group_id_int) return HttpResponseRedirect(reverse('org_groups', args=[url_prefix])) except SearpcError, e: return render_error(request, _(e.msg))
def org_group_remove(request, url_prefix, group_id): # Request header may missing HTTP_REFERER, we need to handle that case. next = request.META.get("HTTP_REFERER", None) if not next: next = seahub_settings.SITE_ROOT try: group_id_int = int(group_id) except ValueError: return HttpResponseRedirect(next) # Check whether is the org group. org_id = get_org_id_by_group(group_id_int) if request.user.org["org_id"] != org_id: return render_permission_error( request, _(u"This group doesn't belong to current organazation"), extra_ctx={"org": request.user.org, "base_template": "org_base.html"}, ) try: ccnet_threaded_rpc.remove_group(group_id_int, request.user.username) seafserv_threaded_rpc.remove_repo_group(group_id_int, None) ccnet_threaded_rpc.remove_org_group(org_id, group_id_int) except SearpcError, e: return render_error(request, e.msg, extra_ctx={"org": request.user.org, "base_template": "org_base.html"})
def repo_history(request, repo_id): """ List library modification histories. """ user_perm = check_folder_permission(request, repo_id, '/') if not user_perm: return render_permission_error(request, _(u'Unable to view library modification')) repo = get_repo(repo_id) if not repo: raise Http404 username = request.user.username try: server_crypto = UserOptions.objects.is_server_crypto(username) except CryptoOptionNotSetError: # Assume server_crypto is ``False`` if this option is not set. server_crypto = False password_set = False if repo.props.encrypted and \ (repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)): try: ret = seafserv_rpc.is_passwd_set(repo_id, username) if ret == 1: password_set = True except SearpcError, e: return render_error(request, e.msg) if not password_set: return HttpResponseRedirect(reverse("view_common_lib_dir", args=[repo_id, '']))
def repo_history(request, repo_id): """ List library modification histories. """ user_perm = check_folder_permission(request, repo_id, '/') if not user_perm: return render_permission_error( request, _(u'Unable to view library modification')) repo = get_repo(repo_id) if not repo: raise Http404 username = request.user.username try: server_crypto = UserOptions.objects.is_server_crypto(username) except CryptoOptionNotSetError: # Assume server_crypto is ``False`` if this option is not set. server_crypto = False password_set = False if repo.props.encrypted and \ (repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)): try: ret = seafserv_rpc.is_passwd_set(repo_id, username) if ret == 1: password_set = True except SearpcError, e: return render_error(request, e.msg) if not password_set: return HttpResponseRedirect( reverse("view_common_lib_dir", args=[repo_id, '']))
def slug(request, slug, file_path="home.md"): """Show wiki page. """ # get wiki object or 404 wiki = get_object_or_404(Wiki, slug=slug) file_path = "/" + file_path is_dir = None file_id = seafile_api.get_file_id_by_path(wiki.repo_id, file_path) if file_id: is_dir = False dir_id = seafile_api.get_dir_id_by_path(wiki.repo_id, file_path) if dir_id: is_dir = True # compatible with old wiki url if is_dir is None: if len(file_path.split('.')) == 1: new_path = file_path[1:] + '.md' return HttpResponseRedirect(reverse('wiki:slug', args=[slug, new_path])) # perm check req_user = request.user.username if not req_user and not wiki.has_read_perm(request): return redirect('auth_login') else: if not wiki.has_read_perm(request): return render_permission_error(request, _(u'Unable to view Wiki')) file_type, ext = get_file_type_and_ext(posixpath.basename(file_path)) if file_type == IMAGE: file_url = reverse('view_lib_file', args=[wiki.repo_id, file_path]) return HttpResponseRedirect(file_url + "?raw=1") if not req_user: user_can_write = False elif req_user == wiki.username or check_folder_permission( request, wiki.repo_id, '/') == 'rw': user_can_write = True else: user_can_write = False is_public_wiki = False if wiki.permission == 'public': is_public_wiki = True return render(request, "wiki/wiki.html", { "wiki": wiki, "page_name": file_path, "user_can_write": user_can_write, "file_path": file_path, "repo_id": wiki.repo_id, "search_repo_id": wiki.repo_id, "search_wiki": True, "is_public_wiki": is_public_wiki, "is_dir": is_dir, })
def dtable_asset_file_view(request, workspace_id, dtable_id, path): # resource check workspace = Workspaces.objects.get_workspace_by_id(workspace_id) if not workspace: return render_error(request, 'Workspace does not exist.') repo_id = workspace.repo_id repo = seafile_api.get_repo(repo_id) if not repo: return render_error(request, 'Library does not exist.') dtable = DTables.objects.get_dtable_by_uuid(dtable_id) if not dtable: return render_error(request, 'DTable does not exist.') asset_path = normalize_file_path(os.path.join('/asset', dtable_id, path)) asset_id = seafile_api.get_file_id_by_path(repo_id, asset_path) if not asset_id: return render_error(request, 'Asset file does not exist.') # permission check username = request.user.username if not check_dtable_permission(username, workspace, dtable): return render_permission_error(request, _('Permission denied.')) file_enc = request.GET.get('file_enc', 'auto') if file_enc not in FILE_ENCODING_LIST: file_enc = 'auto' token = seafile_api.get_fileserver_access_token(repo_id, asset_id, 'view', '', use_onetime=False) file_name = os.path.basename(normalize_file_path(path)) file_type, file_ext = get_file_type_and_ext(file_name) inner_path = gen_inner_file_get_url(token, file_name) error_msg, file_content, encoding = get_file_content( file_type, inner_path, file_enc) raw_path = gen_file_get_url(token, file_name) return_dict = { 'repo': repo, 'filename': file_name, 'file_path': asset_path, 'file_type': file_type, 'file_ext': file_ext, 'raw_path': raw_path, 'file_content': file_content, 'err': 'File preview unsupported' if file_type == 'Unknown' else error_msg, } return render(request, 'dtable_asset_file_view_react.html', return_dict)
def repo_recycle_view(request, repo_id): if not seafile_api.get_dir_id_by_path(repo_id, '/') or \ check_folder_permission(request, repo_id, '/') != 'rw': return render_permission_error(request, _(u'Unable to view recycle page')) commit_id = request.GET.get('commit_id', '') if not commit_id: return render_recycle_root(request, repo_id) else: return render_recycle_dir(request, repo_id, commit_id)
def view_snapshot_file(request, repo_id): ret_dict = {} view_history_file_common(request, repo_id, ret_dict) if not request.user_perm: return render_permission_error(request, _(u"Unable to view file")) # generate file path navigator path = ret_dict["path"] repo = ret_dict["repo"] ret_dict["zipped"] = gen_path_link(path, repo.name) return render_to_response("view_snapshot_file.html", ret_dict, context_instance=RequestContext(request))
def dtable_asset_access(request, workspace_id, dtable_id, path): """ Permission: 1. owner 2. group member 3. shared user with `rw` or `admin` permission """ # asset file type check asset_name = os.path.basename(normalize_file_path(path)) file_type, file_ext = get_file_type_and_ext(asset_name) if file_type != IMAGE: err_msg = 'Invalid file type' return render_error(request, err_msg) # resource check workspace = Workspaces.objects.get_workspace_by_id(workspace_id) if not workspace: raise Http404 repo_id = workspace.repo_id repo = seafile_api.get_repo(repo_id) if not repo: raise Http404 dtable = DTables.objects.get_dtable_by_uuid(dtable_id) if not dtable: raise Http404 asset_path = normalize_file_path(os.path.join('/asset', dtable_id, path)) asset_id = seafile_api.get_file_id_by_path(repo_id, asset_path) if not asset_id: raise Http404 # permission check username = request.user.username owner = workspace.owner if not check_dtable_permission(username, owner) and \ check_dtable_share_permission(dtable, username) not in WRITE_PERMISSION_TUPLE: return render_permission_error(request, _(u'Permission denied.')) dl = request.GET.get('dl', '0') == '1' operation = 'download' if dl else 'view' token = seafile_api.get_fileserver_access_token(repo_id, asset_id, operation, '', use_onetime=False) url = gen_file_get_url(token, asset_name) return HttpResponseRedirect(url)
def thumbnail_get(request, workspace_id, dtable_uuid, path): """ handle thumbnail src from repo file list return thumbnail file to web """ try: size = int(request.GET.get('size')) except Exception as e: logger.error(e) return HttpResponse() else: if size <= 0: return HttpResponse() # resource check workspace = Workspaces.objects.get_workspace_by_id(workspace_id) if not workspace: return HttpResponse() dtable = DTables.objects.get_dtable_by_uuid(dtable_uuid) if not dtable: return HttpResponse() repo_id = workspace.repo_id path = normalize_file_path(os.path.join('/asset', dtable_uuid, path)) file_id = seafile_api.get_file_id_by_path(repo_id, path) if not file_id: return HttpResponse() # permission check username = request.user.username if not (check_dtable_permission(username, workspace, dtable) or \ (request.session.get('external_link') and request.session.get('external_link')['dtable_uuid'] == dtable.uuid.hex)): return render_permission_error(request, _('Permission denied.')) success = True thumbnail_file = os.path.join(THUMBNAIL_ROOT, str(size), file_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(status=500) else: return HttpResponse(status=status_code)
def dir_recycle_view(request, repo_id): dir_path = request.GET.get('dir_path', '') if not seafile_api.get_dir_id_by_path(repo_id, dir_path) or \ check_folder_permission(request, repo_id, dir_path) != 'rw': return render_permission_error(request, _('Unable to view recycle page')) commit_id = request.GET.get('commit_id', '') referer = request.GET.get('referer', '') # for back to 'dir view' page if not commit_id: return render_dir_recycle_root(request, repo_id, dir_path, referer) else: return render_dir_recycle_dir(request, repo_id, commit_id, dir_path, referer)
def view_history_file(request, repo_id): ret_dict = {} view_history_file_common(request, repo_id, ret_dict) if not request.user_perm: return render_permission_error(request, _(u'Unable to view file')) # generate file path navigator path = ret_dict['path'] repo = ret_dict['repo'] ret_dict['zipped'] = gen_path_link(path, repo.name) return render_to_response('view_history_file.html', ret_dict, context_instance=RequestContext(request))
def view_snapshot_file(request, repo_id): ret_dict = {} view_history_file_common(request, repo_id, ret_dict) if not request.user_perm: return render_permission_error(request, _(u'Unable to view file')) # generate file path navigator path = ret_dict['path'] repo = ret_dict['repo'] ret_dict['zipped'] = gen_path_link(path, repo.name) return render_to_response('view_snapshot_file.html', ret_dict, context_instance=RequestContext(request), )
def dtable_file_view(request, workspace_id, name): """ Permission: 1. owner 2. group member 3. shared user """ # resource check workspace = Workspaces.objects.get_workspace_by_id(workspace_id) if not workspace: raise Http404 repo_id = workspace.repo_id repo = seafile_api.get_repo(repo_id) if not repo: raise Http404 dtable = DTables.objects.get_dtable(workspace, name) if not dtable: return render_error(request, _(u'Table does not exist')) table_file_name = name + FILE_TYPE table_path = normalize_file_path(table_file_name) table_file_id = seafile_api.get_file_id_by_path(repo_id, table_path) if not table_file_id: return render_error(request, _(u'Table does not exist')) # permission check username = request.user.username owner = workspace.owner if not check_dtable_permission(username, owner) and \ not check_dtable_share_permission(dtable, username): return render_permission_error(request, _(u'Permission denied.')) return_dict = { '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, 'repo': repo, 'filename': name, 'path': table_path, 'filetype': 'dtable', 'workspace_id': workspace_id, 'dtable_uuid': dtable.uuid.hex, 'media_url': MEDIA_URL, 'dtable_server': DTABLE_SERVER_URL, 'dtable_socket': SEAFILE_COLLAB_SERVER } return render(request, 'dtable_file_view_react.html', return_dict)
def _dtable_asset_access(request, workspace_id, dtable_id, path, asset_name): # resource check workspace = Workspaces.objects.get_workspace_by_id(workspace_id) if not workspace: return render_error(request, 'Workspace does not exist.') repo_id = workspace.repo_id repo = seafile_api.get_repo(repo_id) if not repo: return render_error(request, 'Library does not exist.') dtable = DTables.objects.get_dtable_by_uuid(dtable_id) if not dtable: return render_error(request, 'DTable does not exist.') # use head method to check asset at 'path' wether exists if request.method == 'HEAD': asset_path = normalize_file_path( os.path.join('/asset', dtable_id, path)) asset_id = seafile_api.get_file_id_by_path(repo_id, asset_path) if not asset_id: return HttpResponse(status=404) return HttpResponse(status=200) asset_path = normalize_file_path(os.path.join('/asset', dtable_id, path)) asset_id = seafile_api.get_file_id_by_path(repo_id, asset_path) if not asset_id: return render_error(request, 'Asset file does not exist.') # permission check username = request.user.username if not (check_dtable_permission(username, workspace, dtable) in WRITE_PERMISSION_TUPLE or \ (get_file_type_and_ext(asset_name)[0] == IMAGE and request.session.get('external_link') and request.session.get('external_link')['dtable_uuid'] == dtable.uuid.hex)): return render_permission_error(request, _('Permission denied.')) dl = request.GET.get('dl', '0') == '1' operation = 'download' if dl else 'view' token = seafile_api.get_fileserver_access_token(repo_id, asset_id, operation, '', use_onetime=False) url = gen_file_get_url(token, asset_name) return HttpResponseRedirect(url)
def group_unshare_repo(request, repo_id, group_id, from_email): """ Unshare a repo in group. """ # Check whether group exists group = get_group(group_id) if not group: return render_error(request, _(u"Failed to unshare: the group doesn't exist.")) # Check whether user is group staff or the one share the repo if not check_group_staff(group_id, from_email) and \ seafserv_threaded_rpc.get_group_repo_owner(repo_id) != from_email: return render_permission_error(request, _(u"Operation failed: only administrators and the owner of the library can unshare it.")) if seafserv_threaded_rpc.group_unshare_repo(repo_id, group_id, from_email) != 0: return render_error(request, _(u"Failed to unshare: internal error."))
def draft(request, pk): d = get_object_or_404(Draft, pk=pk) # check perm uuid = FileUUIDMap.objects.get_fileuuidmap_by_uuid(d.origin_file_uuid) origin_repo_id = d.origin_repo_id permission = check_folder_permission(request, origin_repo_id, '/') if not permission: return render_permission_error(request, _(u'Permission denied.')) origin_file_path = posixpath.join(uuid.parent_path, uuid.filename) origin_file = seafile_api.get_file_id_by_path(origin_repo_id, origin_file_path) origin_file_exists = True if not origin_file: origin_file_exists = False draft_file = seafile_api.get_file_id_by_path(origin_repo_id, d.draft_file_path) draft_file_exists = True if not draft_file: draft_file_exists = False draft_file_name = os.path.basename(d.draft_file_path) author_info = user_to_dict(d.username, avatar_size=32) return render( request, "draft.html", { "draft_id": d.id, "draft_repo_id": origin_repo_id, "draft_origin_file_path": origin_file_path, "draft_file_path": d.draft_file_path, "draft_file_name": draft_file_name, "permission": permission, "author": author_info['user_name'], "author_avatar_url": author_info['avatar_url'], "origin_file_exists": origin_file_exists, "draft_file_exists": draft_file_exists, "draft_status": d.status, "publish_file_version": d.publish_file_version, "origin_file_version": d.origin_file_version })
def view_trash_file(request, repo_id): ret_dict = {} view_history_file_common(request, repo_id, ret_dict) if not request.user_perm: return render_permission_error(request, _(u"Unable to view file")) basedir = request.GET.get("base", "") if not basedir: raise Http404 days = show_delete_days(request) ret_dict["basedir"] = basedir ret_dict["days"] = days # generate file path navigator path = ret_dict["path"] repo = ret_dict["repo"] ret_dict["zipped"] = gen_path_link(path, repo.name) return render_to_response("view_trash_file.html", ret_dict, context_instance=RequestContext(request))
def dtable_asset_access(request, workspace_id, dtable_id, path): # asset file type check asset_name = os.path.basename(normalize_file_path(path)) file_type, file_ext = get_file_type_and_ext(asset_name) if file_type != IMAGE: err_msg = 'Invalid file type' return render_error(request, err_msg) # resource check workspace = Workspaces.objects.get_workspace_by_id(workspace_id) if not workspace: raise Http404 repo_id = workspace.repo_id repo = seafile_api.get_repo(repo_id) if not repo: raise Http404 dtable = DTables.objects.get_dtable_by_uuid(dtable_id) if not dtable: raise Http404 asset_path = normalize_file_path(os.path.join('/asset', dtable_id, path)) asset_id = seafile_api.get_file_id_by_path(repo_id, asset_path) if not asset_id: raise Http404 # permission check username = request.user.username owner = workspace.owner if username != owner: return render_permission_error(request, 'Permission denied.') token = seafile_api.get_fileserver_access_token(repo_id, asset_id, 'view', '', use_onetime=False) url = gen_file_get_url(token, asset_name) return HttpResponseRedirect(url)
def dtable_snapshot_view(request, workspace_id, name, commit_id): """ Permission: 1. owner 2. group member 3. shared user """ # resource check workspace = Workspaces.objects.get_workspace_by_id(workspace_id) if not workspace: return render_error(request, 'Workspace does not exist.') dtable = DTables.objects.get_dtable(workspace, name) if not dtable: return render_error(request, 'DTable does not exist.') # permission check username = request.user.username permission = check_dtable_permission(username, workspace, dtable) if not permission: return render_permission_error(request, _('Permission denied.')) snapshot = DTableSnapshot.objects.get_by_commit_id(commit_id) if not snapshot: return render_error(request, 'Snapshot does not exist.') return render( request, 'dtable_snapshot_view_react.html', { 'version': SEATABLE_VERSION, 'dtable_baidu_map_key': DTABLE_BAIDU_MAP_KEY, 'dtable_google_map_key': DTABLE_GOOGLE_MAP_KEY, 'seatable_market_url': SEATABLE_MARKET_URL, 'file_name': dtable.name, 'workspace_id': workspace.id, 'dtable_uuid': dtable.uuid.hex, 'media_url': MEDIA_URL, 'dtable_server': DTABLE_SERVER_URL, 'dtable_socket': DTABLE_SOCKET_URL, 'permission': 'r', 'snapshot_commit_id': commit_id, })
def view_trash_file(request, repo_id): ret_dict = {} view_history_file_common(request, repo_id, ret_dict) if not request.user_perm: return render_permission_error(request, _(u'Unable to view file')) basedir = request.GET.get('base', '') if not basedir: raise Http404 days = show_delete_days(request) ret_dict['basedir'] = basedir ret_dict['days'] = days # generate file path navigator path = ret_dict['path'] repo = ret_dict['repo'] ret_dict['zipped'] = gen_path_link(path, repo.name) return render_to_response('view_trash_file.html', ret_dict, context_instance=RequestContext(request), )
def draft(request, pk): d = get_object_or_404(Draft, pk=pk) # check perm uuid = FileUUIDMap.objects.get_fileuuidmap_by_uuid(d.origin_file_uuid) origin_repo_id = d.origin_repo_id permission = check_folder_permission(request, origin_repo_id, '/') if not permission: return render_permission_error(request, _(u'Permission denied.')) origin_file_path = posixpath.join(uuid.parent_path, uuid.filename) origin_file = seafile_api.get_file_id_by_path(origin_repo_id, origin_file_path) origin_file_exists = True if not origin_file: origin_file_exists = False draft_file = seafile_api.get_file_id_by_path(origin_repo_id, d.draft_file_path) draft_file_exists = True if not draft_file: draft_file_exists = False draft_file_name = os.path.basename(d.draft_file_path) author_info = user_to_dict(d.username, avatar_size=32) return render(request, "draft.html", { "draft_id": d.id, "draft_repo_id": origin_repo_id, "draft_origin_file_path": origin_file_path, "draft_file_path": d.draft_file_path, "draft_file_name": draft_file_name, "permission": permission, "author": author_info['user_name'], "author_avatar_url": author_info['avatar_url'], "origin_file_exists": origin_file_exists, "draft_file_exists": draft_file_exists, "draft_status": d.status, "publish_file_version": d.publish_file_version, "origin_file_version": d.origin_file_version })
def slug(request, slug, file_path="home.md"): """Show wiki page. """ # get wiki object or 404 wiki = get_object_or_404(Wiki, slug=slug) file_path = "/" + file_path # perm check req_user = request.user.username if not req_user: return redirect('auth_login') if not wiki.check_access_wiki(request): return render_permission_error(request, _(u'Permission denied.')) file_type, ext = get_file_type_and_ext(posixpath.basename(file_path)) if file_type == IMAGE: file_url = reverse('view_lib_file', args=[wiki.repo_id, file_path]) return HttpResponseRedirect(file_url + "?raw=1") if not req_user: user_can_write = False elif 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": file_path, "user_can_write": user_can_write, "file_path": file_path, "repo_id": wiki.repo_id, "search_repo_id": wiki.repo_id, "search_wiki": True, "service_url": get_service_url().rstrip('/') })
def repo_folder_trash(request, repo_id): path = request.GET.get('path', '/') if not seafile_api.get_dir_id_by_path(repo_id, path) or \ check_folder_permission(request, repo_id, path) != 'rw': return render_permission_error(request, _('Unable to view recycle page')) repo = get_repo(repo_id) if not repo: raise Http404 if path == '/': name = repo.name else: name = os.path.basename(path.rstrip('/')) return render(request, 'repo_folder_trash_react.html', { 'repo': repo, 'repo_folder_name': name, 'path': path, 'enable_clean': config.ENABLE_USER_CLEAN_TRASH, })
def group_remove(request, group_id): """ Remove group from groupadmin page. Only system admin can perform this operation. """ # Check whether user is system admin. if not request.user.is_staff: return render_permission_error(request, _(u'Only administrators can delete the group.')) # Request header may missing HTTP_REFERER, we need to handle that case. next = request.META.get('HTTP_REFERER', None) if not next: next = SITE_ROOT try: group_id_int = int(group_id) except ValueError: return HttpResponseRedirect(next) try: ccnet_threaded_rpc.remove_group(group_id_int, request.user.username) seafserv_threaded_rpc.remove_repo_group(group_id_int, None) except SearpcError, e: return render_error(request, _(e.msg))
def org_repo_share(request, url_prefix): """ Share org repo to members or groups in current org. """ if request.method != "POST": raise Http404 org = get_user_current_org(request.user.username, url_prefix) if not org: return HttpResponseRedirect(reverse(myhome)) form = RepoShareForm(request.POST) if not form.is_valid(): # TODO: may display error msg on form raise Http404 email_or_group = form.cleaned_data["email_or_group"] repo_id = form.cleaned_data["repo_id"] permission = form.cleaned_data["permission"] from_email = request.user.username # Test whether user is the repo owner if not validate_org_repo_owner(org.org_id, repo_id, request.user.username): return render_permission_error( request, _(u"Only the owner of this library has permission to share it."), extra_ctx={"org": org, "base_template": "org_base.html"}, ) share_to_list = string2list(email_or_group) for share_to in share_to_list: if share_to == "all": """ Share to public """ try: seafserv_threaded_rpc.set_org_inner_pub_repo(org.org_id, repo_id, permission) except: msg = _(u"Failed to share to all members") messages.add_message(request, messages.ERROR, msg) continue msg = _(u'Shared to all members successfully, you can go check it at <a href="%s">Share</a>.') % ( reverse("org_shareadmin", args=[org.url_prefix]) ) messages.add_message(request, messages.INFO, msg) elif share_to.find("@") == -1: """ Share repo to group """ # TODO: if we know group id, then we can simplly call group_share_repo group_name = share_to # Get all org groups. groups = get_org_groups(org.org_id, -1, -1) find = False for group in groups: # for every group that user joined, if group name and # group creator matchs, then has finded the group if group.props.group_name == group_name: seafserv_threaded_rpc.add_org_group_repo(repo_id, org.org_id, group.id, from_email, permission) find = True msg = _( u'Shared to %(group)s successfully,you can go check it at <a href="%(share)s">Share</a>.' ) % {"group": group_name, "share": reverse("org_shareadmin", args=[org.url_prefix])} messages.add_message(request, messages.INFO, msg) break if not find: msg = _(u"Failed to share to %s.") % group_name messages.add_message(request, messages.ERROR, msg) else: """ Share repo to user """ # Test whether share_to is in this org if not org_user_exists(org.org_id, share_to): msg = _(u"Failed to share to %s: this user does not exist in the organization.") % share_to messages.add_message(request, messages.ERROR, msg) continue # Record share info to db. try: seafserv_threaded_rpc.add_share(repo_id, from_email, share_to, permission) msg = _( u'Shared to %(share_to)s successfully,you can go check it at <a href="%(share)s">Share</a>.' ) % {"share_to": share_to, "share": reverse("org_shareadmin", args=[org.url_prefix])} messages.add_message(request, messages.INFO, msg) except SearpcError, e: msg = _(u"Failed to share to %s.") % share_to messages.add_message(request, messages.ERROR, msg) continue
def dtable_file_view(request, workspace_id, name): """ Permission: 1. owner 2. group member 3. shared user """ # resource check workspace = Workspaces.objects.get_workspace_by_id(workspace_id) if not workspace: return render_error(request, 'Workspace does not exist.') group_id = '' if '@seafile_group' in workspace.owner: group_id = workspace.owner.split('@')[0] group = seaserv.get_group(group_id) if not group: error_msg = 'Group %s not found.' % group_id return render_error(request, error_msg) repo_id = workspace.repo_id repo = seafile_api.get_repo(repo_id) if not repo: return render_error(request, 'Library does not exist.') dtable = DTables.objects.get_dtable(workspace, name) if not dtable: return render_error(request, 'DTable does not exist.') # permission check username = request.user.username permission = check_dtable_permission(username, workspace, dtable) if not permission: return render_permission_error(request, _('Permission denied.')) is_admin = False if group_id: is_admin = is_group_admin_or_owner(group_id, username) else: # open your own dtable is_admin = username == workspace.owner seafile_url = '' repo_api_token = '' try: seafile_connector = SeafileConnectors.objects.get(dtable=dtable) seafile_url = seafile_connector.seafile_url repo_api_token = seafile_connector.repo_api_token except SeafileConnectors.DoesNotExist: pass return_dict = { 'version': SEATABLE_VERSION, 'dtable_baidu_map_key': DTABLE_BAIDU_MAP_KEY, 'dtable_google_map_key': DTABLE_GOOGLE_MAP_KEY, 'seatable_market_url': SEATABLE_MARKET_URL, 'filename': name, 'workspace_id': workspace_id, 'dtable_uuid': dtable.uuid.hex, 'permission': permission if check_user_workspace_quota(workspace) else 'r', 'media_url': MEDIA_URL, 'seafile_url': seafile_url, 'repo_api_token': repo_api_token, 'dtable_server': DTABLE_SERVER_URL, 'dtable_socket': DTABLE_SOCKET_URL, 'dtable_enable_geolocation_column': DTABLE_ENABLE_GEOLOCATION_COLUMN, 'is_admin': is_admin, 'asset_quota_exceeded': dtable.creator == request.user.username and not check_user_workspace_quota(workspace), } return render(request, 'dtable_file_view_react.html', return_dict)
def repo_history(request, repo_id): """ List library modification histories. """ user_perm = check_folder_permission(request, repo_id, '/') if not user_perm: return render_permission_error( request, _('Unable to view library modification')) repo = get_repo(repo_id) if not repo: raise Http404 username = request.user.username try: server_crypto = UserOptions.objects.is_server_crypto(username) except CryptoOptionNotSetError: # Assume server_crypto is ``False`` if this option is not set. server_crypto = False password_set = False if repo.props.encrypted and \ (repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)): try: ret = seafile_api.is_password_set(repo_id, username) if ret == 1: password_set = True except SearpcError as e: return render_error(request, e.msg) if not password_set: reverse_url = reverse('lib_view', args=[repo_id, repo.name, '']) return HttpResponseRedirect(reverse_url) try: current_page = int(request.GET.get('page', '1')) except ValueError: current_page = 1 per_page = 100 commits_all = get_commits(repo_id, per_page * (current_page - 1), per_page + 1) commits = commits_all[:per_page] for c in commits: c.show = False if new_merge_with_no_conflict(c) else True show_label = False if ENABLE_REPO_SNAPSHOT_LABEL: show_label = True snapshot_labels = RevisionTags.objects.filter(repo_id=repo_id) for c in commits: if c.show: c.labels = [] for label in snapshot_labels: if label.revision_id == c.id: c.labels.append(label.tag.name) if len(commits_all) == per_page + 1: page_next = True else: page_next = False # for 'go back' referer = request.GET.get('referer', '') #template = 'repo_history.html' template = 'repo_history_react.html' return render( request, template, { "repo": repo, "commits": commits, 'current_page': current_page, 'prev_page': current_page - 1, 'next_page': current_page + 1, 'page_next': page_next, 'user_perm': user_perm, 'show_label': show_label, 'referer': referer, })
def slug(request, slug, file_path="home.md"): """Show wiki page. """ # get wiki object or 404 wiki = get_object_or_404(Wiki, slug=slug) file_path = "/" + file_path is_dir = None file_id = seafile_api.get_file_id_by_path(wiki.repo_id, file_path) if file_id: is_dir = False dir_id = seafile_api.get_dir_id_by_path(wiki.repo_id, file_path) if dir_id: is_dir = True # compatible with old wiki url if is_dir is None: if len(file_path.split('.')) == 1: new_path = file_path[1:] + '.md' return HttpResponseRedirect(reverse('wiki:slug', args=[slug, new_path])) # perm check req_user = request.user.username if not req_user and not wiki.has_read_perm(request): return redirect('auth_login') else: if not wiki.has_read_perm(request): return render_permission_error(request, _('Unable to view Wiki')) file_type, ext = get_file_type_and_ext(posixpath.basename(file_path)) if file_type == IMAGE: file_url = reverse('view_lib_file', args=[wiki.repo_id, file_path]) return HttpResponseRedirect(file_url + "?raw=1") if not req_user: user_can_write = False elif req_user == wiki.username or check_folder_permission( request, wiki.repo_id, '/') == 'rw': user_can_write = True else: user_can_write = False is_public_wiki = False if wiki.permission == 'public': is_public_wiki = True has_index = False dirs = seafile_api.list_dir_by_path(wiki.repo_id, '/') for dir_obj in dirs: if dir_obj.obj_name == 'index.md': has_index = True break try: fs = FileShare.objects.get(repo_id=wiki.repo_id, path='/') except FileShare.DoesNotExist: fs = FileShare.objects.create_dir_link(wiki.username, wiki.repo_id, '/', permission='view_download') wiki.permission = 'public' wiki.save() is_public_wiki = True repo = seafile_api.get_repo(wiki.repo_id) return render(request, "wiki/wiki.html", { "wiki": wiki, "repo_name": repo.name if repo else '', "page_name": file_path, "shared_token": fs.token, "shared_type": fs.s_type, "user_can_write": user_can_write, "file_path": file_path, "filename": os.path.splitext(os.path.basename(file_path))[0], "repo_id": wiki.repo_id, "search_repo_id": wiki.repo_id, "search_wiki": True, "is_public_wiki": is_public_wiki, "is_dir": is_dir, "has_index": has_index, })
def view_file(request, repo_id): """ Steps to view file: 1. Get repo id and file path. 2. Check user's permission. 3. Check whether this file can be viewed online. 4.1 Get file content if file is text file. 4.2 Prepare flash if file is document. 4.3 Prepare or use pdfjs if file is pdf. 4.4 Other file return it's raw path. """ username = request.user.username # check arguments repo = get_repo(repo_id) if not repo: raise Http404 path = request.GET.get("p", "/") obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u"File does not exist")) # construct some varibles u_filename = os.path.basename(path) filename_utf8 = urllib2.quote(u_filename.encode("utf-8")) current_commit = get_commits(repo_id, 0, 1)[0] # Check whether user has permission to view file and get file raw path, # render error page if permission is deny. raw_path, user_perm = get_file_view_path_and_perm(request, repo_id, obj_id, u_filename) if not user_perm: return render_permission_error(request, _(u"Unable to view file")) # get file type and extension filetype, fileext = get_file_type_and_ext(u_filename) img_prev = None img_next = None ret_dict = { "err": "", "file_content": "", "encoding": "", "file_enc": "", "file_encoding_list": [], "swf_exists": False, "filetype": filetype, } # Check file size fsize = get_file_size(obj_id) if fsize > FILE_PREVIEW_MAX_SIZE: from django.template.defaultfilters import filesizeformat err = _(u"File size surpasses %s, can not be opened online.") % filesizeformat(FILE_PREVIEW_MAX_SIZE) ret_dict["err"] = err else: """Choose different approach when dealing with different type of file.""" if is_textual_file(file_type=filetype): handle_textual_file(request, filetype, raw_path, ret_dict) if filetype == MARKDOWN: c = ret_dict["file_content"] ret_dict["file_content"] = convert_md_link(c, repo_id, username) elif filetype == DOCUMENT: handle_document(raw_path, obj_id, fileext, ret_dict) elif filetype == PDF: handle_pdf(raw_path, obj_id, fileext, ret_dict) elif filetype == IMAGE: parent_dir = os.path.dirname(path) dirs = list_dir_by_path(current_commit.id, parent_dir) if not dirs: raise Http404 img_list = [] for dirent in dirs: if not stat.S_ISDIR(dirent.props.mode): fltype, flext = get_file_type_and_ext(dirent.obj_name) if fltype == "Image": img_list.append(dirent.obj_name) if len(img_list) > 1: img_list.sort(lambda x, y: cmp(x.lower(), y.lower())) cur_img_index = img_list.index(u_filename) if cur_img_index != 0: img_prev = os.path.join(parent_dir, img_list[cur_img_index - 1]) if cur_img_index != len(img_list) - 1: img_next = os.path.join(parent_dir, img_list[cur_img_index + 1]) else: pass # generate file path navigator zipped = gen_path_link(path, repo.name) # file shared link l = FileShare.objects.filter(repo_id=repo_id).filter(username=username).filter(path=path) fileshare = l[0] if len(l) > 0 else None http_or_https = request.is_secure() and "https" or "http" domain = RequestSite(request).domain if fileshare: file_shared_link = gen_shared_link(request, fileshare.token, "f") else: file_shared_link = "" # my contacts used in shared link autocomplete contacts = Contact.objects.filter(user_email=username) """List repo groups""" # Get groups this repo is shared. if request.user.org: org_id = request.user.org["org_id"] repo_shared_groups = get_org_groups_by_repo(org_id, repo_id) else: repo_shared_groups = get_shared_groups_by_repo(repo_id) # Filter out groups that user in joined. groups = [x for x in repo_shared_groups if is_group_user(x.id, username)] if len(groups) > 1: ctx = {} ctx["groups"] = groups repogrp_str = render_to_string("snippets/repo_group_list.html", ctx) else: repogrp_str = "" file_path_hash = md5_constructor(urllib2.quote(path.encode("utf-8"))).hexdigest()[:12] # fetch file contributors and latest contributor contributors, last_modified, last_commit_id = get_file_contributors( repo_id, path.encode("utf-8"), file_path_hash, obj_id ) latest_contributor = contributors[0] if contributors else None # check whether file is starred is_starred = False org_id = -1 if request.user.org: org_id = request.user.org["org_id"] is_starred = is_file_starred(username, repo.id, path.encode("utf-8"), org_id) template = "view_file_%s.html" % ret_dict["filetype"].lower() return render_to_response( template, { "repo": repo, "obj_id": obj_id, "filename": u_filename, "path": path, "zipped": zipped, "current_commit": current_commit, "fileext": fileext, "raw_path": raw_path, "fileshare": fileshare, "protocol": http_or_https, "domain": domain, "file_shared_link": file_shared_link, "contacts": contacts, "err": ret_dict["err"], "file_content": ret_dict["file_content"], "file_enc": ret_dict["file_enc"], "encoding": ret_dict["encoding"], "file_encoding_list": ret_dict["file_encoding_list"], "swf_exists": ret_dict["swf_exists"], "filetype": ret_dict["filetype"], "applet_root": get_ccnetapplet_root(), "groups": groups, "DOCUMENT_CONVERTOR_ROOT": DOCUMENT_CONVERTOR_ROOT, "use_pdfjs": USE_PDFJS, "contributors": contributors, "latest_contributor": latest_contributor, "last_modified": last_modified, "last_commit_id": last_commit_id, "repo_group_str": repogrp_str, "is_starred": is_starred, "user_perm": user_perm, "img_prev": img_prev, "img_next": img_next, }, context_instance=RequestContext(request), )
def file_edit(request, repo_id): repo = get_repo(repo_id) if not repo: raise Http404 if request.method == 'POST': return file_edit_submit(request, repo_id) if check_repo_access_permission(repo_id, request.user) != 'rw': return render_permission_error(request, _(u'Unable to edit file')) path = request.GET.get('p', '/') if path[-1] == '/': path = path[:-1] u_filename = os.path.basename(path) filename = urllib2.quote(u_filename.encode('utf-8')) head_id = repo.head_cmmt_id obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u'The file does not exist.')) token = web_get_access_token(repo_id, obj_id, 'view', request.user.username) # generate path and link zipped = gen_path_link(path, repo.name) filetype, fileext = get_file_type_and_ext(filename) op = None err = '' file_content = None encoding = None file_encoding_list = FILE_ENCODING_LIST if filetype == TEXT or filetype == MARKDOWN or filetype == SF: if repo.encrypted: repo.password_set = seafile_api.is_password_set( repo_id, request.user.username) if not repo.password_set: op = 'decrypt' if not op: inner_path = gen_inner_file_get_url(token, filename) file_enc = request.GET.get('file_enc', 'auto') if not file_enc in FILE_ENCODING_LIST: file_enc = 'auto' err, file_content, encoding = repo_file_get(inner_path, file_enc) if encoding and encoding not in FILE_ENCODING_LIST: file_encoding_list.append(encoding) else: err = _(u'Edit online is not offered for this type of file.') # Redirect to different place according to from page when user click # cancel button on file edit page. cancel_url = reverse('repo_view_file', args=[repo.id ]) + '?p=' + urlquote(path) page_from = request.GET.get('from', '') gid = request.GET.get('gid', '') wiki_name = os.path.splitext(u_filename)[0] if page_from == 'wiki_page_edit' or page_from == 'wiki_page_new': cancel_url = reverse('group_wiki', args=[gid, wiki_name]) elif page_from == 'personal_wiki_page_edit' or page_from == 'personal_wiki_page_new': cancel_url = reverse('personal_wiki', args=[wiki_name]) return render_to_response('file_edit.html', { 'repo': repo, 'u_filename': u_filename, 'wiki_name': wiki_name, 'path': path, 'zipped': zipped, 'filetype': filetype, 'fileext': fileext, 'op': op, 'err': err, 'file_content': file_content, 'encoding': encoding, 'file_encoding_list': file_encoding_list, 'head_id': head_id, 'from': page_from, 'gid': gid, 'cancel_url': cancel_url, }, context_instance=RequestContext(request))
def file_edit(request, repo_id): repo = get_repo(repo_id) if not repo: raise Http404 if request.method == "POST": return file_edit_submit(request, repo_id) if get_user_permission(request, repo_id) != "rw": return render_permission_error(request, _(u"Unable to edit file")) path = request.GET.get("p", "/") if path[-1] == "/": path = path[:-1] u_filename = os.path.basename(path) filename = urllib2.quote(u_filename.encode("utf-8")) head_id = repo.head_cmmt_id obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u"The file does not exist.")) token = web_get_access_token(repo_id, obj_id, "view", request.user.username) # generate path and link zipped = gen_path_link(path, repo.name) filetype, fileext = get_file_type_and_ext(filename) op = None err = "" file_content = None encoding = None file_encoding_list = FILE_ENCODING_LIST if filetype == TEXT or filetype == MARKDOWN or filetype == SF: if repo.encrypted: repo.password_set = seafserv_rpc.is_passwd_set(repo_id, request.user.username) if not repo.password_set: op = "decrypt" if not op: raw_path = gen_file_get_url(token, filename) file_enc = request.GET.get("file_enc", "auto") if not file_enc in FILE_ENCODING_LIST: file_enc = "auto" err, file_content, encoding = repo_file_get(raw_path, file_enc) if encoding and encoding not in FILE_ENCODING_LIST: file_encoding_list.append(encoding) else: err = _(u"Edit online is not offered for this type of file.") return render_to_response( "file_edit.html", { "repo": repo, "u_filename": u_filename, "wiki_name": os.path.splitext(u_filename)[0], "path": path, "zipped": zipped, "filetype": filetype, "fileext": fileext, "op": op, "err": err, "file_content": file_content, "encoding": encoding, "file_encoding_list": file_encoding_list, "head_id": head_id, "from": request.GET.get("from", ""), "gid": request.GET.get("gid", ""), }, context_instance=RequestContext(request), )
def share_repo(request): """ Handle repo share request """ if request.method != 'POST': raise Http404 form = RepoShareForm(request.POST) if not form.is_valid(): # TODO: may display error msg on form raise Http404 email_or_group = form.cleaned_data['email_or_group'] repo_id = form.cleaned_data['repo_id'] permission = form.cleaned_data['permission'] from_email = request.user.username repo = get_repo(repo_id) if not repo: raise Http404 is_encrypted = True if repo.encrypted else False # Test whether user is the repo owner. if not validate_owner(request, repo_id): return render_permission_error(request, _(u'Only the owner of the library has permission to share it.')) to_email_list = string2list(email_or_group) for to_email in to_email_list: if to_email == 'all': ''' Share to public ''' # ignore 'all' if we're running in cloud mode if not CLOUD_MODE: try: seafserv_threaded_rpc.set_inner_pub_repo(repo_id, permission) except: msg = _(u'Failed to share to all members') message.add_message(request, message.ERROR, msg) continue msg = _(u'Shared to all members successfully, go check it at <a href="%s">Share</a>.') % \ (reverse('share_admin')) messages.add_message(request, messages.INFO, msg) elif to_email.find('@') == -1: ''' Share repo to group ''' # TODO: if we know group id, then we can simplly call group_share_repo group_name = to_email # get all personal groups groups = get_personal_groups(-1, -1) find = False for group in groups: # for every group that user joined, if group name matchs, # then has find the group if group.props.group_name == group_name: from seahub.group.views import group_share_repo group_share_repo(request, repo_id, int(group.props.id), from_email, permission) find = True msg = _(u'Shared to %(group)s successfully,go check it at <a href="%(share)s">Share</a>.') % \ {'group':group_name, 'share':reverse('share_admin')} messages.add_message(request, messages.INFO, msg) break if not find: msg = _(u'Failed to share to %s,as it does not exists.') % group_name messages.add_message(request, messages.ERROR, msg) else: ''' Share repo to user ''' # Add email to contacts. mail_sended.send(sender=None, user=request.user.username, email=to_email) if not is_registered_user(to_email): # Generate shared link and send mail if user has not registered. # kwargs = {'repo_id': repo_id, # 'repo_owner': from_email, # 'anon_email': to_email, # 'is_encrypted': is_encrypted, # } # anonymous_share(request, **kwargs) msg = _(u'Failed to share to %s, as the email is not registered.') % to_email messages.add_message(request, messages.ERROR, msg) continue else: # Record share info to db. try: seafserv_threaded_rpc.add_share(repo_id, from_email, to_email, permission) except SearpcError, e: msg = _(u'Failed to share to %s .') % to_email messages.add_message(request, messages.ERROR, msg) continue msg = _(u'Shared to %(email)s successfully,go check it at <a href="%(share)s">Share</a>.') % \ {'email':to_email, 'share':reverse('share_admin')} messages.add_message(request, messages.INFO, msg)
def view_file(request, repo_id): """ Steps to view file: 1. Get repo id and file path. 2. Check user's permission. 3. Check whether this file can be viewed online. 4.1 Get file content if file is text file. 4.2 Prepare flash if file is document. 4.3 Prepare or use pdfjs if file is pdf. 4.4 Other file return it's raw path. """ username = request.user.username # check arguments repo = get_repo(repo_id) if not repo: raise Http404 path = request.GET.get('p', '/').rstrip('/') obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u'File does not exist')) # construct some varibles u_filename = os.path.basename(path) current_commit = get_commits(repo_id, 0, 1)[0] # Check whether user has permission to view file and get file raw path, # render error page if permission deny. raw_path, inner_path, user_perm = get_file_view_path_and_perm( request, repo_id, obj_id, path) if not user_perm: return render_permission_error(request, _(u'Unable to view file')) # check if the user is the owner or not, for 'private share' if is_org_context(request): repo_owner = seafile_api.get_org_repo_owner(repo.id) is_repo_owner = True if repo_owner == username else False else: is_repo_owner = seafile_api.is_repo_owner(username, repo.id) # get file type and extension filetype, fileext = get_file_type_and_ext(u_filename) img_prev = None img_next = None ret_dict = { 'err': '', 'file_content': '', 'encoding': '', 'file_enc': '', 'file_encoding_list': [], 'html_exists': False, 'filetype': filetype } fsize = get_file_size(repo.store_id, repo.version, obj_id) exceeds_limit, err_msg = file_size_exceeds_preview_limit(fsize, filetype) if exceeds_limit: ret_dict['err'] = err_msg else: """Choose different approach when dealing with different type of file.""" if is_textual_file(file_type=filetype): handle_textual_file(request, filetype, inner_path, ret_dict) if filetype == MARKDOWN: c = ret_dict['file_content'] ret_dict['file_content'] = convert_md_link( c, repo_id, username) elif filetype == DOCUMENT: handle_document(inner_path, obj_id, fileext, ret_dict) elif filetype == SPREADSHEET: handle_spreadsheet(inner_path, obj_id, fileext, ret_dict) elif filetype == OPENDOCUMENT: if fsize == 0: ret_dict['err'] = _(u'Invalid file format.') elif filetype == PDF: handle_pdf(inner_path, obj_id, fileext, ret_dict) elif filetype == IMAGE: parent_dir = os.path.dirname(path) dirs = seafile_api.list_dir_by_commit_and_path( current_commit.repo_id, current_commit.id, parent_dir) if not dirs: raise Http404 img_list = [] for dirent in dirs: if not stat.S_ISDIR(dirent.props.mode): fltype, flext = get_file_type_and_ext(dirent.obj_name) if fltype == 'Image': img_list.append(dirent.obj_name) if len(img_list) > 1: img_list.sort(lambda x, y: cmp(x.lower(), y.lower())) cur_img_index = img_list.index(u_filename) if cur_img_index != 0: img_prev = posixpath.join(parent_dir, img_list[cur_img_index - 1]) if cur_img_index != len(img_list) - 1: img_next = posixpath.join(parent_dir, img_list[cur_img_index + 1]) else: pass # generate file path navigator zipped = gen_path_link(path, repo.name) # file shared link l = FileShare.objects.filter(repo_id=repo_id).filter( username=username).filter(path=path) fileshare = l[0] if len(l) > 0 else None http_or_https = request.is_secure() and 'https' or 'http' domain = RequestSite(request).domain if fileshare: file_shared_link = gen_file_share_link(fileshare.token) else: file_shared_link = '' for g in request.user.joined_groups: g.avatar = grp_avatar(g.id, 20) """List repo groups""" # Get groups this repo is shared. if request.user.org: org_id = request.user.org.org_id repo_shared_groups = get_org_groups_by_repo(org_id, repo_id) else: repo_shared_groups = get_shared_groups_by_repo(repo_id) # Filter out groups that user in joined. groups = [x for x in repo_shared_groups if is_group_user(x.id, username)] if len(groups) > 1: ctx = {} ctx['groups'] = groups repogrp_str = render_to_string("snippets/repo_group_list.html", ctx) else: repogrp_str = '' file_path_hash = hashlib.md5(urllib2.quote( path.encode('utf-8'))).hexdigest()[:12] # fetch file contributors and latest contributor contributors, last_modified, last_commit_id = \ FileContributors.objects.get_file_contributors( repo_id, path.encode('utf-8'), file_path_hash, obj_id) latest_contributor = contributors[0] if contributors else None # check whether file is starred is_starred = False org_id = -1 if request.user.org: org_id = request.user.org.org_id is_starred = is_file_starred(username, repo.id, path.encode('utf-8'), org_id) template = 'view_file_%s.html' % ret_dict['filetype'].lower() return render_to_response( template, { 'repo': repo, 'is_repo_owner': is_repo_owner, 'obj_id': obj_id, 'filename': u_filename, 'path': path, 'zipped': zipped, 'current_commit': current_commit, 'fileext': fileext, 'raw_path': raw_path, 'fileshare': fileshare, 'protocol': http_or_https, 'domain': domain, 'file_shared_link': file_shared_link, 'err': ret_dict['err'], 'file_content': ret_dict['file_content'], 'file_enc': ret_dict['file_enc'], 'encoding': ret_dict['encoding'], 'file_encoding_list': ret_dict['file_encoding_list'], 'html_exists': ret_dict['html_exists'], 'html_detail': ret_dict.get('html_detail', {}), 'filetype': ret_dict['filetype'], 'groups': groups, 'use_pdfjs': USE_PDFJS, 'contributors': contributors, 'latest_contributor': latest_contributor, 'last_modified': last_modified, 'last_commit_id': last_commit_id, 'repo_group_str': repogrp_str, 'is_starred': is_starred, 'user_perm': user_perm, 'img_prev': img_prev, 'img_next': img_next, 'highlight_keyword': settings.HIGHLIGHT_KEYWORD, }, context_instance=RequestContext(request))
def file_edit(request, repo_id): repo = get_repo(repo_id) if not repo: raise Http404 if request.method == "POST": return file_edit_submit(request, repo_id) if check_repo_access_permission(repo_id, request.user) != "rw": return render_permission_error(request, _(u"Unable to edit file")) path = request.GET.get("p", "/") if path[-1] == "/": path = path[:-1] u_filename = os.path.basename(path) filename = urllib2.quote(u_filename.encode("utf-8")) head_id = repo.head_cmmt_id obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u"The file does not exist.")) token = web_get_access_token(repo_id, obj_id, "view", request.user.username) # generate path and link zipped = gen_path_link(path, repo.name) filetype, fileext = get_file_type_and_ext(filename) op = None err = "" file_content = None encoding = None file_encoding_list = FILE_ENCODING_LIST if filetype == TEXT or filetype == MARKDOWN or filetype == SF: if repo.encrypted: repo.password_set = seafile_api.is_password_set(repo_id, request.user.username) if not repo.password_set: op = "decrypt" if not op: inner_path = gen_inner_file_get_url(token, filename) file_enc = request.GET.get("file_enc", "auto") if not file_enc in FILE_ENCODING_LIST: file_enc = "auto" err, file_content, encoding = repo_file_get(inner_path, file_enc) if encoding and encoding not in FILE_ENCODING_LIST: file_encoding_list.append(encoding) else: err = _(u"Edit online is not offered for this type of file.") # Redirect to different place according to from page when user click # cancel button on file edit page. cancel_url = reverse("repo_view_file", args=[repo.id]) + "?p=" + urlquote(path) page_from = request.GET.get("from", "") gid = request.GET.get("gid", "") wiki_name = os.path.splitext(u_filename)[0] if page_from == "wiki_page_edit" or page_from == "wiki_page_new": cancel_url = reverse("group_wiki", args=[gid, wiki_name]) elif page_from == "personal_wiki_page_edit" or page_from == "personal_wiki_page_new": cancel_url = reverse("personal_wiki", args=[wiki_name]) return render_to_response( "file_edit.html", { "repo": repo, "u_filename": u_filename, "wiki_name": wiki_name, "path": path, "zipped": zipped, "filetype": filetype, "fileext": fileext, "op": op, "err": err, "file_content": file_content, "encoding": encoding, "file_encoding_list": file_encoding_list, "head_id": head_id, "from": page_from, "gid": gid, "cancel_url": cancel_url, }, context_instance=RequestContext(request), )
def dtable_form_view(request, token): # resource check form_obj = DTableForms.objects.get_form_by_token(token) if not form_obj: return render_error(request, 'Table\'s form does not exist.') workspace_id = form_obj.workspace_id workspace = Workspaces.objects.get_workspace_by_id(workspace_id) if not workspace: return render_error(request, 'Workspace does not exist.') dtable_uuid = form_obj.dtable_uuid dtable = DTables.objects.get_dtable_by_uuid(dtable_uuid) if not dtable: return render_error(request, 'Table does not exist.') # permission check if not check_form_submit_permission(request, form_obj): return render_permission_error(request, _('Permission denied.')) # asset quota check if not check_user_workspace_quota(workspace): return render_error(request, _('Asset quota exceeded.')) # generate json web token payload = { 'exp': int(time.time()) + 60 * 5, 'dtable_uuid': dtable_uuid, 'username': "******", 'permission': PERMISSION_READ, } try: access_token = jwt.encode(payload, DTABLE_PRIVATE_KEY, algorithm='HS256') except Exception as e: logger.error(e) return render_error(request, _('Internal Server Error')) url = '%s/api/v1/dtables/%s/metadata/' % (DTABLE_SERVER_URL.strip('/'), dtable_uuid) req = requests.Request( url, headers={"Authorization": "Token %s" % access_token.decode()}) try: dtable_metadata = requests.urlopen(req).read().decode() except Exception as e: logger.error(e) return render_error(request, _('Internal Server Error')) return_dict = { 'version': SEATABLE_VERSION, 'dtable_metadata': dtable_metadata, 'workspace_id': workspace_id, 'form_id': form_obj.form_id, 'form_config': form_obj.form_config, 'dtable_name': dtable.name, 'dtable_web_service_url': DTABLE_WEB_SERVICE_URL, 'form_token': token, } return render(request, 'dtable_share_form_view_react.html', return_dict)
def file_edit(request, repo_id): repo = get_repo(repo_id) if not repo: raise Http404 if request.method == 'POST': return file_edit_submit(request, repo_id) if get_user_permission(request, repo_id) != 'rw': return render_permission_error(request, _(u'Unable to edit file')) path = request.GET.get('p', '/') if path[-1] == '/': path = path[:-1] u_filename = os.path.basename(path) filename = urllib2.quote(u_filename.encode('utf-8')) head_id = repo.head_cmmt_id obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u'The file does not exist.')) token = web_get_access_token(repo_id, obj_id, 'view', request.user.username) # generate path and link zipped = gen_path_link(path, repo.name) filetype, fileext = get_file_type_and_ext(filename) op = None err = '' file_content = None encoding = None file_encoding_list = FILE_ENCODING_LIST if filetype == TEXT or filetype == MARKDOWN or filetype == SF: if repo.encrypted: repo.password_set = seafserv_rpc.is_passwd_set(repo_id, request.user.username) if not repo.password_set: op = 'decrypt' if not op: raw_path = gen_file_get_url(token, filename) file_enc = request.GET.get('file_enc', 'auto') if not file_enc in FILE_ENCODING_LIST: file_enc = 'auto' err, file_content, encoding = repo_file_get(raw_path, file_enc) if encoding and encoding not in FILE_ENCODING_LIST: file_encoding_list.append(encoding) else: err = _(u'Edit online is not offered for this type of file.') # Redirect to different place according to from page when user click # cancel button on file edit page. cancel_url = reverse('repo_view_file', args=[repo.id]) + '?p=' + urlquote(path) page_from = request.GET.get('from', '') gid = request.GET.get('gid', '') wiki_name = os.path.splitext(u_filename)[0] if page_from == 'wiki_page_edit' or page_from == 'wiki_page_new': cancel_url = reverse('group_wiki', args=[gid, wiki_name]) elif page_from == 'personal_wiki_page_edit' or page_from == 'personal_wiki_page_new': cancel_url = reverse('personal_wiki', args=[wiki_name]) search_repo_id = None if not repo.encrypted: search_repo_id = repo.id return render_to_response('file_edit.html', { 'repo':repo, 'u_filename':u_filename, 'wiki_name': wiki_name, 'path':path, 'zipped':zipped, 'filetype':filetype, 'fileext':fileext, 'op':op, 'err':err, 'file_content':file_content, 'encoding': encoding, 'file_encoding_list':file_encoding_list, 'head_id': head_id, 'from': page_from, 'gid': gid, 'cancel_url': cancel_url, 'search_repo_id': search_repo_id, }, context_instance=RequestContext(request))
def dtable_form_edit(request, token): """ Permission: 1. owner 2. group member 3. shared user with `rw` permission """ # resource check form_obj = DTableForms.objects.get_form_by_token(token) if not form_obj: return render_error(request, 'Table\'s form does not exist.') workspace_id = form_obj.workspace_id workspace = Workspaces.objects.get_workspace_by_id(workspace_id) if not workspace: return render_error(request, 'Workspace does not exist.') dtable_uuid = form_obj.dtable_uuid dtable = DTables.objects.get_dtable_by_uuid(dtable_uuid) if not dtable: return render_error(request, 'Table does not exist.') # permission check username = request.user.username permission = check_dtable_permission(username, workspace, dtable) if permission != PERMISSION_READ_WRITE: return render_permission_error(request, 'Permission denied.') if not check_user_workspace_quota(workspace): return render_error(request, 'Asset quota exceeded.') # generate json web token payload = { 'exp': int(time.time()) + 60 * 5, 'dtable_uuid': dtable_uuid, 'username': "******", 'permission': permission, } try: access_token = jwt.encode(payload, DTABLE_PRIVATE_KEY, algorithm='HS256') except Exception as e: logger.error(e) return render_error(request, _('Internal Server Error')) url = '%s/api/v1/dtables/%s/metadata/' % (DTABLE_SERVER_URL.strip('/'), dtable_uuid) req = requests.Request( url, headers={"Authorization": "Token %s" % access_token.decode()}) try: dtable_metadata = requests.urlopen(req).read().decode() except Exception as e: logger.error(e) return render_error(request, _('Internal Server Error')) share_type = form_obj.share_type shared_groups = list() if share_type == SHARED_GROUPS: group_ids = DTableFormShare.objects.list_by_form(form_obj) shared_groups = [{ 'id': group_id, 'name': group_id_to_name(group_id) } for group_id in group_ids] return_dict = { 'dtable_metadata': dtable_metadata, 'dtable_name': dtable.name, 'workspace_id': workspace_id, 'form_id': form_obj.form_id, 'form_config': form_obj.form_config, 'dtable_uuid': dtable.uuid.hex, 'dtable_web_service_url': DTABLE_WEB_SERVICE_URL, 'form_token': token, 'share_type': share_type, 'shared_groups': json.dumps(shared_groups), } return render(request, 'dtable_edit_form_view_react.html', return_dict)
def view_file(request, repo_id): """ Steps to view file: 1. Get repo id and file path. 2. Check user's permission. 3. Check whether this file can be viewed online. 4.1 Get file content if file is text file. 4.2 Prepare flash if file is document. 4.3 Prepare or use pdfjs if file is pdf. 4.4 Other file return it's raw path. """ username = request.user.username # check arguments repo = get_repo(repo_id) if not repo: raise Http404 path = request.GET.get('p', '/') obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u'File does not exist')) # construct some varibles u_filename = os.path.basename(path) current_commit = get_commits(repo_id, 0, 1)[0] # Check whether user has permission to view file and get file raw path, # render error page if permission is deny. raw_path, user_perm = get_file_view_path_and_perm(request, repo_id, obj_id, u_filename) if not user_perm: return render_permission_error(request, _(u'Unable to view file')) # get file type and extension filetype, fileext = get_file_type_and_ext(u_filename) img_prev = None img_next = None ret_dict = {'err': '', 'file_content': '', 'encoding': '', 'file_enc': '', 'file_encoding_list': [], 'html_exists': False, 'filetype': filetype} fsize = get_file_size(obj_id) exceeds_limit, err_msg = file_size_exceeds_preview_limit(fsize, filetype) if exceeds_limit: ret_dict['err'] = err_msg else: """Choose different approach when dealing with different type of file.""" if is_textual_file(file_type=filetype): handle_textual_file(request, filetype, raw_path, ret_dict) if filetype == MARKDOWN: c = ret_dict['file_content'] ret_dict['file_content'] = convert_md_link(c, repo_id, username) elif filetype == DOCUMENT: handle_document(raw_path, obj_id, fileext, ret_dict) elif filetype == PDF: handle_pdf(raw_path, obj_id, fileext, ret_dict) elif filetype == IMAGE: parent_dir = os.path.dirname(path) dirs = list_dir_by_path(current_commit.id, parent_dir) if not dirs: raise Http404 img_list = [] for dirent in dirs: if not stat.S_ISDIR(dirent.props.mode): fltype, flext = get_file_type_and_ext(dirent.obj_name) if fltype == 'Image': img_list.append(dirent.obj_name) if len(img_list) > 1: img_list.sort(lambda x, y : cmp(x.lower(), y.lower())) cur_img_index = img_list.index(u_filename) if cur_img_index != 0: img_prev = os.path.join(parent_dir, img_list[cur_img_index - 1]) if cur_img_index != len(img_list) - 1: img_next = os.path.join(parent_dir, img_list[cur_img_index + 1]) else: pass # generate file path navigator zipped = gen_path_link(path, repo.name) # file shared link l = FileShare.objects.filter(repo_id=repo_id).filter( username=username).filter(path=path) fileshare = l[0] if len(l) > 0 else None http_or_https = request.is_secure() and 'https' or 'http' domain = RequestSite(request).domain if fileshare: file_shared_link = gen_shared_link(request, fileshare.token, 'f') else: file_shared_link = '' # my contacts used in shared link autocomplete contacts = Contact.objects.filter(user_email=username) """List repo groups""" # Get groups this repo is shared. if request.user.org: org_id = request.user.org['org_id'] repo_shared_groups = get_org_groups_by_repo(org_id, repo_id) else: repo_shared_groups = get_shared_groups_by_repo(repo_id) # Filter out groups that user in joined. groups = [ x for x in repo_shared_groups if is_group_user(x.id, username)] if len(groups) > 1: ctx = {} ctx['groups'] = groups repogrp_str = render_to_string("snippets/repo_group_list.html", ctx) else: repogrp_str = '' file_path_hash = md5_constructor(urllib2.quote(path.encode('utf-8'))).hexdigest()[:12] # fetch file contributors and latest contributor contributors, last_modified, last_commit_id = get_file_contributors(repo_id, path.encode('utf-8'), file_path_hash, obj_id) latest_contributor = contributors[0] if contributors else None # check whether file is starred is_starred = False org_id = -1 if request.user.org: org_id = request.user.org['org_id'] is_starred = is_file_starred(username, repo.id, path.encode('utf-8'), org_id) template = 'view_file_%s.html' % ret_dict['filetype'].lower() search_repo_id = None if not repo.encrypted: search_repo_id = repo.id return render_to_response(template, { 'repo': repo, 'obj_id': obj_id, 'filename': u_filename, 'path': path, 'zipped': zipped, 'current_commit': current_commit, 'fileext': fileext, 'raw_path': raw_path, 'fileshare': fileshare, 'protocol': http_or_https, 'domain': domain, 'file_shared_link': file_shared_link, 'contacts': contacts, 'err': ret_dict['err'], 'file_content': ret_dict['file_content'], 'file_enc': ret_dict['file_enc'], 'encoding': ret_dict['encoding'], 'file_encoding_list':ret_dict['file_encoding_list'], 'html_exists': ret_dict['html_exists'], 'html_detail': ret_dict.get('html_detail', {}), 'filetype': ret_dict['filetype'], "applet_root": get_ccnetapplet_root(), 'groups': groups, 'use_pdfjs':USE_PDFJS, 'contributors': contributors, 'latest_contributor': latest_contributor, 'last_modified': last_modified, 'last_commit_id': last_commit_id, 'repo_group_str': repogrp_str, 'is_starred': is_starred, 'user_perm': user_perm, 'img_prev': img_prev, 'img_next': img_next, 'search_repo_id': search_repo_id, }, context_instance=RequestContext(request))
def view_file(request, repo_id): """ Steps to view file: 1. Get repo id and file path. 2. Check user's permission. 3. Check whether this file can be viewed online. 4.1 Get file content if file is text file. 4.2 Prepare flash if file is document. 4.3 Prepare or use pdfjs if file is pdf. 4.4 Other file return it's raw path. """ username = request.user.username # check arguments repo = get_repo(repo_id) if not repo: raise Http404 path = request.GET.get('p', '/') obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u'File does not exist')) # construct some varibles u_filename = os.path.basename(path) filename_utf8 = urllib2.quote(u_filename.encode('utf-8')) current_commit = get_commits(repo_id, 0, 1)[0] # Check whether user has permission to view file and get file raw path, # render error page if permission is deny. raw_path, user_perm = get_file_view_path_and_perm(request, repo_id, obj_id, u_filename) if not user_perm: return render_permission_error(request, _(u'Unable to view file')) # get file type and extension filetype, fileext = get_file_type_and_ext(u_filename) img_prev = None img_next = None ret_dict = {'err': '', 'file_content': '', 'encoding': '', 'file_enc': '', 'file_encoding_list': [], 'html_exists': False, 'filetype': filetype} # Check file size fsize = get_file_size(obj_id) if fsize > FILE_PREVIEW_MAX_SIZE: err = _(u'File size surpasses %s, can not be opened online.') % \ filesizeformat(FILE_PREVIEW_MAX_SIZE) ret_dict['err'] = err elif filetype in (DOCUMENT, PDF) and fsize > OFFICE_PREVIEW_MAX_SIZE: err = _(u'File size surpasses %s, can not be opened online.') % \ filesizeformat(OFFICE_PREVIEW_MAX_SIZE) ret_dict['err'] = err else: """Choose different approach when dealing with different type of file.""" if is_textual_file(file_type=filetype): handle_textual_file(request, filetype, raw_path, ret_dict) if filetype == MARKDOWN: c = ret_dict['file_content'] ret_dict['file_content'] = convert_md_link(c, repo_id, username) elif filetype == DOCUMENT: handle_document(raw_path, obj_id, fileext, ret_dict) elif filetype == PDF: handle_pdf(raw_path, obj_id, fileext, ret_dict) elif filetype == IMAGE: parent_dir = os.path.dirname(path) dirs = list_dir_by_path(current_commit.id, parent_dir) if not dirs: raise Http404 img_list = [] for dirent in dirs: if not stat.S_ISDIR(dirent.props.mode): fltype, flext = get_file_type_and_ext(dirent.obj_name) if fltype == 'Image': img_list.append(dirent.obj_name) if len(img_list) > 1: img_list.sort(lambda x, y : cmp(x.lower(), y.lower())) cur_img_index = img_list.index(u_filename) if cur_img_index != 0: img_prev = os.path.join(parent_dir, img_list[cur_img_index - 1]) if cur_img_index != len(img_list) - 1: img_next = os.path.join(parent_dir, img_list[cur_img_index + 1]) else: pass # generate file path navigator zipped = gen_path_link(path, repo.name) # file shared link l = FileShare.objects.filter(repo_id=repo_id).filter( username=username).filter(path=path) fileshare = l[0] if len(l) > 0 else None http_or_https = request.is_secure() and 'https' or 'http' domain = RequestSite(request).domain if fileshare: file_shared_link = gen_shared_link(request, fileshare.token, 'f') else: file_shared_link = '' # my contacts used in shared link autocomplete contacts = Contact.objects.filter(user_email=username) """List repo groups""" # Get groups this repo is shared. if request.user.org: org_id = request.user.org['org_id'] repo_shared_groups = get_org_groups_by_repo(org_id, repo_id) else: repo_shared_groups = get_shared_groups_by_repo(repo_id) # Filter out groups that user in joined. groups = [ x for x in repo_shared_groups if is_group_user(x.id, username)] if len(groups) > 1: ctx = {} ctx['groups'] = groups repogrp_str = render_to_string("snippets/repo_group_list.html", ctx) else: repogrp_str = '' file_path_hash = md5_constructor(urllib2.quote(path.encode('utf-8'))).hexdigest()[:12] # fetch file contributors and latest contributor contributors, last_modified, last_commit_id = get_file_contributors(repo_id, path.encode('utf-8'), file_path_hash, obj_id) latest_contributor = contributors[0] if contributors else None # check whether file is starred is_starred = False org_id = -1 if request.user.org: org_id = request.user.org['org_id'] is_starred = is_file_starred(username, repo.id, path.encode('utf-8'), org_id) template = 'view_file_%s.html' % ret_dict['filetype'].lower() search_repo_id = None if not repo.encrypted: search_repo_id = repo.id return render_to_response(template, { 'repo': repo, 'obj_id': obj_id, 'filename': u_filename, 'path': path, 'zipped': zipped, 'current_commit': current_commit, 'fileext': fileext, 'raw_path': raw_path, 'fileshare': fileshare, 'protocol': http_or_https, 'domain': domain, 'file_shared_link': file_shared_link, 'contacts': contacts, 'err': ret_dict['err'], 'file_content': ret_dict['file_content'], 'file_enc': ret_dict['file_enc'], 'encoding': ret_dict['encoding'], 'file_encoding_list':ret_dict['file_encoding_list'], 'html_exists': ret_dict['html_exists'], 'html_detail': ret_dict.get('html_detail', {}), 'filetype': ret_dict['filetype'], "applet_root": get_ccnetapplet_root(), 'groups': groups, 'use_pdfjs':USE_PDFJS, 'contributors': contributors, 'latest_contributor': latest_contributor, 'last_modified': last_modified, 'last_commit_id': last_commit_id, 'repo_group_str': repogrp_str, 'is_starred': is_starred, 'user_perm': user_perm, 'img_prev': img_prev, 'img_next': img_next, 'search_repo_id': search_repo_id, }, context_instance=RequestContext(request))
def view_file(request, repo_id): """ Steps to view file: 1. Get repo id and file path. 2. Check user's permission. 3. Check whether this file can be viewed online. 4.1 Get file content if file is text file. 4.2 Prepare flash if file is document. 4.3 Prepare or use pdfjs if file is pdf. 4.4 Other file return it's raw path. """ username = request.user.username # check arguments repo = get_repo(repo_id) if not repo: raise Http404 path = request.GET.get("p", "/").rstrip("/") obj_id = get_file_id_by_path(repo_id, path) if not obj_id: return render_error(request, _(u"File does not exist")) # construct some varibles u_filename = os.path.basename(path) current_commit = get_commits(repo_id, 0, 1)[0] # Check whether user has permission to view file and get file raw path, # render error page if permission deny. raw_path, inner_path, user_perm = get_file_view_path_and_perm(request, repo_id, obj_id, path) if not user_perm: return render_permission_error(request, _(u"Unable to view file")) # check if the user is the owner or not, for 'private share' if is_org_context(request): repo_owner = seafile_api.get_org_repo_owner(repo.id) is_repo_owner = True if repo_owner == username else False else: is_repo_owner = seafile_api.is_repo_owner(username, repo.id) # get file type and extension filetype, fileext = get_file_type_and_ext(u_filename) img_prev = None img_next = None ret_dict = { "err": "", "file_content": "", "encoding": "", "file_enc": "", "file_encoding_list": [], "html_exists": False, "filetype": filetype, } fsize = get_file_size(repo.store_id, repo.version, obj_id) exceeds_limit, err_msg = file_size_exceeds_preview_limit(fsize, filetype) if exceeds_limit: ret_dict["err"] = err_msg else: """Choose different approach when dealing with different type of file.""" if is_textual_file(file_type=filetype): handle_textual_file(request, filetype, inner_path, ret_dict) if filetype == MARKDOWN: c = ret_dict["file_content"] ret_dict["file_content"] = convert_md_link(c, repo_id, username) elif filetype == DOCUMENT: handle_document(inner_path, obj_id, fileext, ret_dict) elif filetype == SPREADSHEET: handle_spreadsheet(inner_path, obj_id, fileext, ret_dict) elif filetype == OPENDOCUMENT: if fsize == 0: ret_dict["err"] = _(u"Invalid file format.") elif filetype == PDF: handle_pdf(inner_path, obj_id, fileext, ret_dict) elif filetype == IMAGE: parent_dir = os.path.dirname(path) dirs = seafile_api.list_dir_by_commit_and_path(current_commit.repo_id, current_commit.id, parent_dir) if not dirs: raise Http404 img_list = [] for dirent in dirs: if not stat.S_ISDIR(dirent.props.mode): fltype, flext = get_file_type_and_ext(dirent.obj_name) if fltype == "Image": img_list.append(dirent.obj_name) if len(img_list) > 1: img_list.sort(lambda x, y: cmp(x.lower(), y.lower())) cur_img_index = img_list.index(u_filename) if cur_img_index != 0: img_prev = posixpath.join(parent_dir, img_list[cur_img_index - 1]) if cur_img_index != len(img_list) - 1: img_next = posixpath.join(parent_dir, img_list[cur_img_index + 1]) else: pass # generate file path navigator zipped = gen_path_link(path, repo.name) # file shared link l = FileShare.objects.filter(repo_id=repo_id).filter(username=username).filter(path=path) fileshare = l[0] if len(l) > 0 else None http_or_https = request.is_secure() and "https" or "http" domain = RequestSite(request).domain if fileshare: file_shared_link = gen_file_share_link(fileshare.token) else: file_shared_link = "" for g in request.user.joined_groups: g.avatar = grp_avatar(g.id, 20) """List repo groups""" # Get groups this repo is shared. if request.user.org: org_id = request.user.org.org_id repo_shared_groups = get_org_groups_by_repo(org_id, repo_id) else: repo_shared_groups = get_shared_groups_by_repo(repo_id) # Filter out groups that user in joined. groups = [x for x in repo_shared_groups if is_group_user(x.id, username)] if len(groups) > 1: ctx = {} ctx["groups"] = groups repogrp_str = render_to_string("snippets/repo_group_list.html", ctx) else: repogrp_str = "" file_path_hash = hashlib.md5(urllib2.quote(path.encode("utf-8"))).hexdigest()[:12] # fetch file contributors and latest contributor contributors, last_modified, last_commit_id = FileContributors.objects.get_file_contributors( repo_id, path.encode("utf-8"), file_path_hash, obj_id ) latest_contributor = contributors[0] if contributors else None # check whether file is starred is_starred = False org_id = -1 if request.user.org: org_id = request.user.org.org_id is_starred = is_file_starred(username, repo.id, path.encode("utf-8"), org_id) template = "view_file_%s.html" % ret_dict["filetype"].lower() return render_to_response( template, { "repo": repo, "is_repo_owner": is_repo_owner, "obj_id": obj_id, "filename": u_filename, "path": path, "zipped": zipped, "current_commit": current_commit, "fileext": fileext, "raw_path": raw_path, "fileshare": fileshare, "protocol": http_or_https, "domain": domain, "file_shared_link": file_shared_link, "err": ret_dict["err"], "file_content": ret_dict["file_content"], "file_enc": ret_dict["file_enc"], "encoding": ret_dict["encoding"], "file_encoding_list": ret_dict["file_encoding_list"], "html_exists": ret_dict["html_exists"], "html_detail": ret_dict.get("html_detail", {}), "filetype": ret_dict["filetype"], "groups": groups, "use_pdfjs": USE_PDFJS, "contributors": contributors, "latest_contributor": latest_contributor, "last_modified": last_modified, "last_commit_id": last_commit_id, "repo_group_str": repogrp_str, "is_starred": is_starred, "user_perm": user_perm, "img_prev": img_prev, "img_next": img_next, "highlight_keyword": settings.HIGHLIGHT_KEYWORD, }, context_instance=RequestContext(request), )