Esempio n. 1
0
 def update(self, request, *args, **kwargs):
     partial = kwargs.pop('partial', False)
     instance = self.get_object()
     old_instance = self.get_object()
     name = request.data.get('name', '')
     if name != instance.name and TeamGroup.objects.filter(
             name=name).first():
         result = {
             'success': False,
             'messages': f'团队:{name} 已经存在, 不能修改成此名称'
         }
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     serializer = self.get_serializer(instance,
                                      data=request.data,
                                      partial=partial)
     serializer.is_valid(raise_exception=True)
     self.perform_update(serializer)
     if getattr(instance, '_prefetched_objects_cache', None):
         instance._prefetched_objects_cache = {}
     action_log(request=request,
                user=request.user,
                action_type=UpdateAction,
                old_instance=old_instance,
                instance=instance,
                action_info=f'修改团队:{instance.__str__()}')
     result = {
         'success': True,
         'messages': f'修改团队:{instance.__str__()}',
         'results': serializer.data
     }
     return Response(result, status=status.HTTP_200_OK)
Esempio n. 2
0
 def token(self, request, *args, **kwargs):
     if request.method == 'GET':
         token = get_jwt_token(request.user)
         result = {
             'success': True,
             'messages': f'获取用户个人token',
             'results': {
                 'token': token
             }
         }
         return Response(result, status=status.HTTP_200_OK)
     if request.method == 'POST':
         action_log(request=request,
                    user=request.user,
                    action_type=UpdateAction,
                    old_instance=None,
                    instance=None,
                    action_info=f'更新用户个人token')
         token = get_jwt_token(request.user)
         result = {
             'success': True,
             'messages': f'更新用户个人token',
             'results': {
                 'token': token
             }
         }
         return Response(result, status=status.HTTP_200_OK)
Esempio n. 3
0
 def create(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     username = request.data.get('username', '')
     if User.objects.filter(username=username).first():
         result = {
             'success': False,
             'messages': f'用户:{username} 已经存在, 不能重复创建'
         }
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     serializer.is_valid(raise_exception=True)
     self.perform_create(serializer)
     headers = self.get_success_headers(serializer.data)
     instance = User.objects.get(pk=int(serializer.data['id']))
     action_log(request=request,
                user=request.user,
                action_type=CreateAction,
                old_instance=None,
                instance=instance,
                action_info=f'新增用户:{instance.__str__()}')
     result = {
         'success': True,
         'messages': f'新增用户:{instance.__str__()}',
         'results': serializer.data
     }
     return Response(result, status=status.HTTP_200_OK, headers=headers)
Esempio n. 4
0
 def bulk_delete(self, request, *args, **kwargs):
     # 批量删除
     deleted_objects_ids = request.data.get('deleted_objects', [])
     queryset = self.get_queryset()
     deleted_objects_names = []
     for deleted_object_id in deleted_objects_ids:
         instance = User.objects.get(pk=int(deleted_object_id))
         if instance == request.user:
             result = {
                 'success':
                 False,
                 'messages':
                 f'用户:{instance.__str__()}为当前账号,不能删除自己!若要删除,请使用其他管理员账号登录删除此用户'
             }
             return Response(result, status=status.HTTP_400_BAD_REQUEST)
         deleted_objects_names.append(instance.__str__())
     deleted_objects = queryset.filter(id__in=deleted_objects_ids).all()
     deleted_objects.delete()
     action_log(request=request,
                user=request.user,
                action_type=DeleteAction,
                old_instance=None,
                instance=None,
                action_info=f'批量删除用户:{deleted_objects_names}')
     result = {
         'success': True,
         'messages': f'批量删除用户:{deleted_objects_names}'
     }
     return Response(result, status=status.HTTP_200_OK)
Esempio n. 5
0
 def password(self, request, *args, **kwargs):
     """修改个人密码"""
     instance = self.request.user
     old_instance = self.request.user
     old_password = request.data.get('old_password')
     new_password = request.data.get('new_password')
     if instance.check_password(old_password):
         instance.set_password(new_password)
         instance.save()
         action_log(request=request,
                    user=request.user,
                    action_type=UpdateAction,
                    old_instance=old_instance,
                    instance=instance,
                    action_info=f'修改个人密码:{instance.__str__()}')
         return Response({
             'messages': f'修改个人密码:{instance.__str__()}',
             'success': True
         })
     else:
         return Response({
             'messages': '原密码不正确',
             'success': False
         },
                         status=status.HTTP_400_BAD_REQUEST)
Esempio n. 6
0
 def destroy(self, request, *args, **kwargs):
     instance = self.get_object()
     self.perform_destroy(instance)
     action_log(request=request, user=request.user, action_type=DeleteAction, old_instance=None,
                instance=instance, action_info=f'删除素材分组:{instance.__str__()}')
     result = {'success': True, 'messages': f'删除素材分组:{instance.__str__()}'}
     return Response(result, status=status.HTTP_200_OK)
Esempio n. 7
0
 def post(self, request, *args, **kwargs):
     username = request.data.get('username')
     email = request.data.get('email')
     if not username or not email:
         result = {'success': False, 'messages': '用户帐号名/邮箱必须存在'}
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     user = User.objects.filter(username=username).first()
     if user:
         if user.email != email:
             result = {'success': False, 'messages': f'当前邮箱与用户注册邮箱:{user.email[:5]}****不一致, 请重新输入'}
             return Response(result, status=status.HTTP_400_BAD_REQUEST)
         email_setting = get_email_setting()
         if not email_setting:
             result = {'success': False, 'messages': f'管理员尚未配置邮箱, 无法重置密码, 请联系管理员'}
             return Response(result, status=status.HTTP_400_BAD_REQUEST)
         email_code = EmailVerificationCode.objects.create(email_name=email, verification_type=20,
                                                           expired_time=datetime.now() + timedelta(hours=12),
                                                           creator=user)
         send_email(subject='DocShared 忘记密码',
                    html_content=f'该邮件来自于DocShared<br>'
                                 f'用于重置:{username}的密码, 验证码为:{email_code.verification_code}<br>'
                                 f'请点击以下链接进行重置: <a href="http://90fyl.com/validation/{email_code.verification_code}"> http://90fyl.com/validation/{email_code.verification_code} </a>',
                    to_list=[email])
         action_log(request=request, user=user, action_type=AuthAction, old_instance=None,
                    instance=None, action_info=f'忘记密码:{username}')
         result = {'success': True, 'messages': f'验证码已发送, 请前往邮箱查看, 并进行下一步'}
         return Response(result, status=status.HTTP_200_OK)
     else:
         result = {'success': False, 'messages': f'当前用户:{username}不存在, 请重新输入或注册新用户'}
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 8
0
 def post(self, request, *args, **kwargs):
     code = request.data.get('code')
     new_password = request.data.get('password', None)
     email_code = EmailVerificationCode.objects.filter(verification_code=code).first()
     if not email_code:
         result = {'success': False, 'messages': '当前验证码不正确, 无法确认信息'}
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     if email_code.status == 0:
         result = {'success': False, 'messages': '当前验证码已使用或无效'}
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     if email_code.expired_time < pytz.UTC.localize(datetime.now()):
         result = {'success': False, 'messages': '当前验证码已经过期, 无法使用'}
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     if email_code.verification_type != 20:
         result = {'success': False, 'messages': '当前验证码不是用于重置密码, 请勿操作'}
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     if not new_password:
         return Response({'messages': '请输入新密码', 'success': False}, status=status.HTTP_400_BAD_REQUEST)
     user = email_code.creator
     user.set_password(new_password)
     user.save()
     email_code.status = 0
     email_code.save()
     action_log(request=request, user=request.user, action_type=AuthAction, old_instance=user,
                instance=user, action_info=f'重置密码:{user.__str__()}')
     result = {'success': True, 'messages': f'用户:{user.username}已经重置密码, 可正常登录使用',
               'results': EmailVerificationCodeListSerializer(email_code).data}
     return Response(result, status=status.HTTP_200_OK)
Esempio n. 9
0
 def create(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     c_doc_id = request.data.get('c_doc', False)
     team_group_id = request.data.get('team_group', False)
     c_doc_team = CollectedDocTeam.objects.filter(
         c_doc__id=int(c_doc_id),
         team_group__id=int(team_group_id)).first()
     if c_doc_team:
         result = {
             'success': False,
             'messages': f'文集团队成员:{c_doc_team.__str__()}已经存在, 请勿重复创建'
         }
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     self.perform_create(serializer)
     headers = self.get_success_headers(serializer.data)
     instance = CollectedDocTeam.objects.get(pk=int(serializer.data['id']))
     action_log(request=request,
                user=request.user,
                action_type=CreateAction,
                old_instance=None,
                instance=instance,
                action_info=f'新增文集团队成员:{instance.__str__()}')
     result = {
         'success': True,
         'messages': f'新增文集团队成员:{instance.__str__()}',
         'results': serializer.data
     }
     return Response(result, status=status.HTTP_200_OK, headers=headers)
Esempio n. 10
0
 def create(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     name = request.data.get('name', False)
     doc_tag = DocTag.objects.filter(name=name,
                                     creator=request.user).first()
     if doc_tag:
         result = {
             'success': False,
             'messages': f'你已创建标签:{doc_tag.__str__()} 请勿重复创建'
         }
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     self.perform_create(serializer)
     headers = self.get_success_headers(serializer.data)
     instance = DocTag.objects.get(pk=int(serializer.data['id']))
     action_log(request=request,
                user=request.user,
                action_type=CreateAction,
                old_instance=None,
                instance=instance,
                action_info=f'新增文档标签:{instance.__str__()}')
     result = {
         'success': True,
         'messages': f'新增文档标签:{instance.__str__()}',
         'results': serializer.data
     }
     return Response(result, status=status.HTTP_200_OK, headers=headers)
Esempio n. 11
0
 def update(self, request, *args, **kwargs):
     partial = kwargs.pop('partial', False)
     parent_doc_id = request.data.get('parent_doc', None)
     instance = self.get_object()
     old_instance = self.get_object()
     if parent_doc_id and int(parent_doc_id) == instance.id:
         result = {'success': False, 'messages': f'上级文档不能为当前文档自身'}
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     serializer = self.get_serializer(instance,
                                      data=request.data,
                                      partial=partial)
     serializer.is_valid(raise_exception=True)
     self.perform_update(serializer)
     if getattr(instance, '_prefetched_objects_cache', None):
         instance._prefetched_objects_cache = {}
     # 保存最新一次记录
     instance.pre_content = old_instance.content
     instance.save()
     # 历史记录
     DocHistory.objects.create(doc=instance,
                               content=instance.pre_content,
                               creator=request.user)
     action_log(request=request,
                user=request.user,
                action_type=UpdateAction,
                old_instance=old_instance,
                instance=instance,
                action_info=f'修改文档:{instance.__str__()}')
     result = {
         'success': True,
         'messages': f'修改文档:{instance.__str__()}',
         'results': serializer.data
     }
     return Response(result, status=status.HTTP_200_OK)
Esempio n. 12
0
 def post(self, request, *args, **kwargs):
     username = request.data.get('username')
     password = request.data.get('password')
     if not username:
         result = {'success': False, 'messages': '用户帐号名必须存在, 请发送用户名'}
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     if not password:
         result = {'success': False, 'messages': '密码必须存在, 请发送密码'}
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     user = User.objects.filter(username=username).first()
     if user:
         if not user.is_active:
             result = {'success': False, 'messages': '当前用户未激活, 若为新注册用户请查看邮箱进行激活, 或联系管理员'}
             return Response(result, status=status.HTTP_403_FORBIDDEN)
         if user.is_deleted:
             result = {'success': False, 'messages': '当前用户已删除, 请使用其他用户'}
             return Response(result, status=status.HTTP_403_FORBIDDEN)
         login_user = authenticate(username=username.strip(), password=password)
         if login_user is None:
             result = {'success': False, 'messages': '用户名:{}密码错误, 请输入正确密码'.format(username)}
             return Response(result, status=status.HTTP_403_FORBIDDEN)
     else:
         result = {'success': False, 'messages': '用户名:{}不存在或无效, 请输入正确用户'.format(username)}
         return Response(result, status=status.HTTP_403_FORBIDDEN)
     # 认证成功
     token = get_jwt_token(login_user)
     response_data = jwt_response_payload_handler(token, login_user, request)
     response = Response(response_data, status=status.HTTP_200_OK)
     action_log(request=request, user=request.user, action_type=AuthAction, old_instance=None,
                instance=None, action_info=f'登录系统')
     return response
Esempio n. 13
0
 def post(self, request, *args, **kwargs):
     username = request.data.get('username')
     password = request.data.get('password')
     email = request.data.get('email')
     reg_code = request.data.get('reg_code')
     if not username or not password or not email:
         result = {'success': False, 'messages': '用户帐号名/密码/邮箱必须存在'}
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     reg_code_setting = SystemSetting.objects.filter(key='use_reg_code').first()
     verify_register_setting = SystemSetting.objects.filter(key='verify_register').first()
     if reg_code_setting:
         use_reg_code = True if reg_code_setting.value.lower() == 'true' else False
     else:
         use_reg_code = False
     if verify_register_setting:
         verify_register = True if verify_register_setting.value.lower() == 'true' else False
     else:
         verify_register = False
     reg_code_obj = RegisterCode.objects.filter(code=reg_code).first()
     if use_reg_code:
         if not reg_code:
             result = {'success': False, 'messages': '当前注册需要注册码, 请输入注册码'}
             return Response(result, status=status.HTTP_400_BAD_REQUEST)
         if not reg_code_obj:
             result = {'success': False, 'messages': '当前注册码不存在, 请输入正确注册码'}
             return Response(result, status=status.HTTP_400_BAD_REQUEST)
         if reg_code_obj.status == 0:
             result = {'success': False, 'messages': '当前注册码已无效, 请输入正确注册码'}
             return Response(result, status=status.HTTP_400_BAD_REQUEST)
         if reg_code_obj.all_cnt - reg_code_obj.used_cnt <= 0:
             result = {'success': False, 'messages': '当前注册码已无有效注册数量, 请输入正确注册码'}
             return Response(result, status=status.HTTP_400_BAD_REQUEST)
     user = User.objects.filter(username=username).first()
     if user:
         result = {'success': False, 'messages': '当前用户已经存在, 请勿重复注册'}
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     else:
         is_active = False if verify_register else True
         user = User.objects.create_user(username=username, password=password, nickname=username, email=email,
                                         register_code=reg_code_obj, is_active=is_active)
         if reg_code_obj and use_reg_code:
             reg_code_obj.used_cnt += 1
             reg_code_obj.save()
         action_log(request=request, user=user, action_type=AuthAction, old_instance=None,
                    instance=None, action_info=f'注册账号:{username}')
         if verify_register:
             email_code = EmailVerificationCode.objects.create(email_name=email, verification_type=10,
                                                               expired_time=datetime.now() + timedelta(hours=12),
                                                               creator=user)
             messages = f'验证邮件已经发送至注册邮箱, 请到邮箱查看验证码信息进行下一步'
             send_email(subject='DocShared 注册用户',
                        html_content=f'该邮件来自于DocShared<br>'
                                     f'用于注册用户:{username}, 验证码为:{email_code.verification_code}<br>'
                                     f'请点击以下链接进行下一步: <a href="http://90fyl.com/validation/{email_code.verification_code}"> http://90fyl.com/validation/{email_code.verification_code} </a>',
                        to_list=[email])
         else:
             messages = f'成功注册用户:{username}'
         result = {'success': True, 'messages': messages}
         return Response(result, status=status.HTTP_200_OK)
Esempio n. 14
0
 def create(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     self.perform_create(serializer)
     headers = self.get_success_headers(serializer.data)
     instance = FileGroup.objects.get(pk=int(serializer.data['id']))
     action_log(request=request, user=request.user, action_type=CreateAction, old_instance=None,
                instance=instance, action_info=f'新增素材分组:{instance.__str__()}')
     result = {'success': True, 'messages': f'新增素材分组:{instance.__str__()}',
               'results': serializer.data}
     return Response(result, status=status.HTTP_200_OK, headers=headers)
Esempio n. 15
0
 def recover(self, request, *args, **kwargs):
     instance = self.get_object()
     instance.is_deleted = False
     instance.save()
     # self.perform_destroy(instance)
     action_log(request=request,
                user=request.user,
                action_type=RecoverAction,
                old_instance=None,
                instance=instance,
                action_info=f'还原文档:{instance.__str__()}')
     result = {'success': True, 'messages': f'还原文档:{instance.__str__()}'}
     return Response(result, status=status.HTTP_200_OK)
Esempio n. 16
0
 def destroy(self, request, *args, **kwargs):
     instance = self.get_object()
     file_path = instance.file_path
     file_save_path = os.path.join(settings.MEDIA_ROOT, file_path)
     try:
         os.remove(file_save_path)
     except:
         pass
     self.perform_destroy(instance)
     action_log(request=request, user=request.user, action_type=DeleteAction, old_instance=None,
                instance=instance, action_info=f'删除素材:{instance.__str__()}')
     result = {'success': True, 'messages': f'删除素材:{instance.__str__()}'}
     return Response(result, status=status.HTTP_200_OK)
Esempio n. 17
0
 def bulk_delete(self, request, *args, **kwargs):
     # 批量删除
     deleted_objects_ids = request.data.get('deleted_objects', [])
     queryset = self.get_queryset()
     deleted_objects_names = []
     for deleted_object_id in deleted_objects_ids:
         instance = FileGroup.objects.get(pk=int(deleted_object_id))
         deleted_objects_names.append(instance.__str__())
     deleted_objects = queryset.filter(id__in=deleted_objects_ids).all()
     deleted_objects.delete()
     action_log(request=request, user=request.user, action_type=DeleteAction, old_instance=None,
                instance=None, action_info=f'批量删除素材分组:{deleted_objects_names}')
     result = {'success': True, 'messages': f'批量删除素材分组:{deleted_objects_names}'}
     return Response(result, status=status.HTTP_200_OK)
Esempio n. 18
0
 def update(self, request, *args, **kwargs):
     partial = kwargs.pop('partial', False)
     instance = self.get_object()
     old_instance = self.get_object()
     serializer = self.get_serializer(instance, data=request.data, partial=partial)
     serializer.is_valid(raise_exception=True)
     self.perform_update(serializer)
     if getattr(instance, '_prefetched_objects_cache', None):
         instance._prefetched_objects_cache = {}
     action_log(request=request, user=request.user, action_type=UpdateAction, old_instance=old_instance,
                instance=instance, action_info=f'修改素材分组:{instance.__str__()}')
     result = {'success': True, 'messages': f'修改素材分组:{instance.__str__()}',
               'results': serializer.data}
     return Response(result, status=status.HTTP_200_OK)
Esempio n. 19
0
 def destroy(self, request, *args, **kwargs):
     instance = self.get_object()
     clear = request.data.get('clear', False)
     if clear:
         self.perform_destroy(instance)
         messages = f'清空文档:{instance.__str__()}'
     else:
         instance.is_deleted = True
         instance.save()
         messages = f'删除文档:{instance.__str__()}'
     action_log(request=request,
                user=request.user,
                action_type=DeleteAction,
                old_instance=None,
                instance=instance,
                action_info=messages)
     result = {'success': True, 'messages': messages}
     return Response(result, status=status.HTTP_200_OK)
Esempio n. 20
0
 def destroy(self, request, *args, **kwargs):
     instance = self.get_object()
     if instance == request.user:
         result = {
             'success':
             False,
             'messages':
             f'用户:{instance.__str__()}为当前账号,不能删除自己!若要删除,请使用其他管理员账号登录删除此用户'
         }
         return Response(result, status=status.HTTP_400_BAD_REQUEST)
     self.perform_destroy(instance)
     action_log(request=request,
                user=request.user,
                action_type=DeleteAction,
                old_instance=None,
                instance=instance,
                action_info=f'删除用户:{instance.__str__()}')
     result = {'success': True, 'messages': f'删除用户:{instance.__str__()}'}
     return Response(result, status=status.HTTP_200_OK)
Esempio n. 21
0
 def bulk_recover(self, request, *args, **kwargs):
     # 批量删除
     recover_objects_ids = request.data.get('recover_objects', [])
     queryset = self.get_queryset()
     recover_objects_names = []
     for recover_objects_id in recover_objects_ids:
         instance = Doc.objects.get(pk=int(recover_objects_id))
         recover_objects_names.append(instance.__str__())
     recover_objects = queryset.filter(id__in=recover_objects_ids)
     recover_objects.update(is_deleted=False)
     action_log(request=request,
                user=request.user,
                action_type=RecoverAction,
                old_instance=None,
                instance=None,
                action_info=f'批量还原文档:{recover_objects_names}')
     result = {
         'success': True,
         'messages': f'批量还原文档:{recover_objects_names}'
     }
     return Response(result, status=status.HTTP_200_OK)
Esempio n. 22
0
 def bulk_delete(self, request, *args, **kwargs):
     # 批量删除
     deleted_objects_ids = request.data.get('deleted_objects', [])
     queryset = self.get_queryset()
     deleted_objects_names = []
     for deleted_object_id in deleted_objects_ids:
         instance = FileAttachment.objects.get(pk=int(deleted_object_id))
         file_path = instance.file_path
         file_save_path = os.path.join(settings.MEDIA_ROOT, file_path)
         try:
             os.remove(file_save_path)
         except:
             pass
         self.perform_destroy(instance)
         deleted_objects_names.append(instance.__str__())
     deleted_objects = queryset.filter(id__in=deleted_objects_ids).all()
     deleted_objects.delete()
     action_log(request=request, user=request.user, action_type=DeleteAction, old_instance=None,
                instance=None, action_info=f'批量删除素材:{deleted_objects_names}')
     result = {'success': True, 'messages': f'批量删除素材:{deleted_objects_names}'}
     return Response(result, status=status.HTTP_200_OK)
Esempio n. 23
0
 def activation(self, request, *args, **kwargs):
     """禁用/启用用户"""
     old_instance = self.get_object()
     instance = self.get_object()
     active = request.data.get('active', True)
     if active:
         instance.is_active = True
         instance.save()
         action_log(request=request,
                    user=request.user,
                    action_type=ActiveAction,
                    old_instance=old_instance,
                    instance=instance,
                    action_info=f'启用用户:{instance.__str__()}')
         result = {
             'success': True,
             'messages': f'启用用户:{instance.__str__()}'
         }
         return Response(result, status=status.HTTP_200_OK)
     else:
         if instance == request.user:
             result = {
                 'success': False,
                 'messages': f'用户:{instance.__str__()}为当前账号,不能禁用自己'
             }
             return Response(result, status=status.HTTP_400_BAD_REQUEST)
         instance.is_active = False
         instance.save()
         action_log(request=request,
                    user=request.user,
                    action_type=DisableAction,
                    old_instance=old_instance,
                    instance=instance,
                    action_info=f'禁用用户:{instance.__str__()}')
         result = {
             'success': True,
             'messages': f'禁用用户:{instance.__str__()}'
         }
         return Response(result, status=status.HTTP_200_OK)
Esempio n. 24
0
 def reset_password(self, request, *args, **kwargs):
     """修改/重置用户密码"""
     old_instance = self.get_object()
     instance = self.get_object()
     new_password = request.data.get('password', None)
     if not new_password:
         return Response({
             'messages': '请输入新密码',
             'success': False
         },
                         status=status.HTTP_400_BAD_REQUEST)
     instance.set_password(new_password)
     instance.save()
     action_log(request=request,
                user=request.user,
                action_type=UpdateAction,
                old_instance=old_instance,
                instance=instance,
                action_info=f'重置用户密码:{instance.__str__()}')
     return Response({
         'messages': f'重置用户密码:{instance.__str__()}',
         'success': True
     })
Esempio n. 25
0
 def bulk_delete(self, request, *args, **kwargs):
     # 批量删除
     deleted_objects_ids = request.data.get('deleted_objects', [])
     clear = request.data.get('clear', False)
     queryset = self.get_queryset()
     deleted_objects_names = []
     for deleted_object_id in deleted_objects_ids:
         instance = Doc.objects.get(pk=int(deleted_object_id))
         deleted_objects_names.append(instance.__str__())
     deleted_objects = queryset.filter(id__in=deleted_objects_ids)
     if clear:
         deleted_objects.delete()
         messages = f'批量清空文档:{deleted_objects_names}'
     else:
         deleted_objects.update(is_deleted=True)
         messages = f'批量删除文档:{deleted_objects_names}'
     action_log(request=request,
                user=request.user,
                action_type=DeleteAction,
                old_instance=None,
                instance=None,
                action_info=messages)
     result = {'success': True, 'messages': messages}
     return Response(result, status=status.HTTP_200_OK)
Esempio n. 26
0
    def create(self, request, *args, **kwargs):
        """
        简化版大文件上传接口, 同时可处理大文件上传, 但不支持断点续传
        """
        chunk_file = request.data.get('chunk_file', None)  # 分块文件
        chunk_md5 = request.data.get('chunk_md5', None)  # 分块文件MD5
        chunk_index = request.data.get('chunk_index', None)  # 分块文件顺序
        chunks_num = request.data.get('chunks_num', None)  # 完整文件分块数目,用于确定当前分块是否已经全部上传完毕
        file_name = request.data.get('file_name', None)  # 完整文件的文件名称,用于所有分块上传完毕后合并的名称
        file_md5 = request.data.get('file_md5', None)  # 完整文件的文件md5,用于确定文件合并后是否正确
        group_id = request.data.get('group', None)
        file_type = request.data.get('file_type', None)
        if not chunk_file or not chunk_index or not chunks_num or not file_name:
            result = {'success': False,
                      'messages': '上传失败, 缺少指定参数值: chunk_file/chunk_index/chunks_num/file_name'}
            return Response(result, status=status.HTTP_400_BAD_REQUEST)

        file_type_name = FileType.get(int(file_type), 'default')
        try:
            group = FileGroup.objects.get(pk=int(group_id))
            group_name = group.name
        except:
            group = None
            group_name = 'None'
        file_path = f'{file_type_name}/{request.user.username}/{group_name}'
        base_path = create_or_get_directory(f'{settings.MEDIA_ROOT}/{file_path}')
        base_chunk_path = create_or_get_directory(f'{base_path}/{file_name}-tmp')
        chunk_path = os.path.join(base_chunk_path, f'{file_name}.part{chunk_index}')
        # default_storage不会覆盖文件, 若文件存在, 删除后重新上传
        if default_storage.exists(chunk_path):
            default_storage.delete(chunk_path)
        # 保存
        default_storage.save(chunk_path, ContentFile(chunk_file.read()))
        # 验证分块MD5是否正确
        if chunk_md5:
            chunk_file_md5 = check_md5_sum(file_name=chunk_path)
            # 保存的分块文件内容不一致
            if chunk_file_md5 != chunk_md5:
                result = {'success': False, 'messages': '文件上传发生错误, md5值不一致',
                          'results': {'upload_md5': chunk_md5, 'save_md5': chunk_file_md5}}
                return Response(result, status=status.HTTP_400_BAD_REQUEST)
        if int(chunk_index) == int(chunks_num):
            uploaded = True
            save_file_path = os.path.join(base_path, file_name)
            # 文件已经存在, 添加时间戳
            if os.path.exists(save_file_path):
                save_file_path = os.path.join(base_path, f'{int(time.time())}-{file_name}')
            with open(save_file_path, 'wb') as uploaded_file:
                for index in range(int(chunks_num)):
                    chunk_file = os.path.join(base_chunk_path, f'{file_name}.part{index + 1}')
                    try:
                        chunk_file = open(chunk_file, 'rb')  # 按序打开每个分片
                        uploaded_file.write(chunk_file.read())  # 读取分片内容写入新文件
                        chunk_file.close()
                    except Exception as error:
                        print(f'合并文件:{file_name} form {base_chunk_path}失败:{error}')
                        uploaded = False
                        # 检查合并后的MD5
            uploaded_file_md5 = check_md5_sum(save_file_path)
            if uploaded_file_md5 != file_md5:
                uploaded = False
            if uploaded:
                attachment = FileAttachment.objects.create(group=group, file_name=file_name,
                                                           file_path=os.path.join(file_path, file_name),
                                                           file_size=os.path.getsize(save_file_path),
                                                           file_type=file_type, creator=request.user)
                shutil.rmtree(base_chunk_path)
                action_log(request=request, user=request.user, action_type=UploadAction, old_instance=None,
                           instance=attachment, action_info=f'上传素材:{attachment.__str__()}')
                serializer = self.get_serializer(attachment)
                results = serializer.data
                results['uploaded'] = True
                result = {'success': True, 'messages': f'新增素材:{attachment.__str__()}', 'results': results}
                return Response(result, status=status.HTTP_200_OK)
            else:
                result = {'success': False, 'messages': '合并文件失败, 请重新上传'}
                return Response(result, status=status.HTTP_400_BAD_REQUEST)
        else:
            result = {'success': True, 'messages': f'成功上传文件:{file_name}, 分块:{chunk_index}',
                      'results': {'uploaded': False, 'chunk_index': chunk_index, 'file_name': file_name, }
                      }
            return Response(result, status=status.HTTP_200_OK)