def _decorated(request, group_id, *args, **kwargs): group_id_int = int(group_id) # Checked by URL Conf group = get_group(group_id_int) if not group: group_list_url = reverse('groups') return HttpResponseRedirect(group_list_url) group.is_staff = False if PublicGroup.objects.filter(group_id=group.id): group.is_pub = True else: group.is_pub = False if not request.user.is_authenticated(): if not group.is_pub: login_url = settings.LOGIN_URL path = urlquote(request.get_full_path()) tup = login_url, REDIRECT_FIELD_NAME, path return HttpResponseRedirect('%s?%s=%s' % tup) else: group.view_perm = "pub" return func(request, group, *args, **kwargs) joined = is_group_member(group_id_int, request.user.username) if joined: group.view_perm = "joined" group.is_staff = is_group_staff(group, request.user) return func(request, group, *args, **kwargs) if group.is_pub: group.view_perm = "pub" return func(request, group, *args, **kwargs) return render(request, 'error.html', { 'error_msg': _('Permission denied'), })
def format_group_join_request(self): """ Arguments: - `self`: """ d = json.loads(self.detail) username = d['username'] group_id = d['group_id'] join_request_msg = d['join_request_msg'] group = seaserv.get_group(group_id) if group is None: self.delete() return None nickname = email2nickname(username) msg = _(u"User <a href='%(user_profile)s'>%(username)s</a> has asked to join group <a href='%(href)s'>%(group_name)s</a>, verification message: %(join_request_msg)s") % { 'user_profile': reverse('user_profile', args=[username]), 'username': username, 'href': reverse('group_members', args=[group_id]), 'group_name': group.group_name, 'join_request_msg': join_request_msg, } return msg
def format_group_message_title(self): """ Arguments: - `self`: """ try: d = self.group_message_detail_to_dict() except self.InvalidDetailError as e: return _(u"Internal error") group_id = d.get("group_id") group = seaserv.get_group(group_id) if group is None: self.delete() return None msg_from = d.get("msg_from") if msg_from is None: msg = _(u"<a href='%(href)s'>%(group_name)s</a> has a new discussion.") % { "href": reverse("group_discuss", args=[group.id]), "group_name": group.group_name, } else: msg = _(u"%(user)s posted a new discussion in <a href='%(href)s'>%(group_name)s</a>.") % { "href": reverse("group_discuss", args=[group.id]), "user": escape(email2nickname(msg_from)), "group_name": group.group_name, } return msg
def _decorated(request, group_id, *args, **kwargs): group_id_int = int(group_id) # Checked by URL Conf group = get_group(group_id_int) if not group: group_list_url = reverse('groups') return HttpResponseRedirect(group_list_url) group.is_staff = False group.is_pub = False if not request.user.is_authenticated(): if not group.is_pub: login_url = settings.LOGIN_URL path = urlquote(request.get_full_path()) tup = login_url, REDIRECT_FIELD_NAME, path return HttpResponseRedirect('%s?%s=%s' % tup) else: group.view_perm = "pub" return func(request, group, *args, **kwargs) joined = is_group_member(group_id_int, request.user.username) if joined: group.view_perm = "joined" group.is_staff = is_group_staff(group, request.user) return func(request, group, *args, **kwargs) if group.is_pub: group.view_perm = "pub" return func(request, group, *args, **kwargs) return render(request, 'error.html', { 'error_msg': _('Permission denied'), })
def format_group_join_request(self): """ Arguments: - `self`: """ d = json.loads(self.detail) username = d['username'] group_id = d['group_id'] join_request_msg = d['join_request_msg'] group = seaserv.get_group(group_id) if group is None: self.delete() return None msg = _( u"User <a href='%(user_profile)s'>%(username)s</a> has asked to join group <a href='%(href)s'>%(group_name)s</a>, verification message: %(join_request_msg)s" ) % { 'user_profile': reverse('user_profile', args=[username]), 'username': username, 'href': reverse('group_members', args=[group_id]), 'group_name': group.group_name, 'join_request_msg': escape(join_request_msg), } return msg
def _decorated(view, request, group_id, *args, **kwargs): group_id = int(group_id) # Checked by URL Conf try: group = seaserv.get_group(group_id) except SearpcError as e: logger.error(e) error_msg = _(u'Internal Server Error') return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) if not group: error_msg = _(u'Group does not exist.') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) username = request.user.username try: is_group_member = seaserv.is_group_user(group_id, username) except SearpcError as e: logger.error(e) error_msg = _(u'Internal Server Error') return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) if not is_group_member: error_msg = _(u'Permission denied') return api_error(status.HTTP_403_FORBIDDEN, error_msg) return func(view, request, group_id, *args, **kwargs)
def check_group_folder_perm_args(from_user, repo_id, path, group_id, perm = None): if not seafile_api.get_repo(repo_id): return {'error': _(u'Library does not exist.'), 'status': 400} if check_repo_access_permission(repo_id, from_user) != 'rw': return {'error': _('Permission denied'), 'status': 403} if perm is not None: # add or toggle folder perm if seafile_api.get_dir_id_by_path(repo_id, path) is None: return {'error': _('Invalid path'), 'status': 400} if perm != 'r' and perm != 'rw': return {'error': _('Invalid folder permission'), 'status': 400} if not path.startswith('/'): return {'error': _('Path should start with "/"'), 'status': 400} if path != '/' and path.endswith('/'): return {'error': _('Path should NOT ends with "/"'), 'status': 400} if not seaserv.get_group(group_id): return {'error': _('Invalid group'), 'status': 400} return {'success': True}
def _decorated(view, request, group_id, *args, **kwargs): group_id_int = int(group_id) # Checked by URL Conf group = get_group(group_id_int) if not group: return api_error(status.HTTP_404_NOT_FOUND, 'Group not found.') group.is_staff = False if PublicGroup.objects.filter(group_id=group.id): group.is_pub = True else: group.is_pub = False joined = is_group_user(group_id_int, request.user.username) if joined: group.view_perm = "joined" group.is_staff = is_group_staff(group, request.user) return func(view, request, group, *args, **kwargs) if request.user.is_staff: # viewed by system admin group.view_perm = "sys_admin" return func(view, request, group, *args, **kwargs) if group.is_pub: group.view_perm = "pub" return func(view, request, group, *args, **kwargs) # Return group public info page. return api_error(status.HTTP_403_FORBIDDEN, 'Forbid to access this group.')
def check_group_folder_perm_args(request_user, repo_id, path, group_id, perm=None): if not seafile_api.get_repo(repo_id): return {'error': _(u'Library does not exist.'), 'status': 400} if check_repo_access_permission(repo_id, request_user) != 'rw': return {'error': _('Permission denied'), 'status': 403} if perm is not None: # add or toggle folder perm if seafile_api.get_dir_id_by_path(repo_id, path) is None: return {'error': _('Invalid path'), 'status': 400} if perm != 'r' and perm != 'rw': return {'error': _('Invalid folder permission'), 'status': 400} if not path.startswith('/'): return {'error': _('Path should start with "/"'), 'status': 400} if path != '/' and path.endswith('/'): return {'error': _('Path should NOT ends with "/"'), 'status': 400} if group_id and not seaserv.get_group(group_id): return {'error': _('Invalid group'), 'status': 400} return {'success': True}
def list_group_shared_items(self, request, repo_id, path): username = request.user.username if is_org_context(request): org_id = request.user.org.org_id if path == '/': share_items = seafile_api.list_org_repo_shared_group(org_id, username, repo_id) else: share_items = seafile_api.get_org_shared_groups_for_subdir(org_id, repo_id, path, username) else: if path == '/': share_items = seafile_api.list_repo_shared_group_by_user(username, repo_id) else: share_items = seafile_api.get_shared_groups_for_subdir(repo_id, path, username) ret = [] for item in share_items: ret.append({ "share_type": "group", "group_info": { "id": item.group_id, "name": seaserv.get_group(item.group_id).group_name, }, "permission": item.perm, }) return ret
def list_group_shared_items(self, request, repo_id, path): username = request.user.username if is_org_context(request): org_id = request.user.org.org_id if path == '/': share_items = seafile_api.list_org_repo_shared_group( org_id, username, repo_id) else: share_items = seafile_api.get_org_shared_groups_for_subdir( org_id, repo_id, path, username) else: if path == '/': share_items = seafile_api.list_repo_shared_group_by_user( username, repo_id) else: share_items = seafile_api.get_shared_groups_for_subdir( repo_id, path, username) ret = [] for item in share_items: ret.append({ "share_type": "group", "group_info": { "id": item.group_id, "name": seaserv.get_group(item.group_id).group_name, }, "permission": item.perm, }) return ret
def get_group_info(request, group_id, avatar_size=GROUP_AVATAR_DEFAULT_SIZE): group = seaserv.get_group(group_id) try: avatar_url, is_default, date_uploaded = api_grp_avatar_url( group.id, avatar_size) except Exception as e: logger.error(e) avatar_url = get_default_group_avatar_url() val = utc_to_local(dt(group.timestamp)) group_info = { "id": group.id, "name": group.group_name, "owner": group.creator_name, "created_at": val.strftime("%Y-%m-%dT%H:%M:%S") + DateFormat(val).format('O'), "avatar_url": request.build_absolute_uri(avatar_url), "admins": get_group_admins(group.id), } return group_info
def format_group_message_title(self): """ Arguments: - `self`: """ try: d = self.group_message_detail_to_dict() except self.InvalidDetailError as e: return _(u"Internal error") group_id = d.get('group_id') group = seaserv.get_group(group_id) if group is None: self.delete() return None msg_from = d.get('msg_from') if msg_from is None: msg = _( u"<a href='%(href)s'>%(group_name)s</a> has a new discussion." ) % { 'href': reverse('group_discuss', args=[group.id]), 'group_name': group.group_name } else: msg = _( u"%(user)s posted a new discussion in <a href='%(href)s'>%(group_name)s</a>." ) % { 'href': reverse('group_discuss', args=[group.id]), 'user': escape(email2nickname(msg_from)), 'group_name': group.group_name } return msg
def group_message_remove(request, group_id, msg_id): """ Remove group message and all message replies and attachments. """ # Checked by URL Conf group_id_int = int(group_id) msg_id = int(msg_id) group = get_group(group_id_int) if not group: raise Http404 # Test whether user is in the group if not is_group_user(group_id_int, request.user.username): raise Http404 try: gm = GroupMessage.objects.get(id=msg_id) except GroupMessage.DoesNotExist: return HttpResponse(json.dumps({'success': False, 'err_msg':_(u"The message doesn't exist")}), content_type='application/json; charset=utf-8') else: # Test whether user is group admin or message owner. if seaserv.check_group_staff(group_id, request.user.username) or \ gm.from_email == request.user.username: gm.delete() return HttpResponse(json.dumps({'success': True}), content_type='application/json; charset=utf-8') else: return HttpResponse(json.dumps({'success': False, 'err_msg': _(u"You don't have the permission.")}), content_type='application/json; charset=utf-8')
def _decorated(request, group_id, *args, **kwargs): group_id_int = int(group_id) # Checked by URL Conf group = get_group(group_id_int) if not group: return HttpResponseRedirect(reverse('group_list', args=[])) group.is_staff = False if PublicGroup.objects.filter(group_id=group.id): group.is_pub = True else: group.is_pub = False if not request.user.is_authenticated(): if not group.is_pub: login_url = settings.LOGIN_URL path = urlquote(request.get_full_path()) tup = login_url, REDIRECT_FIELD_NAME, path return HttpResponseRedirect('%s?%s=%s' % tup) else: group.view_perm = "pub" return func(request, group, *args, **kwargs) joined = is_group_user(group_id_int, request.user.username) if joined: group.view_perm = "joined" group.is_staff = is_group_staff(group, request.user) return func(request, group, *args, **kwargs) if group.is_pub: group.view_perm = "pub" return func(request, group, *args, **kwargs) return render_to_response('error.html', { 'error_msg': _('Permission denied'), }, context_instance=RequestContext(request))
def format_add_user_to_group(self): """ Arguments: - `self`: """ try: d = json.loads(self.detail) except Exception as e: logger.error(e) return _(u"Internal error") group_staff = d['group_staff'] group_id = d['group_id'] group = seaserv.get_group(group_id) if group is None: self.delete() return None msg = _(u"User <a href='%(user_profile)s'>%(group_staff)s</a> has added you to group <a href='%(href)s'>%(group_name)s</a>") % { 'user_profile': reverse('user_profile', args=[group_staff]), 'group_staff': group_staff, 'href': reverse('view_group', args=[group_id]), 'group_name': group.group_name, } return msg
def format_group_join_request(self): """ Arguments: - `self`: """ try: d = json.loads(self.detail) except Exception as e: logger.error(e) return _(u"Internal error") username = d['username'] group_id = d['group_id'] join_request_msg = d['join_request_msg'] group = seaserv.get_group(group_id) if group is None: self.delete() return None msg = _(u"User <a href='%(user_profile)s'>%(username)s</a> has asked to join group <a href='%(href)s'>%(group_name)s</a>, verification message: %(join_request_msg)s") % { 'user_profile': reverse('user_profile', args=[username]), 'username': username, 'href': reverse('group_members', args=[group_id]), 'group_name': group.group_name, 'join_request_msg': escape(join_request_msg), } return msg
def format_group_message(self): """ Arguments: - `self`: """ try: d = self.group_message_detail_to_dict() except self.InvalidDetailError as e: return _(u"Internal error") group_id = d.get('group_id') group = seaserv.get_group(group_id) if group is None: self.delete() return None msg_from = d.get('msg_from') if msg_from is None: msg = _(u"<a href='%(href)s'>%(group_name)s</a> has new discussion") % { 'href': reverse('group_discuss', args=[group.id]), 'group_name': group.group_name} else: msg = _(u"%(user)s posted a new discussion in <a href='%(href)s'>%(group_name)s</a>") % { 'href': reverse('group_discuss', args=[group.id]), 'user': msg_from, 'group_name': group.group_name} return msg
def get_group_info(request, group_id, avatar_size=GROUP_AVATAR_DEFAULT_SIZE): group = seaserv.get_group(group_id) try: avatar_url, is_default, date_uploaded = api_grp_avatar_url( group.id, avatar_size) except Exception as e: logger.error(e) avatar_url = get_default_group_avatar_url() isoformat_timestr = timestamp_to_isoformat_timestr(group.timestamp) group_info = { "id": group.id, "parent_group_id": group.parent_group_id, "name": group.group_name, "owner": group.creator_name, "created_at": isoformat_timestr, "avatar_url": request.build_absolute_uri(avatar_url), "admins": get_group_admins(group.id), "wiki_enabled": is_wiki_mod_enabled_for_group(group_id) } # parent_group_id = 0: non department group # parent_group_id = -1: top department group # parent_group_id = n(n > 0): sub department group, n is parent group's id if group.parent_group_id != 0: group_info['group_quota'] = seafile_api.get_group_quota(group_id) group_info['group_quota_usage'] = seafile_api.get_group_quota_usage( group_id) return group_info
def list_group_shared_items(self, request, repo_id, path): if is_org_context(request): # when calling seafile API to share authority related functions, change the uesrname to repo owner. repo_owner = seafile_api.get_org_repo_owner(repo_id) org_id = request.user.org.org_id if path == '/': share_items = seafile_api.list_org_repo_shared_group(org_id, repo_owner, repo_id) else: share_items = seafile_api.get_org_shared_groups_for_subdir(org_id, repo_id, path, repo_owner) else: repo_owner = seafile_api.get_repo_owner(repo_id) if path == '/': share_items = seafile_api.list_repo_shared_group_by_user(repo_owner, repo_id) else: share_items = seafile_api.get_shared_groups_for_subdir(repo_id, path, repo_owner) ret = [] # change is_admin to True if user in admin groups. admin_groups = ExtraGroupsSharePermission.objects.get_admin_groups_by_repo(repo_id) for item in share_items: ret.append({ "share_type": "group", "group_info": { "id": item.group_id, "name": seaserv.get_group(item.group_id).group_name, }, "permission": item.perm, "is_admin": item.group_id in admin_groups, }) return ret
def group_recommend(request): """ Recommend a file or directory to a group. """ if request.method != 'POST': raise Http404 next = request.META.get('HTTP_REFERER', None) if not next: next = SITE_ROOT form = GroupRecommendForm(request.POST) if form.is_valid(): repo_id = form.cleaned_data['repo_id'] attach_type = form.cleaned_data['attach_type'] path = form.cleaned_data['path'] message = form.cleaned_data['message'] groups = request.POST.getlist('groups') # groups is a group_id list, e.g. [u'1', u'7'] username = request.user.username # Check group id format for group_id in groups: try: group_id = int(group_id) except ValueError: messages.error(request, _(u'Error: wrong group id')) return HttpResponseRedirect(next) # Get that group group = get_group(group_id) # TODO: Check whether repo is in the group and Im in the group if not is_group_user(group_id, username): err_msg = _(u'Error: you are not in group %s.') messages.error(request, err_msg % group.group_name) continue # save message to group gm = GroupMessage(group_id=group_id, from_email=username, message=message) gm.save() # send signal grpmsg_added.send(sender=GroupMessage, group_id=group_id, from_email=request.user.username) # save attachment ma = MessageAttachment(group_message=gm, repo_id=repo_id, attach_type=attach_type, path=path, src='recommend') ma.save() group_url = reverse('group_info', args=[group_id]) msg = _(u'Successfully recommended to <a href="%(url)s" target="_blank">%(name)s</a>.') %\ {'url':group_url, 'name':group.group_name} messages.add_message(request, messages.INFO, msg) else: messages.add_message(request, messages.ERROR, _(u'Failed to recommend.')) return HttpResponseRedirect(next)
def format_group_join_request(self): """ Arguments: - `self`: """ d = json.loads(self.detail) username = d["username"] group_id = d["group_id"] join_request_msg = d["join_request_msg"] group = seaserv.get_group(group_id) if group is None: self.delete() return None msg = _( u"User <a href='%(user_profile)s'>%(username)s</a> has asked to join group <a href='%(href)s'>%(group_name)s</a>, verification message: %(join_request_msg)s" ) % { "user_profile": reverse("user_profile", args=[username]), "username": username, "href": reverse("group_members", args=[group_id]), "group_name": group.group_name, "join_request_msg": escape(join_request_msg), } return msg
def group_message_remove(request, group_id, msg_id): """ Remove group message and all message replies and attachments. """ # Checked by URL Conf group_id_int = int(group_id) msg_id = int(msg_id) group = get_group(group_id_int) if not group: raise Http404 # Test whether user is in the group if not is_group_user(group_id_int, request.user.username): raise Http404 try: gm = GroupMessage.objects.get(id=msg_id) except GroupMessage.DoesNotExist: return HttpResponse( json.dumps({"success": False, "err_msg": _(u"The message doesn't exist")}), content_type="application/json; charset=utf-8", ) else: # Test whether user is group admin or message owner. if seaserv.check_group_staff(group_id, request.user.username) or gm.from_email == request.user.username: gm.delete() return HttpResponse(json.dumps({"success": True}), content_type="application/json; charset=utf-8") else: return HttpResponse( json.dumps({"success": False, "err_msg": _(u"You don't have the permission.")}), content_type="application/json; charset=utf-8", )
def delete(self, request, group_id, table_id): """ delete a dtable from a group :param request: :param group_id: :param table_id: :return: """ group = seaserv.get_group(group_id) if not group: error_msg = _('Group not found.') return api_error(status.HTTP_404_NOT_FOUND, error_msg) owner = '%s@seafile_group' % (group_id, ) workspace = Workspaces.objects.get_workspace_by_owner(owner) if not workspace: error_msg = _('Workspace not found') return api_error(status.HTTP_404_NOT_FOUND, error_msg) dtable = DTables.objects.filter(workspace=workspace, id=int(table_id)).first() if not dtable: error_msg = _('Table not found') return api_error(status.HTTP_404_NOT_FOUND, error_msg) username = request.user.username # delete asset asset_dir_path = '/asset/' + str(dtable.uuid) asset_dir_id = seafile_api.get_dir_id_by_path(workspace.repo_id, asset_dir_path) if asset_dir_id: parent_dir = os.path.dirname(asset_dir_path) file_name = os.path.basename(asset_dir_path) try: seafile_api.del_file(workspace.repo_id, parent_dir, file_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) # delete table try: table_file_name = dtable.name + FILE_TYPE seafile_api.del_file(workspace.repo_id, '/', table_file_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) try: DTables.objects.delete_dtable(workspace, dtable.name) 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 create_group_repo(request, group_id): """Create a repo and share it to current group""" content_type = 'application/json; charset=utf-8' def json_error(err_msg): result = {'error': err_msg} return HttpResponseBadRequest(json.dumps(result), content_type=content_type) group_id = int(group_id) group = get_group(group_id) if not group: return json_error(_(u'Failed to create: the group does not exist.')) # Check whether user belongs to the group. username = request.user.username if not is_group_user(group_id, username): return json_error(_(u'Failed to create: you are not in the group.')) form = SharedRepoCreateForm(request.POST) if not form.is_valid(): return json_error(str(form.errors.values()[0])) # Form is valid, create group repo repo_name = form.cleaned_data['repo_name'] repo_desc = form.cleaned_data['repo_desc'] permission = form.cleaned_data['permission'] encryption = int(form.cleaned_data['encryption']) uuid = form.cleaned_data['uuid'] magic_str = form.cleaned_data['magic_str'] encrypted_file_key = form.cleaned_data['encrypted_file_key'] if is_org_context(request): org_id = request.user.org.org_id try: if encryption: repo_id = seafile_api.create_org_enc_repo(uuid, repo_name, repo_desc, username, magic_str, encrypted_file_key, enc_version=2, org_id=org_id) else: repo_id = seafile_api.create_org_repo(repo_name, repo_desc, username, None, org_id) except SearpcError, e: logger.error(e) return json_error(_(u'Failed to create')) try: seafile_api.add_org_group_repo(repo_id, org_id, group.id, username, permission) except SearpcError, e: logger.error(e) return json_error(_(u'Failed to create: internal error.'))
def get(self, request, workspace_id, name): """list dtable related users """ table_name = name table_file_name = table_name + FILE_TYPE # resource check workspace = Workspaces.objects.get_workspace_by_id(workspace_id) if not workspace: error_msg = 'Workspace %s not found.' % workspace_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) 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 api_error(status.HTTP_404_NOT_FOUND, error_msg) repo_id = workspace.repo_id repo = seafile_api.get_repo(repo_id) if not repo: error_msg = 'Library %s not found.' % repo_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) dtable = DTables.objects.get_dtable(workspace, table_name) if not dtable: error_msg = 'dtable %s not found.' % table_name return api_error(status.HTTP_404_NOT_FOUND, error_msg) 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: error_msg = 'file %s not found.' % table_file_name return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check username = request.user.username owner = workspace.owner if not check_dtable_permission(username, owner) and \ not check_dtable_share_permission(dtable, username): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # main user_list = list() try: email_list = list_dtable_related_users(workspace, dtable) for email in email_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 msg_reply_new(request): username = request.user.username grpmsg_reply_list = [x for x in UserNotification.objects.get_group_msg_reply_notices(username)] msg_ids = [] for e in grpmsg_reply_list: try: msg_id = e.grpmsg_reply_detail_to_dict().get("msg_id") except UserNotification.InvalidDetailError: continue msg_ids.append(msg_id) group_msgs = [] for msg_id in msg_ids: try: m = GroupMessage.objects.get(id=msg_id) except GroupMessage.DoesNotExist: continue else: if m in group_msgs: continue # get group name group = get_group(m.group_id) if not group: continue m.group_name = group.group_name # get attachements attachments = m.messageattachment_set.all() for attachment in attachments: path = attachment.path if path == "/": repo = get_repo(attachment.repo_id) if not repo: continue attachment.name = repo.name else: attachment.name = os.path.basename(path) m.attachments = attachments # get message replies reply_list = MessageReply.objects.filter(reply_to=m) m.reply_cnt = reply_list.count() if m.reply_cnt > 3: m.replies = reply_list[m.reply_cnt - 3 :] else: m.replies = reply_list group_msgs.append(m) # remove new group msg reply notification UserNotification.objects.seen_group_msg_reply_notice(username) return render_to_response( "group/new_msg_reply.html", {"group_msgs": group_msgs}, context_instance=RequestContext(request) )
def msg_reply_new(request): username = request.user.username grpmsg_reply_list = [ x for x in UserNotification.objects.get_group_msg_reply_notices(username) ] msg_ids = [] for e in grpmsg_reply_list: try: msg_id = e.grpmsg_reply_detail_to_dict().get('msg_id') except UserNotification.InvalidDetailError: continue msg_ids.append(msg_id) group_msgs = [] for msg_id in msg_ids: try: m = GroupMessage.objects.get(id=msg_id) except GroupMessage.DoesNotExist: continue else: if m in group_msgs: continue # get group name group = get_group(m.group_id) if not group: continue m.group_name = group.group_name # get attachements attachments = m.messageattachment_set.all() for attachment in attachments: path = attachment.path if path == '/': repo = get_repo(attachment.repo_id) if not repo: continue attachment.name = repo.name else: attachment.name = os.path.basename(path) m.attachments = attachments # get message replies reply_list = MessageReply.objects.filter(reply_to=m) m.reply_cnt = reply_list.count() if m.reply_cnt > 3: m.replies = reply_list[m.reply_cnt - 3:] else: m.replies = reply_list group_msgs.append(m) # remove new group msg reply notification UserNotification.objects.seen_group_msg_reply_notice(username) return render_to_response("group/new_msg_reply.html", { 'group_msgs': group_msgs, }, context_instance=RequestContext(request))
def create_group_repo(request, group_id): """Create a repo and share it to current group""" content_type = 'application/json; charset=utf-8' def json_error(err_msg): result = {'error': [err_msg]} return HttpResponseBadRequest(json.dumps(result), content_type=content_type) group_id = int(group_id) if not get_group(group_id): return json_error(_(u'Failed to create: the group does not exist.')) # Check whether user belongs to the group. if not is_group_user(group_id, request.user.username): return json_error(_(u'Failed to create: you are not in the group.')) form = SharedRepoCreateForm(request.POST) if not form.is_valid(): return json_error(form.errors) else: repo_name = form.cleaned_data['repo_name'] repo_desc = form.cleaned_data['repo_desc'] permission = form.cleaned_data['permission'] encrypted = form.cleaned_data['encryption'] passwd = form.cleaned_data['passwd'] user = request.user.username org, base_template = check_and_get_org_by_group(group_id, user) if org: # create group repo in org context try: repo_id = create_org_repo(repo_name, repo_desc, user, passwd, org.org_id) except: repo_id = None if not repo_id: return json_error(_(u'Failed to create')) try: status = seafserv_threaded_rpc.add_org_group_repo(repo_id, org.org_id, group_id, user, permission) except SearpcError, e: status = -1 # if share failed, remove the newly created repo if status != 0: seafserv_threaded_rpc.remove_repo(repo_id) return json_error(_(u'Failed to create: internal error.')) else: result = {'success': True} return HttpResponse(json.dumps(result), content_type=content_type) else:
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 put(self, request, group_id): """ Rename, transfer a specific group """ group = seaserv.get_group(group_id) username = request.user.username new_group_name = request.data.get('name', None) if new_group_name: # rename a group # Check whether group name is validate. if not validate_group_name(new_group_name): error_msg = _(u'Group name can only contain letters, numbers, blank, hyphen or underscore') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Check whether group name is duplicated. if check_group_name_conflict(request, new_group_name): error_msg = _(u'There is already a group with that name.') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: seaserv.ccnet_threaded_rpc.set_group_name(group_id, new_group_name) except SearpcError as e: logger.error(e) error_msg = _(u'Internal Server Error') return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) new_creator= request.data.get('creator', None) if new_creator: # transfer a group if not is_valid_username(new_creator): error_msg = _('Creator %s is not valid.') % new_creator return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if new_creator == group.creator_name: error_msg = _('%s is already group owner') % new_creator return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: if not seaserv.is_group_user(group_id, new_creator): seaserv.ccnet_threaded_rpc.group_add_member(group_id, username, new_creator) if not seaserv.check_group_staff(group_id, new_creator): seaserv.ccnet_threaded_rpc.group_set_admin(group_id, new_creator) seaserv.ccnet_threaded_rpc.set_group_creator(group_id, new_creator) except SearpcError as e: logger.error(e) error_msg = _(u'Internal Server Error') return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # get new info of this group group_info = get_group_info(request, group_id, GROUP_AVATAR_DEFAULT_SIZE) return Response(group_info)
def create_group_repo(request, group_id): """Create a repo and share it to current group""" content_type = 'application/json; charset=utf-8' def json_error(err_msg): result = {'error': err_msg} return HttpResponseBadRequest(json.dumps(result), content_type=content_type) group_id = int(group_id) group = get_group(group_id) if not group: return json_error(_(u'Failed to create: the group does not exist.')) # Check whether user belongs to the group. username = request.user.username if not is_group_user(group_id, username): return json_error(_(u'Failed to create: you are not in the group.')) form = SharedRepoCreateForm(request.POST) if not form.is_valid(): return json_error(str(form.errors.values()[0])) # Form is valid, create group repo repo_name = form.cleaned_data['repo_name'] repo_desc = form.cleaned_data['repo_desc'] permission = form.cleaned_data['permission'] encryption = int(form.cleaned_data['encryption']) uuid = form.cleaned_data['uuid'] magic_str = form.cleaned_data['magic_str'] encrypted_file_key = form.cleaned_data['encrypted_file_key'] if is_org_context(request): org_id = request.user.org.org_id try: if encryption: repo_id = seafile_api.create_org_enc_repo( uuid, repo_name, repo_desc, username, magic_str, encrypted_file_key, enc_version=2, org_id=org_id) else: repo_id = seafile_api.create_org_repo(repo_name, repo_desc, username, None, org_id) except SearpcError, e: logger.error(e) return json_error(_(u'Failed to create')) try: seafile_api.add_org_group_repo(repo_id, org_id, group.id, username, permission) except SearpcError, e: logger.error(e) return json_error(_(u'Failed to create: internal error.'))
def group_share_repo(request, repo_id, group_id, from_email, permission): """ Share a repo to a group. """ # Check whether group exists group = get_group(group_id) if not group: return render_error(request, _(u"Failed to share: the group doesn't exist.")) if seafserv_threaded_rpc.group_share_repo(repo_id, group_id, from_email, permission) != 0: return render_error(request, _(u"Failed to share: internal error."))
def _decorated(request, group_id, *args, **kwargs): group_id_int = int(group_id) # Checked by URL Conf group = get_group(group_id_int) if not group: return HttpResponseRedirect(reverse('group_list', args=[])) joined = is_group_user(group_id_int, request.user.username) if not joined and not request.user.is_staff: # Return group public info page. return render_to_response('group/group_pubinfo.html', { 'group': group, }, context_instance=RequestContext(request)) return func(request, group, *args, **kwargs)
def format_group_message(self, notice): d = json.loads(notice.detail) group_id = d['group_id'] group = seaserv.get_group(int(group_id)) if group is None: notice.delete() notice.group_url = reverse('group_discuss', args=[group.id]) notice.group_msg_from = escape(email2nickname(d['msg_from'])) notice.group_name = group.group_name notice.group_msg_from_avatar_url = self.get_avatar_url(d['msg_from']) return notice
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 org_admin_group_info(request, group_id): group_id = int(group_id) group = get_group(group_id) org_id = request.user.org.org_id repos = seafile_api.get_org_group_repos(org_id, group_id) members = get_group_members(group_id) return render(request, 'organizations/org_admin_group_info.html', { 'group': group, 'repos': repos, 'members': members, })
def group_joinrequest(request, group_id): """ Handle post request to join a group. """ if not request.is_ajax() or request.method != 'POST': raise Http404 result = {} content_type = 'application/json; charset=utf-8' group_id = int(group_id) group =get_group(group_id) if not group: raise Http404 user = request.user.username # TODO: Group creator is group staff now, but may changed in future. staff = group.creator_name if is_group_user(group_id, user): # Already in the group. Normally, this case should not happen. err = _(u'You are already in the group.') return HttpResponseBadRequest(json.dumps({'error': err}), content_type=content_type) else: form = GroupJoinMsgForm(request.POST) if form.is_valid(): group_join_msg = form.cleaned_data['group_join_msg'] # Send the message to group staff. use_https = request.is_secure() domain = RequestSite(request).domain t = loader.get_template('group/group_join_email.html') c = { 'staff': staff, 'user': user, 'group_name': group.group_name, 'group_join_msg': group_join_msg, 'site_name': SITE_NAME, } try: send_mail(_(u'apply to join the group'), t.render(Context(c)), None, [staff], fail_silently=False) messages.success(request, _(u'Sent successfully, the group admin will handle it.')) return HttpResponse(json.dumps('success'), content_type=content_type) except: err = _(u'Failed to send. You can try it again later.') return HttpResponse(json.dumps({'error': err}), status=500, content_type=content_type) else: return HttpResponseBadRequest(json.dumps(form.errors), content_type=content_type)
def post(self, request): """ Create a group """ if not self._can_add_group(request): error_msg = _(u'You do not have permission to create group.') return api_error(status.HTTP_403_FORBIDDEN, error_msg) username = request.user.username group_name = request.data.get('group_name', '') group_name = group_name.strip() # Check whether group name is validate. if not validate_group_name(group_name): error_msg = _(u'Group name can only contain letters, numbers, blank, hyphen or underscore') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Check whether group name is duplicated. if check_group_name_conflict(request, group_name): error_msg = _(u'There is already a group with that name.') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Group name is valid, create that group. try: group_id = seaserv.ccnet_threaded_rpc.create_group(group_name, username) except SearpcError as e: logger.error(e) error_msg = _(u'Failed') return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) try: size = int(request.data.get('avatar_size', GROUP_AVATAR_DEFAULT_SIZE)) except ValueError: size = GROUP_AVATAR_DEFAULT_SIZE g = seaserv.get_group(group_id) try: avatar_url, is_default, date_uploaded = api_grp_avatar_url(g.id, size) except Exception as e: logger.error(e) avatar_url = get_default_group_avatar_url() val = utc_to_local(dt(g.timestamp)) new_group = { "id": g.id, "name": g.group_name, "creator": g.creator_name, "created_at": val.strftime("%Y-%m-%dT%H:%M:%S") + DateFormat(val).format('O'), "avatar_url": request.build_absolute_uri(avatar_url), "admins": self._get_group_admins(g.id), } return Response(new_group, status=status.HTTP_201_CREATED)
def _decorated(view, request, group_id, *args, **kwargs): group_id = int(group_id) # Checked by URL Conf try: group = seaserv.get_group(group_id) 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 group: error_msg = 'Group %d not found.' % group_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) return func(view, request, group_id, *args, **kwargs)
def get(self, request): """list all departments """ if not is_pro_version(): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') try: departments = ccnet_api.list_all_departments() except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) try: avatar_size = int( request.GET.get('avatar_size', GROUP_AVATAR_DEFAULT_SIZE)) except ValueError: avatar_size = GROUP_AVATAR_DEFAULT_SIZE result = [] for department in departments: department = seaserv.get_group(department.id) username = request.user.username if not is_group_member(department.id, username): continue try: avatar_url, is_default, date_uploaded = api_grp_avatar_url( department.id, avatar_size) except Exception as e: logger.error(e) avatar_url = get_default_group_avatar_url() created_at = timestamp_to_isoformat_timestr(department.timestamp) department_info = { "id": department.id, "email": '%s@seafile_group' % str(department.id), "parent_group_id": department.parent_group_id, "name": department.group_name, "owner": department.creator_name, "created_at": created_at, "avatar_url": request.build_absolute_uri(avatar_url), } result.append(department_info) return Response(result)
def format_group_message(self, notice): d = notice.group_message_detail_to_dict() group_id = d['group_id'] message = d['message'] group = seaserv.get_group(int(group_id)) if group is None: notice.delete() notice.group_url = reverse('group_discuss', args=[group.id]) notice.notice_from = escape(email2nickname(d['msg_from'])) notice.group_name = group.group_name notice.avatar_src = self.get_avatar_src(d['msg_from']) notice.grp_msg = message return notice
def msg_reply_new(request): notes = UserNotification.objects.filter(to_user=request.user.username) grpmsg_reply_list = [ n.detail for n in notes if \ n.msg_type == 'grpmsg_reply'] group_msgs = [] for msg_id in grpmsg_reply_list: try: m = GroupMessage.objects.get(id=msg_id) except GroupMessage.DoesNotExist: continue else: # get group name group = get_group(m.group_id) if not group: continue m.group_name = group.group_name # get attachement attachment = get_first_object_or_none(m.messageattachment_set.all()) if attachment: path = attachment.path if path == '/': repo = get_repo(attachment.repo_id) if not repo: continue attachment.name = repo.name else: attachment.name = os.path.basename(path) m.attachment = attachment # get message replies reply_list = MessageReply.objects.filter(reply_to=m) m.reply_cnt = reply_list.count() if m.reply_cnt > 3: m.replies = reply_list[m.reply_cnt - 3:] else: m.replies = reply_list group_msgs.append(m) # remove new group msg reply notification UserNotification.objects.filter(to_user=request.user.username, msg_type='grpmsg_reply').delete() return render_to_response("group/new_msg_reply.html", { 'group_msgs': group_msgs, }, context_instance=RequestContext(request))
def format_add_user_to_group(self, notice): d = json.loads(notice.detail) group_staff = d['group_staff'] group_id = d['group_id'] group = seaserv.get_group(group_id) if group is None: notice.delete() notice.notice_from = group_staff notice.avatar_src = self.get_avatar_src(group_staff) notice.group_staff_profile_url = reverse('user_profile', args=[group_staff]) notice.group_url = reverse('group_info', args=[group_id]) notice.group_name = group.group_name return notice
def format_group_join_request(self, notice): d = json.loads(notice.detail) username = d['username'] group_id = d['group_id'] join_request_msg = d['join_request_msg'] group = seaserv.get_group(group_id) if group is None: notice.delete() notice.grpjoin_user_profile_url = reverse('user_profile', args=[username]) notice.grpjoin_group_url = reverse('group_members', args=[group_id]) notice.grpjoin_username = username notice.grpjoin_group_name = group.group_name notice.grpjoin_request_msg = join_request_msg return notice
def format_group_join_request(self, notice): d = json.loads(notice.detail) username = d['username'] group_id = d['group_id'] join_request_msg = d['join_request_msg'] group = seaserv.get_group(group_id) if group is None: notice.delete() notice.grpjoin_user_profile_url = reverse('user_profile', args=[username]) notice.grpjoin_group_url = reverse('group_members', args=[group_id]) notice.grpjoin_username = username notice.grpjoin_group_name = group.group_name, notice.grpjoin_request_msg = join_request_msg, return notice
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 get(self, request): """list all departments """ try: departments = ccnet_api.list_all_departments() except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) try: avatar_size = int(request.GET.get('avatar_size', GROUP_AVATAR_DEFAULT_SIZE)) except ValueError: avatar_size = GROUP_AVATAR_DEFAULT_SIZE result = [] for department in departments: department = seaserv.get_group(department.id) username = request.user.username if not is_group_member(department.id, username): continue try: avatar_url, is_default, date_uploaded = api_grp_avatar_url(department.id, avatar_size) except Exception as e: logger.error(e) avatar_url = get_default_group_avatar_url() created_at = timestamp_to_isoformat_timestr(department.timestamp) department_info = { "id": department.id, "email": '%s@seafile_group' % str(department.id), "parent_group_id": department.parent_group_id, "name": department.group_name, "owner": department.creator_name, "created_at": created_at, "avatar_url": request.build_absolute_uri(avatar_url), } result.append(department_info) return Response(result)
def _decorated(view, request, repo_id, *args, **kwargs): 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 permission if is_org_context(request): repo_owner = seafile_api.get_org_repo_owner(repo_id) else: repo_owner = seafile_api.get_repo_owner(repo_id) username = request.user.username if repo.is_virtual or username != repo_owner: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # check arguments group_id = request.data.get('group_id', None) path = request.data.get('folder_path', None) perm = request.data.get('permission', None) try: group_id = int(group_id) except ValueError: error_msg = 'group_id invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if not seaserv.get_group(group_id): error_msg = 'Group %s not found.' % group_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) if path: path = path.rstrip('/') if path != '/' else path if seafile_api.get_dir_id_by_path(repo_id, path) is None: error_msg = 'Folder %s not found.' % path return api_error(status.HTTP_404_NOT_FOUND, error_msg) if request.method in ('POST', 'PUT') and perm not in ('r', 'rw'): error_msg = 'permission invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) return func(view, request, repo_id, *args, **kwargs)
def get_group_info(request, group_id, avatar_size=GROUP_AVATAR_DEFAULT_SIZE): group = seaserv.get_group(group_id) try: avatar_url, is_default, date_uploaded = api_grp_avatar_url(group.id, avatar_size) except Exception as e: logger.error(e) avatar_url = get_default_group_avatar_url() isoformat_timestr = timestamp_to_isoformat_timestr(group.timestamp) group_info = { "id": group.id, "name": group.group_name, "owner": group.creator_name, "created_at": isoformat_timestr, "avatar_url": request.build_absolute_uri(avatar_url), "admins": get_group_admins(group.id), "wiki_enabled": is_wiki_mod_enabled_for_group(group_id) } return group_info
def get(self, request, group_id): """ get workspace by group id get dtables from workspace :param request: :param group_id: :return: """ group = seaserv.get_group(group_id) if not group: error_msg = _('Group not found.') return api_error(status.HTTP_404_NOT_FOUND, error_msg) owner = '%s@seafile_group' % (group_id, ) workspace = Workspaces.objects.get_workspace_by_owner(owner) if not workspace: error_msg = _('Workspace not found') return api_error(status.HTTP_404_NOT_FOUND, error_msg) table_list = [] dtables = DTables.objects.filter(workspace=workspace) for dtable in dtables: dtable_dict = dict() dtable_dict['id'] = dtable.pk dtable_dict['workspace_id'] = dtable.workspace_id dtable_dict['uuid'] = dtable.uuid dtable_dict['name'] = dtable.name dtable_dict['creator'] = email2nickname(dtable.creator) dtable_dict['creator_email'] = dtable.creator dtable_dict['modifier'] = email2nickname(dtable.modifier) dtable_dict['created_at'] = datetime_to_isoformat_timestr( dtable.created_at) dtable_dict['updated_at'] = datetime_to_isoformat_timestr( dtable.updated_at) table_list.append(dtable_dict) return Response({ 'tables': table_list, 'group_name': group.group_name, })
def is_group_owner(group_id, email): group = seaserv.get_group(group_id) if email == group.creator_name: return True else: return False
def post(self, request, repo_id, format=None): """Update shared item permission. """ username = request.user.username repo = seafile_api.get_repo(repo_id) if not repo: return api_error(status.HTTP_404_NOT_FOUND, 'Library %s not found.' % repo_id) path = request.GET.get('p', '/') if seafile_api.get_dir_id_by_path(repo.id, path) is None: return api_error(status.HTTP_400_BAD_REQUEST, 'Directory not found.') if username != self.get_repo_owner(request, repo_id): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') shared_to_user, shared_to_group = self.handle_shared_to_args(request) permission = request.data.get('permission', 'r') if permission not in ['r', 'rw']: return api_error(status.HTTP_400_BAD_REQUEST, 'permission invalid.') path = request.GET.get('p', '/') if seafile_api.get_dir_id_by_path(repo.id, path) is None: return api_error(status.HTTP_404_NOT_FOUND, 'Folder %s not found.' % path) if path == '/': shared_repo = repo else: try: sub_repo = self.get_sub_repo_by_path(request, repo, path) if sub_repo: shared_repo = sub_repo else: # unlikely to happen return api_error(status.HTTP_404_NOT_FOUND, 'Failed to get sub repo') except SearpcError as e: logger.error(e) return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Internal Server Error') if shared_to_user: shared_to = request.GET.get('username') if shared_to is None or not is_valid_username(shared_to): return api_error(status.HTTP_400_BAD_REQUEST, 'Email %s invalid.' % shared_to) try: User.objects.get(email=shared_to) except User.DoesNotExist: return api_error(status.HTTP_400_BAD_REQUEST, 'Invalid user, should be registered') if is_org_context(request): org_id = request.user.org.org_id seaserv.seafserv_threaded_rpc.org_set_share_permission( org_id, shared_repo.id, username, shared_to, permission) else: seafile_api.set_share_permission(shared_repo.id, username, shared_to, permission) send_perm_audit_msg('modify-repo-perm', username, shared_to, repo_id, path, permission) if shared_to_group: gid = request.GET.get('group_id') try: gid = int(gid) except ValueError: return api_error(status.HTTP_400_BAD_REQUEST, 'group_id %s invalid.' % gid) group = seaserv.get_group(gid) if not group: return api_error(status.HTTP_404_NOT_FOUND, 'Group %s not found.' % gid) if is_org_context(request): org_id = request.user.org.org_id seaserv.seafserv_threaded_rpc.set_org_group_repo_permission( org_id, gid, shared_repo.id, permission) else: seafile_api.set_group_repo_permission(gid, shared_repo.id, permission) send_perm_audit_msg('modify-repo-perm', username, gid, repo_id, path, permission) return HttpResponse(json.dumps({'success': True}), status=200, content_type=json_content_type)
def put(self, request, repo_id, format=None): username = request.user.username repo = seafile_api.get_repo(repo_id) if not repo: return api_error(status.HTTP_404_NOT_FOUND, 'Library %s not found.' % repo_id) path = request.GET.get('p', '/') if seafile_api.get_dir_id_by_path(repo.id, path) is None: return api_error(status.HTTP_404_NOT_FOUND, 'Folder %s not found.' % path) if username != self.get_repo_owner(request, repo_id): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') if path != '/': try: sub_repo = self.get_or_create_sub_repo_by_path( request, repo, path) except SearpcError as e: logger.error(e) return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Failed to get sub repo.') else: sub_repo = None share_type = request.data.get('share_type') if share_type != 'user' and share_type != 'group': return api_error(status.HTTP_400_BAD_REQUEST, 'share_type invalid.') permission = request.data.get('permission', 'r') if permission not in ['r', 'rw']: return api_error(status.HTTP_400_BAD_REQUEST, 'permission invalid.') shared_repo = repo if path == '/' else sub_repo success, failed = [], [] if share_type == 'user': share_to_users = request.data.getlist('username') for to_user in share_to_users: if not is_valid_username(to_user): failed.append(to_user) continue try: User.objects.get(email=to_user) except User.DoesNotExist: failed.append(to_user) continue if not check_user_share_quota( username, shared_repo, users=[to_user]): return api_error(status.HTTP_403_FORBIDDEN, 'Not enough quota.') try: if is_org_context(request): org_id = request.user.org.org_id seaserv.seafserv_threaded_rpc.org_add_share( org_id, shared_repo.id, username, to_user, permission) else: seafile_api.share_repo(shared_repo.id, username, to_user, permission) # send a signal when sharing repo successful share_repo_to_user_successful.send(sender=None, from_user=username, to_user=to_user, repo=shared_repo) success.append({ "share_type": "user", "user_info": { "name": to_user, "nickname": email2nickname(to_user), }, "permission": permission }) send_perm_audit_msg('add-repo-perm', username, to_user, repo_id, path, permission) except SearpcError as e: logger.error(e) failed.append(to_user) continue if share_type == 'group': group_ids = request.data.getlist('group_id') for gid in group_ids: try: gid = int(gid) except ValueError: return api_error(status.HTTP_400_BAD_REQUEST, 'group_id %s invalid.' % gid) group = seaserv.get_group(gid) if not group: return api_error(status.HTTP_404_NOT_FOUND, 'Group %s not found' % gid) if not check_user_share_quota( username, shared_repo, groups=[group]): return api_error(status.HTTP_403_FORBIDDEN, 'Not enough quota.') try: if is_org_context(request): org_id = request.user.org.org_id seafile_api.add_org_group_repo(shared_repo.repo_id, org_id, gid, username, permission) else: seafile_api.set_group_repo(shared_repo.repo_id, gid, username, permission) success.append({ "share_type": "group", "group_info": { "id": gid, "name": group.group_name, }, "permission": permission }) send_perm_audit_msg('add-repo-perm', username, gid, repo_id, path, permission) except SearpcError as e: logger.error(e) failed.append(group.group_name) continue return HttpResponse(json.dumps({ "success": success, "failed": failed }), status=200, content_type=json_content_type)