def get(self, request, org_id, email): """Get org user info """ # argument check avatar_size = request.GET.get('avatar_size', AVATAR_DEFAULT_SIZE) # resource check org_id = int(org_id) if not ccnet_api.get_org_by_id(org_id): error_msg = 'Organization %s not found.' % org_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: user = User.objects.get(email=email) except User.DoesNotExist: err_msg = 'User %s not found.' % email return api_error(status.HTTP_404_NOT_FOUND, err_msg) # permission check if not ccnet_api.org_user_exists(org_id, email): err_msg = _('User %s not found in organization.') % email return api_error(status.HTTP_404_NOT_FOUND, err_msg) # get user info user_info = get_user_info(email, org_id) avatar_url, is_default, date_uploaded = api_avatar_url( email, avatar_size) user_info['avatar_url'] = avatar_url return Response(user_info)
def get(self, request, email): avatar_size = request.data.get('avatar_size', 64) try: avatar_size = int(avatar_size) except Exception as e: logger.error(e) error_msg = 'avatar_size invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: User.objects.get(email=email) except User.DoesNotExist: error_msg = 'User %s not found.' % email return api_error(status.HTTP_404_NOT_FOUND, error_msg) user_info = get_user_info(email) # get other detailed info user_info['avatar_url'], _, _ = api_avatar_url(email, avatar_size) try: user_info[ 'storage_usage'] = Workspaces.objects.get_owner_total_storage( owner=email) except Exception as e: logging.error(e) return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Internal Server Error') return Response(user_info)
def get_group_member_info(request, group_id, email, avatar_size=AVATAR_DEFAULT_SIZE): p = Profile.objects.get_profile_by_user(email) if p: login_id = p.login_id if p.login_id else '' else: login_id = '' try: avatar_url, is_default, date_uploaded = api_avatar_url(email, avatar_size) except Exception as e: logger.error(e) avatar_url = get_default_avatar_url() role = 'Member' group = ccnet_api.get_group(int(group_id)) is_admin = bool(ccnet_api.check_group_staff(int(group_id), email)) if email == group.creator_name: role = 'Owner' elif is_admin: role = 'Admin' member_info = { 'group_id': group_id, "name": email2nickname(email), 'email': email, "contact_email": Profile.objects.get_contact_email_by_user(email), "login_id": login_id, "avatar_url": request.build_absolute_uri(avatar_url), "is_admin": is_admin, "role": role, } return member_info
def _get_address_book_group_memeber_info(self, request, group_member_obj, avatar_size): email = group_member_obj.user_name try: avatar_url, is_default, date_uploaded = api_avatar_url( email, avatar_size) except Exception as e: logger.error(e) avatar_url = get_default_avatar_url() group_id = group_member_obj.group_id group = ccnet_api.get_group(group_member_obj.group_id) role = 'Member' is_admin = bool(group_member_obj.is_staff) if email == group.creator_name: role = 'Owner' elif is_admin: role = 'Admin' member_info = { 'group_id': group_id, 'group_name': group.group_name, 'email': email, "name": email2nickname(email), "contact_email": email2contact_email(email), "avatar_url": request.build_absolute_uri(avatar_url), "is_admin": is_admin, "role": role, } return member_info
def _get_address_book_group_memeber_info(self, request, group_member_obj, avatar_size): email = group_member_obj.user_name try: avatar_url, is_default, date_uploaded = api_avatar_url(email, avatar_size) except Exception as e: logger.error(e) avatar_url = get_default_avatar_url() group_id = group_member_obj.group_id group = ccnet_api.get_group(group_member_obj.group_id) role = 'Member' is_admin = bool(group_member_obj.is_staff) if email == group.creator_name: role = 'Owner' elif is_admin: role = 'Admin' member_info = { 'group_id': group_id, 'group_name': group.group_name, 'email': email, "name": email2nickname(email), "contact_email": email2contact_email(email), "avatar_url": request.build_absolute_uri(avatar_url), "is_admin": is_admin, "role": role, } return member_info
def get(self, request, format=None): if not EVENTS_ENABLED: events = None return api_error(status.HTTP_404_NOT_FOUND, 'Events not enabled.') try: page = int(request.GET.get('page', '')) except ValueError: page = 1 try: per_page = int(request.GET.get('per_page', '')) except ValueError: per_page = 25 start = (page - 1) * per_page count = per_page email = request.user.username events = get_user_activities(email, start, count) events_list = [] for e in events: d = dict(op_type=e.op_type) d['repo_id'] = e.repo_id d['repo_name'] = e.repo_name d['obj_type'] = e.obj_type d['commit_id'] = e.commit_id d['path'] = e.path d['name'] = '' if e.path == '/' else os.path.basename(e.path) d['author_email'] = e.op_user d['author_name'] = email2nickname(e.op_user) d['author_contact_email'] = email2contact_email(e.op_user) try: size = int(request.GET.get('size', 36)) except ValueError as e: size = 36 url, is_default, date_uploaded = api_avatar_url(e.op_user, size) d['avatar_url'] = request.build_absolute_uri(url) d['time_relative'] = translate_seahub_time( utc_to_local(e.timestamp)) if e.op_type == 'clean-up-trash': d['days'] = e.days elif e.op_type == 'rename' and e.obj_type == 'repo': d['old_repo_name'] = e.old_repo_name elif e.op_type == 'move' and e.obj_type in ['dir', 'file']: d['old_path'] = e.old_path elif e.op_type == 'rename' and e.obj_type in ['dir', 'file']: d['old_path'] = e.old_path d['old_name'] = os.path.basename(e.old_path) events_list.append(d) ret = {'events': events_list} return Response(ret)
def get_group_member_info(request, group_id, email, avatar_size=AVATAR_DEFAULT_SIZE): p = Profile.objects.get_profile_by_user(email) if p: login_id = p.login_id if p.login_id else '' else: login_id = '' avatar_url, is_default, date_uploaded = api_avatar_url(email, avatar_size) role = 'Member' group = ccnet_api.get_group(int(group_id)) is_admin = bool(ccnet_api.check_group_staff(int(group_id), email)) if email == group.creator_name: role = 'Owner' elif is_admin: role = 'Admin' member_info = { 'group_id': group_id, "name": email2nickname(email), 'email': email, "contact_email": Profile.objects.get_contact_email_by_user(email), "login_id": login_id, "avatar_url": avatar_url, "is_admin": is_admin, "role": role, } return member_info
def get_group_member_info(request, group_id, email, avatar_size=AVATAR_DEFAULT_SIZE): p = Profile.objects.get_profile_by_user(email) if p: login_id = p.login_id if p.login_id else '' else: login_id = '' try: avatar_url, is_default, date_uploaded = api_avatar_url( email, avatar_size) except Exception as e: logger.error(e) avatar_url = get_default_avatar_url() is_admin = seaserv.check_group_staff(group_id, email) member_info = { "name": email2nickname(email), 'email': email, "contact_email": Profile.objects.get_contact_email_by_user(email), "login_id": login_id, "avatar_url": request.build_absolute_uri(avatar_url), "is_admin": is_admin, } return member_info
def get_user_common_info(email, avatar_size=AVATAR_DEFAULT_SIZE): avatar_url, is_default, date_uploaded = api_avatar_url(email, avatar_size) return { "email": email, "name": email2nickname(email), "contact_email": email2contact_email(email), "avatar_url": avatar_url }
def get_user_common_info(email, avatar_size=AVATAR_DEFAULT_SIZE): try: avatar_url, is_default, date_uploaded = api_avatar_url(email, avatar_size) except Exception as e: logger.error(e) avatar_url = get_default_avatar_url() return { "email": email, "name": email2nickname(email), "contact_email": email2contact_email(email), "avatar_url": avatar_url }
def format_searched_user_result(request, users, size): results = [] for email in users: url, is_default, date_uploaded = api_avatar_url(email, size) results.append({ "email": email, "avatar_url": request.build_absolute_uri(url), "name": email2nickname(email), "contact_email": Profile.objects.get_contact_email_by_user(email), }) return results
def format_searched_user_result(request, users, size): results = [] for email in users: url, is_default, date_uploaded = api_avatar_url(email, size) results.append({ "email": email, "avatar_url": url, "name": email2nickname(email), "contact_email": email2contact_email(email), }) return results
def post(self, request): image_file = request.FILES.get('avatar', None) avatar_size = request.data.get('avatar_size', 64) if not image_file: error_msg = 'avatar invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: avatar_size = int(avatar_size) except Exception as e: logger.error(e) error_msg = 'avatar_size invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) (root, ext) = os.path.splitext(image_file.name.lower()) if AVATAR_ALLOWED_FILE_EXTS and ext not in AVATAR_ALLOWED_FILE_EXTS: error_msg = _( "%(ext)s is an invalid file extension. Authorized extensions are : %(valid_exts_list)s" ) % { 'ext': ext, 'valid_exts_list': ", ".join(AVATAR_ALLOWED_FILE_EXTS) } return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if image_file.size > AVATAR_MAX_SIZE: error_msg = _( "Your file is too big (%(size)s), the maximum allowed size is %(max_valid_size)s" ) % { 'size': filesizeformat(image_file.size), 'max_valid_size': filesizeformat(AVATAR_MAX_SIZE) } return api_error(status.HTTP_400_BAD_REQUEST, error_msg) username = request.user.username try: avatar = Avatar.objects.filter(emailuser=username, primary=True).first() avatar = avatar or Avatar(emailuser=username, primary=True) avatar.avatar = image_file avatar.save() avatar_url, is_default, date_uploaded = api_avatar_url( username, int(avatar_size)) 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({'avatar_url': avatar_url})
def post(self, request): image_file = request.FILES.get('avatar', None) avatar_size = request.data.get('avatar_size', 64) if not image_file: error_msg = 'avatar invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: avatar_size = int(avatar_size) except Exception as e: logger.error(e) error_msg = 'avatar_size invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) (root, ext) = os.path.splitext(image_file.name.lower()) if AVATAR_ALLOWED_FILE_EXTS and ext not in AVATAR_ALLOWED_FILE_EXTS: error_msg = _(u"%(ext)s is an invalid file extension. Authorized extensions are : %(valid_exts_list)s") % {'ext' : ext, 'valid_exts_list' : ", ".join(AVATAR_ALLOWED_FILE_EXTS)} return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if image_file.size > AVATAR_MAX_SIZE: error_msg = _(u"Your file is too big (%(size)s), the maximum allowed size is %(max_valid_size)s") % { 'size' : filesizeformat(image_file.size), 'max_valid_size' : filesizeformat(AVATAR_MAX_SIZE)} return api_error(status.HTTP_400_BAD_REQUEST, error_msg) username = request.user.username count = Avatar.objects.filter(emailuser=username).count() if AVATAR_MAX_AVATARS_PER_USER > 1 and count >= AVATAR_MAX_AVATARS_PER_USER: error_msg = _(u"You already have %(nb_avatars)d avatars, and the maximum allowed is %(nb_max_avatars)d.") % { 'nb_avatars' : count, 'nb_max_avatars' : AVATAR_MAX_AVATARS_PER_USER} return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: avatar = Avatar( emailuser = username, primary = True, ) avatar.avatar.save(image_file.name, image_file) avatar.save() avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar) avatar_url, is_default, date_uploaded = api_avatar_url(username, int(avatar_size)) 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({'avatar_url': request.build_absolute_uri(avatar_url)})
def get_file_history_info(commit, avatar_size): info = {} creator_name = commit.creator_name url, is_default, date_uploaded = api_avatar_url(creator_name, avatar_size) info['creator_avatar_url'] = url info['creator_email'] = creator_name info['creator_name'] = email2nickname(creator_name) info['creator_contact_email'] = email2contact_email(creator_name) info['ctime'] = timestamp_to_isoformat_timestr(commit.ctime) info['description'] = commit.desc info['commit_id'] = commit.id info['size'] = commit.rev_file_size info['rev_file_id'] = commit.rev_file_id info['rev_renamed_old_path'] = commit.rev_renamed_old_path return info
def get_user_common_info(email, avatar_size=AVATAR_DEFAULT_SIZE): try: avatar_url, is_default, date_uploaded = api_avatar_url(email, avatar_size) except Exception as e: logger.error(e) avatar_url = get_default_avatar_url() p = Profile.objects.get_profile_by_user(email) if p: login_id = p.login_id if p.login_id else '' else: login_id = '' return { "email": email, "name": email2nickname(email), "avatar_url": avatar_url, "login_id": login_id }
def get_new_file_history_info(ent, avatar_size): info = {} creator_name = ent.op_user url, is_default, date_uploaded = api_avatar_url(creator_name, avatar_size) info['creator_avatar_url'] = url info['creator_email'] = creator_name info['creator_name'] = email2nickname(creator_name) info['creator_contact_email'] = email2contact_email(creator_name) info['op_type'] = ent.op_type info['ctime'] = utc_datetime_to_isoformat_timestr(ent.timestamp) info['commit_id'] = ent.commit_id info['size'] = ent.size info['rev_file_id'] = ent.file_id info['old_path'] = ent.old_path if hasattr(ent, 'old_path') else '' info['path'] = ent.path return info
def get(self, request, email): avatar_size = request.data.get('avatar_size', 64) try: avatar_size = int(avatar_size) except Exception as e: logger.error(e) error_msg = 'avatar_size invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: User.objects.get(email=email) except User.DoesNotExist: error_msg = 'User %s not found.' % email return api_error(status.HTTP_404_NOT_FOUND, error_msg) user_info = get_user_info(email) user_info['avatar_url'], _, _ = api_avatar_url(email, avatar_size) return Response(user_info)
def list_user_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_to( org_id, repo_owner, repo_id) else: share_items = seafile_api.get_org_shared_users_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_to( repo_owner, repo_id) else: share_items = seafile_api.get_shared_users_for_subdir( repo_id, path, repo_owner) # change is_admin to True if user is repo admin. admin_users = ExtraSharePermission.objects.get_admin_users_by_repo( repo_id) ret = [] for item in share_items: avatar_url, is_default, date_uploaded = api_avatar_url( item.user, 72) ret.append({ "share_type": "user", "user_info": { "name": item.user, "nickname": email2nickname(item.user), "contact_email": email2contact_email(item.user), "avatar_url": avatar_url, }, "permission": item.perm, "is_admin": item.user in admin_users }) return ret
def _get_account_info(self, request): info = {} email = request.user.username p = Profile.objects.get_profile_by_user(email) if is_org_context(request): org_id = request.user.org.org_id is_org_staff = request.user.org.is_staff info['is_org_staff'] = is_org_staff else: quota_total = request.user.permissions.role_asset_quota() quota_total = get_quota_from_string( quota_total) if quota_total else -2 quota_usage = Workspaces.objects.get_owner_total_storage( request.user.username) if quota_total is not None and quota_total > 0: info['space_usage'] = str( float(quota_usage) / quota_total * 100) + '%' else: # no space quota set in config info['space_usage'] = '0%' info['total'] = quota_total info['usage'] = quota_usage url, _, _ = api_avatar_url(email, int(72)) info['avatar_url'] = url info['email'] = email info['name'] = email2nickname(email) info['login_id'] = p.login_id if p and p.login_id else "" info['contact_email'] = p.contact_email if p else "" info['institution'] = p.institution if p and p.institution else "" info['is_staff'] = request.user.is_staff if getattr(settings, 'MULTI_INSTITUTION', False): info['is_inst_admin'] = request.user.inst_admin interval = UserOptions.objects.get_dtable_updates_email_interval(email) info[ 'email_notification_interval'] = 0 if interval is None else interval return info
def get_group_member_info(request, group_id, email, avatar_size=AVATAR_DEFAULT_SIZE): p = Profile.objects.get_profile_by_user(email) if p: login_id = p.login_id if p.login_id else '' else: login_id = '' try: avatar_url, is_default, date_uploaded = api_avatar_url(email, avatar_size) except Exception as e: logger.error(e) avatar_url = get_default_avatar_url() is_admin = seaserv.check_group_staff(group_id, email) member_info = { "name": email2nickname(email), 'email': email, "contact_email": Profile.objects.get_contact_email_by_user(email), "login_id": login_id, "avatar_url": request.build_absolute_uri(avatar_url), "is_admin": is_admin, } return member_info
def post(self, request): image_file = request.FILES.get('avatar', None) avatar_size = request.data.get('avatar_size', 64) if not image_file: error_msg = 'avatar invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: avatar_size = int(avatar_size) except Exception as e: logger.error(e) error_msg = 'avatar_size invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) (root, ext) = os.path.splitext(image_file.name.lower()) if AVATAR_ALLOWED_FILE_EXTS and ext not in AVATAR_ALLOWED_FILE_EXTS: error_msg = _( u"%(ext)s is an invalid file extension. Authorized extensions are : %(valid_exts_list)s" ) % { 'ext': ext, 'valid_exts_list': ", ".join(AVATAR_ALLOWED_FILE_EXTS) } return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if image_file.size > AVATAR_MAX_SIZE: error_msg = _( u"Your file is too big (%(size)s), the maximum allowed size is %(max_valid_size)s" ) % { 'size': filesizeformat(image_file.size), 'max_valid_size': filesizeformat(AVATAR_MAX_SIZE) } return api_error(status.HTTP_400_BAD_REQUEST, error_msg) username = request.user.username count = Avatar.objects.filter(emailuser=username).count() if AVATAR_MAX_AVATARS_PER_USER > 1 and count >= AVATAR_MAX_AVATARS_PER_USER: error_msg = _( u"You already have %(nb_avatars)d avatars, and the maximum allowed is %(nb_max_avatars)d." ) % { 'nb_avatars': count, 'nb_max_avatars': AVATAR_MAX_AVATARS_PER_USER } return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: avatar = Avatar( emailuser=username, primary=True, ) avatar.avatar.save(image_file.name, image_file) avatar.save() avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar) avatar_url, is_default, date_uploaded = api_avatar_url( username, int(avatar_size)) 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({'avatar_url': request.build_absolute_uri(avatar_url)})
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 repo.encrypted and path != '/': return api_error(status.HTTP_400_BAD_REQUEST, 'Folder invalid.') 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.') repo_owner = self.get_repo_owner(request, repo_id) if repo_owner != username and not is_repo_admin(username, repo_id): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') permission = request.data.get('permission', PERMISSION_READ) if permission not in get_available_repo_perms(): return api_error(status.HTTP_400_BAD_REQUEST, 'permission invalid.') result = {} result['failed'] = [] result['success'] = [] 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): result['failed'].append({ 'email': to_user, 'error_msg': _('username invalid.') }) continue try: User.objects.get(email=to_user) except User.DoesNotExist: result['failed'].append({ 'email': to_user, 'error_msg': _('User %s not found.') % to_user }) continue if self.has_shared_to_user(request, repo_id, path, to_user): result['failed'].append({ 'email': to_user, 'error_msg': _('This item has been shared to %s.') % email2nickname(to_user) }) continue try: org_id = None if is_org_context(request): org_id = request.user.org.org_id if not is_org_user(to_user, int(org_id)): org_name = request.user.org.org_name error_msg = 'User %s is not member of organization %s.' \ % (to_user, org_name) result['failed'].append({ 'email': to_user, 'error_msg': error_msg }) continue # 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) # can't share to owner if to_user == repo_owner: error_msg = "Library can not be shared to owner" return api_error(status.HTTP_400_BAD_REQUEST, error_msg) share_dir_to_user(repo, path, repo_owner, username, to_user, permission, org_id) else: if is_org_user(to_user): error_msg = 'User %s is a member of organization.' % to_user result['failed'].append({ 'email': to_user, 'error_msg': error_msg }) continue repo_owner = seafile_api.get_repo_owner(repo_id) # can't share to owner if to_user == repo_owner: error_msg = "Library can not be shared to owner" return api_error(status.HTTP_400_BAD_REQUEST, error_msg) share_dir_to_user(repo, path, repo_owner, username, to_user, permission, None) avatar_url, is_default, date_uploaded = api_avatar_url( to_user, 72) result['success'].append({ "share_type": "user", "user_info": { "name": to_user, "nickname": email2nickname(to_user), "contact_email": email2contact_email(to_user), "avatar_url": avatar_url, }, "permission": PERMISSION_READ_WRITE if permission == PERMISSION_ADMIN else permission, "is_admin": permission == PERMISSION_ADMIN }) # send a signal when sharing repo successful share_repo_to_user_successful.send(sender=None, from_user=username, to_user=to_user, repo=repo, path=path, org_id=org_id) send_perm_audit_msg('add-repo-perm', username, to_user, repo_id, path, permission) except SearpcError as e: logger.error(e) result['failed'].append({ 'email': to_user, 'error_msg': 'Internal Server Error' }) continue if share_type == 'group': group_ids = request.data.getlist('group_id') for gid in group_ids: try: gid = int(gid) except ValueError: result['failed'].append( {'error_msg': 'group_id %s invalid.' % gid}) continue group = ccnet_api.get_group(gid) if not group: result['failed'].append( {'error_msg': 'Group %s not found' % gid}) continue if not config.ENABLE_SHARE_TO_ALL_GROUPS and \ not is_group_member(gid, username): result['failed'].append({ 'group_name': group.group_name, 'error_msg': 'Permission denied.' }) continue if self.has_shared_to_group(request, repo_id, path, gid): result['failed'].append({ 'group_name': group.group_name, 'error_msg': _('This item has been shared to %s.') % group.group_name }) continue try: org_id = None 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 share_dir_to_group(repo, path, repo_owner, username, gid, permission, org_id) else: repo_owner = seafile_api.get_repo_owner(repo_id) share_dir_to_group(repo, path, repo_owner, username, gid, permission, None) result['success'].append({ "share_type": "group", "group_info": { "id": gid, "name": group.group_name, }, "permission": PERMISSION_READ_WRITE if permission == PERMISSION_ADMIN else permission, "is_admin": permission == PERMISSION_ADMIN }) share_repo_to_group_successful.send(sender=None, from_user=username, group_id=gid, repo=repo, path=path, org_id=org_id) send_perm_audit_msg('add-repo-perm', username, gid, repo_id, path, permission) except SearpcError as e: logger.error(e) result['failed'].append({ 'group_name': group.group_name, 'error_msg': 'Internal Server Error' }) continue return HttpResponse(json.dumps(result), status=200, content_type=json_content_type)
def get(self, request, format=None): if not EVENTS_ENABLED: events = None return api_error(status.HTTP_404_NOT_FOUND, 'Events not enabled.') try: page = int(request.GET.get('page', '')) except ValueError: page = 1 try: per_page = int(request.GET.get('per_page', '')) except ValueError: per_page = 25 start = (page - 1) * per_page count = per_page email = request.user.username try: events = get_user_activities(email, start, count) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) events_list = [] for e in events: d = dict(op_type=e.op_type) d['repo_id'] = e.repo_id d['repo_name'] = e.repo_name d['obj_type'] = e.obj_type d['commit_id'] = e.commit_id d['path'] = e.path d['name'] = '' if e.path == '/' else os.path.basename(e.path) d['author_email'] = e.op_user d['author_name'] = email2nickname(e.op_user) d['author_contact_email'] = email2contact_email(e.op_user) try: avatar_size = int(request.GET.get('avatar_size', 72)) except ValueError as e: avatar_size = 72 url, is_default, date_uploaded = api_avatar_url(e.op_user, avatar_size) d['avatar_url'] = request.build_absolute_uri(url) d['time'] = utc_datetime_to_isoformat_timestr(e.timestamp) if e.op_type == 'clean-up-trash': d['days'] = e.days elif e.op_type == 'rename' and e.obj_type == 'repo': d['old_repo_name'] = e.old_repo_name elif e.op_type == 'move' and e.obj_type in ['dir', 'file']: d['old_path'] = e.old_path elif e.op_type == 'rename' and e.obj_type in ['dir', 'file']: d['old_path'] = e.old_path d['old_name'] = os.path.basename(e.old_path) elif e.op_type == 'publish': d['old_path'] = e.old_path elif d['name'].endswith('(draft).md'): if e.op_type in ('create', 'edit') and e.obj_type == 'file': try: draft = Draft.objects.filter(username=e.op_user, origin_repo_id=e.repo_id, draft_file_path=e.path) if draft: draft = draft[0] d['draft_id'] = draft.id else: Draft.DoesNotExist except Draft.DoesNotExist: pass events_list.append(d) ret = { 'events': events_list } return Response(ret)
def get(self, request): """ Return file info. """ # argument check doc_id = request.GET.get('doc_id', '') if not doc_id: error_msg = 'doc_id invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) file_info = cache.get('BISHENG_OFFICE_' + doc_id) if not file_info: error_msg = 'doc_id invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) username = file_info.get('username') if not username: error_msg = 'username invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) repo_id = file_info.get('repo_id') if not repo_id: error_msg = 'repo_id invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) file_path = file_info.get('file_path') if not file_path: error_msg = 'file_path invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) file_path = normalize_file_path(file_path) # resource check try: User.objects.get(email=username) except User.DoesNotExist: error_msg = 'User %s not found.' % username return api_error(status.HTTP_404_NOT_FOUND, error_msg) if not seafile_api.get_repo(repo_id): error_msg = 'Library %s not found.' % repo_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) if not seafile_api.get_file_id_by_path(repo_id, file_path): error_msg = 'File %s not found.' % file_path return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check parent_dir = os.path.dirname(file_path) permission = seafile_api.check_permission_by_path(repo_id, parent_dir, username) if not permission: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # get file basic info file_name = os.path.basename(file_path.rstrip('/')) filetype, fileext = get_file_type_and_ext(file_name) # get file raw url file_id = seafile_api.get_file_id_by_path(repo_id, file_path) download_token = seafile_api.get_fileserver_access_token(repo_id, file_id, 'download', username, use_onetime=True) raw_url = gen_file_get_url(download_token, file_name) # get avatar url url, _, _ = api_avatar_url(username, int(72)) # prepare file permission privilege = copy.deepcopy(BISHENG_OFFICE_PRIVILEGE) can_edit = file_info.get('can_edit', False) if not can_edit: privilege.remove('FILE_WRITE') # prepare response file_info = { 'doc': { 'docId': doc_id, 'title': file_name, 'mime_type': BISHENG_OFFICE_MIME_TYPE[fileext], 'fetchUrl': raw_url, 'thumbnail': "", 'fromApi': True }, 'user': { 'uid': username, 'oid': username, 'nickName': email2nickname(username), 'avatar': request.build_absolute_uri(url), 'privilege': privilege }, } return Response(file_info)
def get(self, request): if not DTABLE_EVENTS_ENABLED: return api_error(status.HTTP_400_BAD_REQUEST, 'Events not enabled.') try: page = int(request.GET.get('page', '')) except ValueError: page = 1 try: per_page = int(request.GET.get('per_page', '')) except ValueError: per_page = 25 start = (page - 1) * per_page count = per_page username = request.user.username try: activity_list = get_user_activities(username, start, count) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) dtable_uuid_name_map = dict() dtable_uuid_list = list() for activity in activity_list: if activity.dtable_uuid not in dtable_uuid_name_map: dtable_uuid_list.append(activity.dtable_uuid) if dtable_uuid_list: dtables = DTables.objects.filter(uuid__in=dtable_uuid_list, deleted=False) for dtable in dtables: dtable_uuid_name_map[dtable.uuid.hex] = dtable.name activities = [] for activity in activity_list: activity_dict = dict(dtable_uuid=activity.dtable_uuid) activity_dict['dtable_name'] = dtable_uuid_name_map[activity.dtable_uuid] if activity.dtable_uuid in dtable_uuid_name_map else '' activity_dict['row_id'] = activity.row_id activity_dict['op_type'] = activity.op_type activity_dict['author_email'] = activity.op_user activity_dict['author_name'] = email2nickname(activity.op_user) activity_dict['author_contact_email'] = email2contact_email(activity.op_user) activity_dict['op_time'] = utc_datetime_to_isoformat_timestr(activity.op_time) activity_dict['table_id'] = activity.table_id activity_dict['table_name'] = activity.table_name activity_dict['row_name'] = getattr(activity, "row_name", "") # compatible with previous data activity_dict['row_data'] = activity.row_data activity_dict['op_app'] = activity.op_app try: avatar_size = int(request.GET.get('avatar_size', 72)) except ValueError: avatar_size = 72 url, is_default, date_uploaded = api_avatar_url(activity.op_user, avatar_size) activity_dict['avatar_url'] = url if activity_dict['op_app']: activity_dict['app_avatar_url'] = api_app_avatar_url()[0] activities.append(activity_dict) return Response({'activities': activities})
def update_notice_detail(request, notices): repo_dict = {} for notice in notices: if notice.is_repo_share_msg(): try: d = json.loads(notice.detail) repo_id = d['repo_id'] path = d.get('path', '/') org_id = d.get('org_id', None) if path == '/': repo = seafile_api.get_repo(repo_id) else: if org_id: owner = seafile_api.get_org_repo_owner(repo_id) repo = seafile_api.get_org_virtual_repo( org_id, repo_id, path, owner) else: owner = seafile_api.get_repo_owner(repo_id) repo = seafile_api.get_virtual_repo( repo_id, path, owner) if repo is None: notice.detail = None else: d.pop('org_id') share_from_user_email = d.pop('share_from') url, is_default, date_uploaded = api_avatar_url( share_from_user_email, 32) d['repo_name'] = repo.name d['repo_id'] = repo.id d['share_from_user_name'] = email2nickname( share_from_user_email) d['share_from_user_email'] = share_from_user_email d['share_from_user_contact_email'] = email2contact_email( share_from_user_email) d['share_from_user_avatar_url'] = request.build_absolute_uri( url) notice.detail = d except Exception as e: logger.error(e) elif notice.is_repo_share_to_group_msg(): try: d = json.loads(notice.detail) group_id = d['group_id'] path = d.get('path', '/') org_id = d.get('org_id', None) repo_id = d['repo_id'] group = ccnet_api.get_group(group_id) if path == '/': repo = seafile_api.get_repo(repo_id) else: if org_id: owner = seafile_api.get_org_repo_owner(repo_id) repo = seafile_api.get_org_virtual_repo( org_id, repo_id, path, owner) else: owner = seafile_api.get_repo_owner(repo_id) repo = seafile_api.get_virtual_repo( repo_id, path, owner) if not repo or not group: notice.detail = None else: d.pop('org_id') share_from_user_email = d.pop('share_from') url, is_default, date_uploaded = api_avatar_url( share_from_user_email, 32) d['share_from_user_name'] = email2nickname( share_from_user_email) d['share_from_user_email'] = share_from_user_email d['share_from_user_contact_email'] = email2contact_email( share_from_user_email) d['share_from_user_avatar_url'] = request.build_absolute_uri( url) d['repo_name'] = repo.name d['repo_id'] = repo.id d['group_name'] = group.group_name notice.detail = d except Exception as e: logger.error(e) elif notice.is_add_user_to_group(): try: d = json.loads(notice.detail) group_id = d['group_id'] group = ccnet_api.get_group(group_id) if group is None: notice.detail = None else: group_staff_email = d.pop('group_staff') url, is_default, date_uploaded = api_avatar_url( group_staff_email, 32) d['group_staff_name'] = email2nickname(group_staff_email) d['group_staff_email'] = group_staff_email d['group_staff_contact_email'] = email2contact_email( group_staff_email) d['group_staff_avatar_url'] = request.build_absolute_uri( url) d['group_name'] = group.group_name notice.detail = d except Exception as e: logger.error(e) elif notice.is_draft_comment_msg(): try: d = json.loads(notice.detail) author_email = d.pop('author') url, is_default, date_uploaded = api_avatar_url( author_email, 32) d['author_name'] = email2nickname(author_email) d['author_email'] = author_email d['author_context_email'] = email2contact_email(author_email) d['author_avatar_url'] = request.build_absolute_uri(url) notice.detail = d except Exception as e: logger.error(e) elif notice.is_repo_transfer_msg(): try: d = json.loads(notice.detail) repo_id = d['repo_id'] repo = seafile_api.get_repo(repo_id) if not repo: notice.detail = None else: d.pop('org_id') repo_owner_email = d.pop('repo_owner') d['transfer_from_user_name'] = email2nickname( repo_owner_email) d['transfer_from_user_email'] = repo_owner_email d['transfer_from_user_contact_email'] = email2contact_email( repo_owner_email) url, is_default, date_uploaded = api_avatar_url( repo_owner_email, 32) d['transfer_from_user_avatar_url'] = request.build_absolute_uri( url) notice.detail = d except Exception as e: logger.error(e) elif notice.is_draft_reviewer_msg(): try: d = json.loads(notice.detail) d.pop('to_user') request_user_email = d.pop('from_user') url, is_default, date_uploaded = api_avatar_url( request_user_email, 32) d['request_user_name'] = email2nickname(request_user_email) d['request_user_email'] = request_user_email d['request_user_contact_email'] = email2contact_email( request_user_email) d['request_user_avatat_url'] = request.build_absolute_uri(url) notice.detail = d except Exception as e: logger.error(e) elif notice.is_file_uploaded_msg(): try: d = json.loads(notice.detail) filename = d['file_name'] repo_id = d['repo_id'] if repo_id in repo_dict: repo = repo_dict[repo_id] else: repo = seafile_api.get_repo(repo_id) repo_dict[repo_id] = repo if repo: if d['uploaded_to'] == '/': # current upload path is '/' file_path = '/' + filename name = repo.name else: uploaded_to = d['uploaded_to'].rstrip('/') file_path = uploaded_to + '/' + filename name = os.path.basename(uploaded_to) d['repo_name'] = repo.name d['folder_path'] = d.pop('uploaded_to') d['folder_name'] = name d['file_path'] = file_path url, is_default, date_uploaded = api_avatar_url('', 32) d['uploaded_user_avatar_url'] = request.build_absolute_uri( url) notice.detail = d else: notice.detail = None except Exception as e: logger.error(e) elif notice.is_file_comment_msg(): try: d = json.loads(notice.detail) repo_id = d['repo_id'] file_path = d['file_path'] if repo_id in repo_dict: repo = repo_dict[repo_id] else: repo = seafile_api.get_repo(repo_id) repo_dict[repo_id] = repo if repo is None or not seafile_api.get_file_id_by_path( repo.id, file_path): notice.detail = None else: author_email = d.pop('author') file_name = os.path.basename(file_path) url, is_default, date_uploaded = api_avatar_url( author_email, 32) d['author_avatar_url'] = request.build_absolute_uri(url) d['author_name'] = email2nickname(author_email) d['author_email'] = author_email d['author_contact_email'] = email2contact_email( author_email) d['file_name'] = file_name notice.detail = d except Exception as e: logger.error(e) return notices
def update_notice_detail(request, notices): for notice in notices: # if need to update this func, command-line's code perhaps # needs to be updated, work-weixin-send-notices, email-send-notices, etc... if notice.is_add_user_to_group_msg(): try: d = json.loads(notice.detail) group_id = d['group_id'] group = ccnet_api.get_group(group_id) if group is None: notice.detail = None else: group_staff_email = d.pop('group_staff') url, is_default, date_uploaded = api_avatar_url( group_staff_email, 72) d['group_staff_name'] = email2nickname(group_staff_email) d['group_staff_email'] = group_staff_email d['group_staff_contact_email'] = email2contact_email( group_staff_email) d['group_staff_avatar_url'] = url d['group_name'] = group.group_name notice.detail = d except Exception as e: logger.error(e) elif notice.is_share_dtable_to_user_msg(): try: d = json.loads(notice.detail) table_id = d.pop('table_id') share_from = d.pop('share_user') dtable = DTables.objects.filter(id=table_id).first() if not dtable: notice.detail = None continue # resource check workspace = Workspaces.objects.get_workspace_by_id( dtable.workspace_id) if not workspace: notice.detail = None continue repo_id = workspace.repo_id repo = seafile_api.get_repo(repo_id) if not repo: notice.detail = None continue if repo.status != 0: notice.detail = None continue d['dtable'] = { 'id': dtable.id, 'workspace_id': dtable.workspace_id, 'uuid': dtable.uuid, 'name': dtable.name, } url, is_default, date_uploaded = api_avatar_url(share_from, 72) d['share_from'] = { 'share_from_user_name': email2nickname(share_from), 'share_from_user_email': share_from, 'share_from_user_avatar_url': url, } notice.detail = d except Exception as e: logger.error(e) elif notice.is_submit_form_msg(): try: detail = json.loads(notice.detail) dtable_id = detail.pop('dtable_id') table_id = detail.pop('table_id') form_name = detail.pop('form_name') submit_user = detail.pop('submit_user') dtable = DTables.objects.filter(id=dtable_id).first() if not dtable: notice.detail = None continue # resource check workspace = Workspaces.objects.get_workspace_by_id( dtable.workspace_id) if not workspace: notice.detail = None continue detail['form'] = { 'id': dtable.id, 'workspace_id': dtable.workspace_id, 'uuid': dtable.uuid, 'name': dtable.name, 'table_id': table_id, 'form_name': form_name, } url, is_default, date_uploaded = api_avatar_url( submit_user, 72) detail['submit_user'] = { 'submit_user_name': email2nickname(submit_user), 'submit_user_email': submit_user, 'submit_user_avatar_url': url, } notice.detail = detail except Exception as e: logger.error(e) return notices
def base(request): """ Add seahub base configure to the context. """ try: org = request.user.org except AttributeError: org = None # extra repo id from request path, use in search repo_id_patt = r".*/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})/.*" m = re.match(repo_id_patt, request.get_full_path()) search_repo_id = m.group(1) if m is not None else None file_server_root = config.FILE_SERVER_ROOT if not file_server_root.endswith('/'): file_server_root += '/' logo_path = LOGO_PATH favicon_path = FAVICON_PATH login_bg_path = LOGIN_BG_IMAGE_PATH # filter ajax/api request out avatar_url = '' username = request.user.username if (not request.is_ajax()) and ("api2/" not in request.path) and \ ("api/v2.1/" not in request.path): # get logo path custom_logo_file = os.path.join(MEDIA_ROOT, CUSTOM_LOGO_PATH) if os.path.exists(custom_logo_file): logo_path = CUSTOM_LOGO_PATH # get favicon path custom_favicon_file = os.path.join(MEDIA_ROOT, CUSTOM_FAVICON_PATH) if os.path.exists(custom_favicon_file): favicon_path = CUSTOM_FAVICON_PATH # get login bg path custom_login_bg_file = os.path.join(MEDIA_ROOT, CUSTOM_LOGIN_BG_PATH) if os.path.exists(custom_login_bg_file): login_bg_path = CUSTOM_LOGIN_BG_PATH avatar_url, is_default, date_uploaded = api_avatar_url(username, 72) result = { 'seafile_version': SEAFILE_VERSION, 'site_title': config.SITE_TITLE, 'branding_css': BRANDING_CSS, 'enable_branding_css': config.ENABLE_BRANDING_CSS, 'favicon_path': favicon_path, 'login_bg_path': login_bg_path, 'logo_path': logo_path, 'logo_width': LOGO_WIDTH, 'logo_height': LOGO_HEIGHT, 'cloud_mode': request.cloud_mode, 'org': org, 'site_name': get_site_name(), 'enable_signup': config.ENABLE_SIGNUP, 'max_file_name': MAX_FILE_NAME, 'has_file_search': HAS_FILE_SEARCH, 'show_repo_download_button': SHOW_REPO_DOWNLOAD_BUTTON, 'share_link_password_min_length': config.SHARE_LINK_PASSWORD_MIN_LENGTH, 'repo_password_min_length': config.REPO_PASSWORD_MIN_LENGTH, 'events_enabled': EVENTS_ENABLED, 'sysadmin_extra_enabled': ENABLE_SYSADMIN_EXTRA, 'multi_tenancy': MULTI_TENANCY, 'multi_institution': getattr(dj_settings, 'MULTI_INSTITUTION', False), 'search_repo_id': search_repo_id, 'SITE_ROOT': SITE_ROOT, 'CSRF_COOKIE_NAME': dj_settings.CSRF_COOKIE_NAME, 'constance_enabled': dj_settings.CONSTANCE_ENABLED, 'FILE_SERVER_ROOT': file_server_root, 'LOGIN_URL': dj_settings.LOGIN_URL, 'enable_thumbnail': ENABLE_THUMBNAIL, 'thumbnail_size_for_original': THUMBNAIL_SIZE_FOR_ORIGINAL, 'enable_guest_invitation': ENABLE_GUEST_INVITATION, 'enable_terms_and_conditions': config.ENABLE_TERMS_AND_CONDITIONS, 'show_logout_icon': SHOW_LOGOUT_ICON, 'is_pro': True if is_pro_version() else False, 'is_docs': ENABLE_SEAFILE_DOCS, 'enable_upload_folder': dj_settings.ENABLE_UPLOAD_FOLDER, 'enable_resumable_fileupload': dj_settings.ENABLE_RESUMABLE_FILEUPLOAD, 'service_url': get_service_url().rstrip('/'), 'enable_file_scan': ENABLE_FILE_SCAN, 'enable_work_weixin': ENABLE_WORK_WEIXIN, 'avatar_url': avatar_url if avatar_url else '', } if request.user.is_staff: result['is_default_admin'] = request.user.admin_role == DEFAULT_ADMIN result[ 'enable_share_link_report_abuse'] = ENABLE_SHARE_LINK_REPORT_ABUSE return result
def update_notice_detail(request, notices): repo_dict = {} for notice in notices: if notice.is_repo_share_msg(): try: d = json.loads(notice.detail) repo_id = d['repo_id'] path = d.get('path', '/') org_id = d.get('org_id', None) if path == '/': repo = seafile_api.get_repo(repo_id) else: if org_id: owner = seafile_api.get_org_repo_owner(repo_id) repo = seafile_api.get_org_virtual_repo( org_id, repo_id, path, owner) else: owner = seafile_api.get_repo_owner(repo_id) repo = seafile_api.get_virtual_repo(repo_id, path, owner) if repo is None: notice.detail = None else: d.pop('org_id') share_from_user_email = d.pop('share_from') url, is_default, date_uploaded = api_avatar_url(share_from_user_email, 32) d['repo_name'] = repo.name d['repo_id'] = repo.id d['share_from_user_name'] = email2nickname(share_from_user_email) d['share_from_user_email'] = share_from_user_email d['share_from_user_contact_email'] = email2contact_email(share_from_user_email) d['share_from_user_avatar_url'] = request.build_absolute_uri(url) notice.detail = d except Exception as e: logger.error(e) elif notice.is_repo_share_to_group_msg(): try: d = json.loads(notice.detail) group_id = d['group_id'] path = d.get('path', '/') org_id = d.get('org_id', None) repo_id = d['repo_id'] group = ccnet_api.get_group(group_id) if path == '/': repo = seafile_api.get_repo(repo_id) else: if org_id: owner = seafile_api.get_org_repo_owner(repo_id) repo = seafile_api.get_org_virtual_repo( org_id, repo_id, path, owner) else: owner = seafile_api.get_repo_owner(repo_id) repo = seafile_api.get_virtual_repo(repo_id, path, owner) if not repo or not group: notice.detail = None else: d.pop('org_id') share_from_user_email = d.pop('share_from') url, is_default, date_uploaded = api_avatar_url(share_from_user_email, 32) d['share_from_user_name'] = email2nickname(share_from_user_email) d['share_from_user_email'] = share_from_user_email d['share_from_user_contact_email'] = email2contact_email(share_from_user_email) d['share_from_user_avatar_url'] = request.build_absolute_uri(url) d['repo_name'] = repo.name d['repo_id'] = repo.id d['group_name'] = group.group_name notice.detail = d except Exception as e: logger.error(e) elif notice.is_add_user_to_group(): try: d = json.loads(notice.detail) group_id = d['group_id'] group = ccnet_api.get_group(group_id) if group is None: notice.detail = None else: group_staff_email = d.pop('group_staff') url, is_default, date_uploaded = api_avatar_url(group_staff_email, 32) d['group_staff_name'] = email2nickname(group_staff_email) d['group_staff_email'] = group_staff_email d['group_staff_contact_email'] = email2contact_email(group_staff_email) d['group_staff_avatar_url'] = request.build_absolute_uri(url) d['group_name'] = group.group_name notice.detail = d except Exception as e: logger.error(e) elif notice.is_draft_comment_msg(): try: d = json.loads(notice.detail) author_email = d.pop('author') url, is_default, date_uploaded = api_avatar_url(author_email, 32) d['author_name'] = email2nickname(author_email) d['author_email'] = author_email d['author_context_email'] = email2contact_email(author_email) d['author_avatar_url'] = request.build_absolute_uri(url) notice.detail = d except Exception as e: logger.error(e) elif notice.is_repo_transfer_msg(): try: d = json.loads(notice.detail) repo_id = d['repo_id'] repo = seafile_api.get_repo(repo_id) if not repo: notice.detail = None else: d.pop('org_id') repo_owner_email = d.pop('repo_owner') d['transfer_from_user_name'] = email2nickname(repo_owner_email) d['transfer_from_user_email'] = repo_owner_email d['transfer_from_user_contact_email'] = email2contact_email(repo_owner_email) url, is_default, date_uploaded = api_avatar_url(repo_owner_email, 32) d['transfer_from_user_avatar_url'] = request.build_absolute_uri(url) notice.detail = d except Exception as e: logger.error(e) elif notice.is_draft_reviewer_msg(): try: d = json.loads(notice.detail) d.pop('to_user') request_user_email = d.pop('from_user') url, is_default, date_uploaded = api_avatar_url(request_user_email, 32) d['request_user_name'] = email2nickname(request_user_email) d['request_user_email'] = request_user_email d['request_user_contact_email'] = email2contact_email(request_user_email) d['request_user_avatat_url'] = request.build_absolute_uri(url) notice.detail = d except Exception as e: logger.error(e) elif notice.is_file_uploaded_msg(): try: d = json.loads(notice.detail) filename = d['file_name'] repo_id = d['repo_id'] if repo_id in repo_dict: repo = repo_dict[repo_id] else: repo = seafile_api.get_repo(repo_id) repo_dict[repo_id] = repo if repo: if d['uploaded_to'] == '/': # current upload path is '/' file_path = '/' + filename name = repo.name else: uploaded_to = d['uploaded_to'].rstrip('/') file_path = uploaded_to + '/' + filename name = os.path.basename(uploaded_to) d['repo_name'] = repo.name d['folder_path'] = d.pop('uploaded_to') d['folder_name'] = name d['file_path'] = file_path url, is_default, date_uploaded = api_avatar_url('', 32) d['uploaded_user_avatar_url'] = request.build_absolute_uri(url) notice.detail = d else: notice.detail = None except Exception as e: logger.error(e) elif notice.is_file_comment_msg(): try: d = json.loads(notice.detail) repo_id = d['repo_id'] file_path = d['file_path'] if repo_id in repo_dict: repo = repo_dict[repo_id] else: repo = seafile_api.get_repo(repo_id) repo_dict[repo_id] = repo if repo is None or not seafile_api.get_file_id_by_path(repo.id, file_path): notice.detail = None else: author_email = d.pop('author') file_name = os.path.basename(file_path) url, is_default, date_uploaded = api_avatar_url(author_email, 32) d['author_avatar_url'] = request.build_absolute_uri(url) d['author_name'] = email2nickname(author_email) d['author_email'] = author_email d['author_contact_email'] = email2contact_email(author_email) d['file_name'] = file_name notice.detail = d except Exception as e: logger.error(e) return notices
def do_action(self): emails = [] user_dtable_updates_email_intervals = [] for ele in UserOptions.objects.filter( option_key=KEY_DTABLE_UPDATES_EMAIL_INTERVAL): try: user_dtable_updates_email_intervals.append( (ele.email, int(ele.option_val))) emails.append(ele.email) except Exception as e: logger.error(e) self.stderr.write('[%s]: %s' % (str(datetime.now()), e)) continue user_last_emailed_time_dict = {} for ele in UserOptions.objects.filter( option_key=KEY_DTABLE_UPDATES_LAST_EMAILED_TIME).filter( email__in=emails): try: user_last_emailed_time_dict[ele.email] = datetime.strptime( ele.option_val, "%Y-%m-%d %H:%M:%S") except Exception as e: logger.error(e) self.stderr.write('[%s]: %s' % (str(datetime.now()), e)) continue for (username, interval_val) in user_dtable_updates_email_intervals: # save current language cur_language = translation.get_language() # get and active user language user_language = self.get_user_language(username) translation.activate(user_language) logger.debug('Set language code to %s for user: %s' % (user_language, username)) self.stdout.write('[%s] Set language code to %s for user: %s' % (str(datetime.now()), user_language, username)) # get last_emailed_time if any, defaults to today 00:00:00.0 last_emailed_time = user_last_emailed_time_dict.get(username, None) now = datetime.utcnow().replace(microsecond=0) if not last_emailed_time: last_emailed_time = datetime.utcnow().replace(hour=0).replace( minute=0).replace(second=0).replace(microsecond=0) else: if (now - last_emailed_time).total_seconds() < interval_val: continue # find all the user's tables and groups' tables groups = ccnet_api.get_groups(username, return_ancestors=True) owner_list = [username] + [ '%s@seafile_group' % group.id for group in groups ] dtables = list( DTables.objects.filter(workspace__owner__in=owner_list)) # find all tables shared to user shared_tables = list(DTableShare.objects.list_by_to_user(username)) # combine tables dtables.extend([item.dtable for item in shared_tables]) # dtable uuid map dtables_uuid_map = {dtable.uuid.hex: dtable for dtable in dtables} # query all activities about above dtables with DB SQL cursor = connection.cursor() sql = "SELECT a.* FROM activities a JOIN user_activities ua ON a.id=ua.activity_id WHERE ua.timestamp > %s AND ua.username=%s ORDER BY ua.timestamp DESC" cursor.execute(sql, (last_emailed_time, username)) # time and username col_names = [desc[0] for desc in cursor.description] activities, activities_count = [], 0 for activity in cursor.fetchall(): activity = dict(zip(col_names, activity)) if activity['dtable_uuid'] not in dtables_uuid_map: continue activity_detail = json.loads(activity['detail']) activity_dict = dict(dtable_uuid=activity['dtable_uuid']) activity_dict['dtable_name'] = dtables_uuid_map[ activity['dtable_uuid']].name if activity[ 'dtable_uuid'] in dtables_uuid_map else '' activity_dict['row_id'] = activity['row_id'] activity_dict['op_type'] = activity['op_type'] activity_dict['author_email'] = activity['op_user'] activity_dict['author_name'] = email2nickname( activity['op_user']) activity_dict['author_contact_email'] = email2contact_email( activity['op_user']) activity_dict['op_time'] = utc_datetime_to_isoformat_timestr( activity['op_time']) activity_dict['table_id'] = activity_detail['table_id'] activity_dict['table_name'] = activity_detail['table_name'] activity_dict['row_data'] = activity_detail['row_data'] activity_dict['row_name'] = self.get_row_name( activity_dict['row_data']) or activity_detail.get( 'row_name', '') # compatible with previous data avatar_size = 72 # todo: size url, is_default, date_uploaded = api_avatar_url( activity['op_user'], avatar_size) activity_dict['avatar_url'] = url # fields for html-display activity_dict['op_user_link'] = a_tag( activity_dict['author_name'], user_info_url(activity['op_user'])) activity_dict['dtable_link'] = a_tag( activity_dict['dtable_name'], dtable_url(dtables_uuid_map[activity_dict['dtable_uuid']])) activity_dict['details'] = self.format_modify_operation( activity_dict) activity_dict['local_timestamp'] = utc_to_local( activity['op_time']) activities_count += 1 if len(activities) <= 100: activities.append(activity_dict) if not activities: translation.activate(cur_language) continue c = { 'name': email2nickname(username), 'updates_count': activities_count, 'updates': activities, } contact_email = email2contact_email(username) try: send_html_email( _('New table updates on %s') % get_site_name(), 'notifications/dtable_updates_email.html', c, None, [contact_email]) now = datetime.utcnow().replace(microsecond=0) UserOptions.objects.set_dtable_updates_last_emailed_time( username, now) except Exception as e: logger.error('Failed to send email to %s, error detail: %s' % (contact_email, e)) self.stderr.write('[%s] Failed to send email to %s, error ' 'detail: %s' % (str(datetime.now()), contact_email, e)) finally: # reset lang translation.activate(cur_language)
def get(self, request): """ Return file info. """ # argument check doc_id = request.GET.get('doc_id', '') if not doc_id: error_msg = 'doc_id invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) file_info = cache.get('BISHENG_OFFICE_' + doc_id) if not file_info: error_msg = 'doc_id invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) username = file_info.get('username') if not username: error_msg = 'username invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) repo_id = file_info.get('repo_id') if not repo_id: error_msg = 'repo_id invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) file_path = file_info.get('file_path') if not file_path: error_msg = 'file_path invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) file_path = normalize_file_path(file_path) # resource check try: User.objects.get(email=username) except User.DoesNotExist: error_msg = 'User %s not found.' % username return api_error(status.HTTP_404_NOT_FOUND, error_msg) if not seafile_api.get_repo(repo_id): error_msg = 'Library %s not found.' % repo_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) if not seafile_api.get_file_id_by_path(repo_id, file_path): error_msg = 'File %s not found.' % file_path return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check parent_dir = os.path.dirname(file_path) permission = seafile_api.check_permission_by_path(repo_id, parent_dir, username) if not permission: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # get file basic info file_name = os.path.basename(file_path.rstrip('/')) filetype, fileext = get_file_type_and_ext(file_name) # get file raw url file_id = seafile_api.get_file_id_by_path(repo_id, file_path) download_token = seafile_api.get_fileserver_access_token(repo_id, file_id, 'download', username, use_onetime=True) raw_url = gen_file_get_url(download_token, file_name) # get avatar url url, _, _ = api_avatar_url(username, int(72)) # prepare file permission privilege = copy.deepcopy(BISHENG_OFFICE_PRIVILEGE) can_edit = file_info.get('can_edit', False) if not can_edit: privilege.remove('FILE_WRITE') # prepare response file_info = { 'doc': { 'docId': doc_id, 'title': file_name, 'mime_type': BISHENG_OFFICE_MIME_TYPE[fileext], 'fetchUrl': raw_url, 'thumbnail': "", 'fromApi': True }, 'user': { 'uid': username, 'oid': username, 'nickName': email2nickname(username), 'avatar': url, 'privilege': privilege }, } return Response(file_info)
def get(self, request, format=None): if not EVENTS_ENABLED: events = None return api_error(status.HTTP_404_NOT_FOUND, 'Events not enabled.') try: page = int(request.GET.get('page', '')) except ValueError: page = 1 try: per_page = int(request.GET.get('per_page', '')) except ValueError: per_page = 25 start = (page - 1) * per_page count = per_page email = request.user.username try: events = get_user_activities(email, start, count) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) events_list = [] for e in events: d = dict(op_type=e.op_type) d['repo_id'] = e.repo_id d['repo_name'] = e.repo_name d['obj_type'] = e.obj_type d['commit_id'] = e.commit_id d['path'] = e.path d['name'] = '' if e.path == '/' else os.path.basename(e.path) d['author_email'] = e.op_user d['author_name'] = email2nickname(e.op_user) d['author_contact_email'] = email2contact_email(e.op_user) try: avatar_size = int(request.GET.get('avatar_size', 72)) except ValueError as e: avatar_size = 72 url, is_default, date_uploaded = api_avatar_url(e.op_user, avatar_size) d['avatar_url'] = request.build_absolute_uri(url) d['time'] = utc_datetime_to_isoformat_timestr(e.timestamp) if e.op_type == 'clean-up-trash': d['days'] = e.days elif e.op_type == 'rename' and e.obj_type == 'repo': d['old_repo_name'] = e.old_repo_name elif e.op_type == 'move' and e.obj_type in ['dir', 'file']: d['old_path'] = e.old_path elif e.op_type == 'rename' and e.obj_type in ['dir', 'file']: d['old_path'] = e.old_path d['old_name'] = os.path.basename(e.old_path) elif e.op_type == 'publish': d['old_path'] = e.old_path elif d['name'].endswith('(draft).md'): if e.op_type in ('create', 'edit') and e.obj_type == 'file': try: draft = Draft.objects.get(username=e.op_user, origin_repo_id=e.repo_id, draft_file_path=e.path) d['draft_id'] = draft.id except Draft.DoesNotExist: pass events_list.append(d) ret = { 'events': events_list } return Response(ret)