All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.rexsheng.springboot.faster.system.notice.adapter.NoticeController Maven / Gradle / Ivy

The newest version!
package com.github.rexsheng.springboot.faster.system.notice.adapter;

import com.github.rexsheng.springboot.faster.common.constant.CommonConstant;
import com.github.rexsheng.springboot.faster.common.domain.Result;
import com.github.rexsheng.springboot.faster.io.file.FileSystemService;
import com.github.rexsheng.springboot.faster.io.file.model.UploadFileRequest;
import com.github.rexsheng.springboot.faster.io.file.model.UploadFileResponse;
import com.github.rexsheng.springboot.faster.logging.RequestLog;
import com.github.rexsheng.springboot.faster.system.file.application.dto.FileLinkDTO;
import com.github.rexsheng.springboot.faster.system.modular.AppModuleProperties;
import com.github.rexsheng.springboot.faster.system.notice.application.NoticeService;
import com.github.rexsheng.springboot.faster.system.notice.application.dto.*;
import com.github.rexsheng.springboot.faster.system.utils.AuthenticationUtil;
import com.github.rexsheng.springboot.faster.util.DateUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.InputStream;
import java.util.Arrays;
import java.util.UUID;

@RestController
@RequestMapping("/sys/notice")
@Tag(name = "NoticeController",description = "公告管理")
@ConditionalOnProperty(prefix = "app.module.notice",name = "controller",havingValue = "true",matchIfMissing = true)
@ConditionalOnClass({Authentication.class, SseEmitter.class, SqlSessionFactoryBean.class})
public class NoticeController {

    private static final Logger logger= LoggerFactory.getLogger(NoticeController.class);

    @Resource
    private NoticeService noticeService;

    @Resource
    private AppModuleProperties appModuleProperties;

    @Autowired(required = false)
    private FileSystemService fileSystemService;

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).NOTICE_LIST)")
    @GetMapping
    public Result queryNoticePagedList(@RequestParam(required = false) String title,
                                       @RequestParam Long pageIndex,
                                       @RequestParam Long pageSize){
        QueryNoticeRequest request=new QueryNoticeRequest();
        request.setTitle(title);
        request.setPageIndex(pageIndex);
        request.setPageSize(pageSize);
        return Result.success(noticeService.pagedList(request));
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).NOTICE_ADD)")
    @PostMapping
    @RequestLog("新增公告")
    public Result addNotice(@RequestParam(value = "file", required = false) MultipartFile[] files, @Validated AddNoticeRequest request){
        request.setFiles(files);
        noticeService.addNotice(request);
        return Result.success();
    }

    @GetMapping("/{id}")
    @PreAuthorize("@ss.denyApi()")
    public Result getNotice(@PathVariable Long id){
        return Result.success(noticeService.getNotice(id));
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).NOTICE_EDIT)")
    @PutMapping("/{id}")
    @RequestLog("修改公告")
    public Result updateNotice(@RequestParam(value = "file", required = false) MultipartFile[] files,
                               @PathVariable Long id,
                               @Validated UpdateNoticeRequest request){
        request.setId(id);
        request.setFiles(files);
        noticeService.update(request);
        return Result.success();
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).NOTICE_EDIT)")
    @PutMapping("/{ids}/status/{status}")
    @RequestLog("修改公告状态")
    public Result changeNoticeValid(@PathVariable Long[] ids,@PathVariable Boolean status){
        noticeService.updateStatus(UpdateNoticeRequest.of(ids,status? CommonConstant.STATUS_RUNNING:CommonConstant.STATUS_STOP));
        return Result.success();
    }

    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).NOTICE_DEL)")
    @DeleteMapping
    @RequestLog("删除公告")
    public Result deletePost(@RequestBody Long[] ids){
        noticeService.delete(Arrays.asList(ids));
        return Result.success();
    }

    @GetMapping("/user")
    @PreAuthorize("@ss.denyApi()")
    public Result queryNoticePagedList(Authentication authentication,
                                       @RequestParam(required = true) Boolean readed,
                                       @RequestParam Long pageIndex,
                                       @RequestParam Long pageSize){
        QueryUserNoticeRequest request=new QueryUserNoticeRequest();
        request.setUserId(AuthenticationUtil.getUserIdFromAuthentication(authentication));
        request.setReaded(readed);
        request.setPageIndex(pageIndex);
        request.setPageSize(pageSize);
        return Result.success(noticeService.userNoticeList(request));
    }

    @PutMapping("/readed")
    @PreAuthorize("@ss.denyApi()")
    public Result readNotice(Authentication authentication, @RequestParam(required = false) Long id, @RequestParam(required = false) Long relationId){
        noticeService.updateNoticeToReaded(AuthenticationUtil.getUserIdFromAuthentication(authentication),id,relationId);
        return Result.success();
    }

    @PostMapping("/message")
    @PreAuthorize("@ss.denyApi()")
    public Result siteNotice(@RequestBody @Validated AddInternalNoticeRequest request){
        noticeService.addInternalNotice(request);
        return Result.success();
    }

    @PostMapping("/readall")
    @PreAuthorize("@ss.denyApi()")
    public Result readAllNotice(Authentication authentication){
        noticeService.readAllNotice(AuthenticationUtil.getUserIdFromAuthentication(authentication));
        return Result.success();
    }

    @PostMapping("/img/upload")
    @PreAuthorize("hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).NOTICE_ADD) " +
            "|| hasAuthority(T(com.github.rexsheng.springboot.faster.common.constant.AuthCodeConstant).NOTICE_EDIT)")
    @ConditionalOnProperty(prefix = "app.module.file",name = "enabled",havingValue = "true",matchIfMissing = false)
    public Result uploadImage(@RequestParam(value = "photo", required = false) MultipartFile imgFile){
        if(fileSystemService==null){
            logger.warn("请启用配置app.module.file.enabled=true");
            throw new RuntimeException("文件服务异常");
        }
        if(imgFile.getSize()>appModuleProperties.getNotice().getImageSize()){
            logger.warn("文件过大, {}, max: {}", imgFile.getSize(), appModuleProperties.getNotice().getImageSize());
            throw new IllegalArgumentException("文件过大");
        }
        String name=imgFile.getOriginalFilename().toLowerCase();
        if(!Arrays.stream(appModuleProperties.getNotice().getImageSuffix()).anyMatch(suffix->name.endsWith(suffix.toLowerCase()))){
            throw new IllegalArgumentException("格式不支持");
        }
        String newFileName=UUID.randomUUID()+name.substring(name.lastIndexOf("."));
        String key= "notice/"+DateUtil.format(DateUtil.currentDateTime(),"yyyyMMdd")+"/"+newFileName;
        try(InputStream inputStream=imgFile.getInputStream()){
            UploadFileResponse uploadFileResponse=fileSystemService.uploadFile(new UploadFileRequest(appModuleProperties.getNotice().getBucketName(),key,newFileName,inputStream));
            if(uploadFileResponse!=null){
                return Result.success(FileLinkDTO.downloadLink(uploadFileResponse));
            }
        }
        catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException("文件上传异常",e);
        }
        return Result.error("文件上传异常");
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy