feat: 定时报告自测版本

This commit is contained in:
fit2cloud-chenyw
2021-11-23 18:37:32 +08:00
parent f50274dc1c
commit 09d6cc7103
13 changed files with 307 additions and 142 deletions

View File

@@ -48,6 +48,10 @@ public class AuthUserServiceImpl implements AuthUserService {
return authMapper.findUser(userId);
}
public SysUserEntity getUserByIdNoCache(Long userId) {
return authMapper.findUser(userId);
}
@Override
public SysUserEntity getUserByName(String username) {
return authMapper.findUserByName(username);

View File

@@ -1,11 +1,15 @@
package io.dataease.commons.utils;
import io.dataease.commons.constants.AuthConstants;
import io.dataease.plugins.config.SpringContextUtil;
import org.springframework.core.env.Environment;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ServletUtils {
@@ -34,6 +38,20 @@ public class ServletUtils {
return token;
}
public static String domain() {
InetAddress ip;
String hostAddress = "";
try {
ip = InetAddress.getLocalHost();
hostAddress = ip.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
Environment environment = SpringContextUtil.getBean(Environment.class);
Integer port = environment.getProperty("server.port", Integer.class);
return "http://" + hostAddress + ":"+port ;
}

View File

@@ -1,88 +0,0 @@
package io.dataease.commons.utils;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.Augmenter;
import org.springframework.core.env.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
/**
* 打印浏览器
*/
public class WebDriverUtils {
private static String driverPath;
public static void print(String url, String filePath) {
try {
url = URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (StringUtils.isBlank(driverPath)) {
driverPath = CommonBeanFactory.getBean(Environment.class).getProperty("dataease.chrome-driver-path", String.class, "/usr/bin/chromedriver");
}
String driverPath = "/usr/local/sbin/chromedriver";
ChromeOptions options = new ChromeOptions();
options.addArguments("headless");
options.addArguments("no-sandbox");
options.addArguments("disable-gpu");
options.addArguments("disable-features=NetworkService");
options.addArguments("ignore-certificate-errors");
options.addArguments("silent-launch");
options.addArguments("disable-application-cache");
options.addArguments("disable-web-security");
options.addArguments("no-proxy-server");
options.addArguments("disable-dev-shm-usage");
WebDriver driver = null;
try {
System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, driverPath);
driver = new ChromeDriver(options);
} catch (Exception e) {
e.printStackTrace();
}
driver.get(url);
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenshot = ((TakesScreenshot) augmentedDriver) .getScreenshotAs(OutputType.FILE);
File file = new File(filePath);
copy(screenshot, file);
driver.quit();
}
private static void copy(File src, File dest) {
try
{
FileInputStream fis = new FileInputStream(src);//创建输入流对象
FileOutputStream fos = new FileOutputStream(dest); //创建输出流对象
byte datas[] = new byte[1024*8];//创建搬运工具
int len = 0;//创建长度
while((len = fis.read(datas))!=-1)//循环读取数据
{
fos.write(datas,0,len);
}
fis.close();//释放资源
fis.close();//释放资源
} catch (Exception e){
e.printStackTrace();
}
}
}

View File

@@ -18,8 +18,8 @@ public abstract class TaskHandler implements InitializingBean {
public void addTask(ScheduleManager scheduleManager, GlobalTaskEntity taskEntity) throws Exception {
// 1。首先看看是否过期
Long endTime = taskEntity.getEndTime();
removeTask(scheduleManager, taskEntity);
if (taskExpire(endTime)) { // 过期了就删除任务
removeTask(scheduleManager, taskEntity);
return;
}
JobKey jobKey = new JobKey(taskEntity.getTaskId().toString());

View File

@@ -4,26 +4,27 @@ package io.dataease.job.sechedule.strategy.impl;
import io.dataease.auth.entity.SysUserEntity;
import io.dataease.auth.entity.TokenInfo;
import io.dataease.auth.service.AuthUserService;
import io.dataease.auth.service.impl.AuthUserServiceImpl;
import io.dataease.auth.util.JWTUtils;
import io.dataease.commons.utils.CommonBeanFactory;
import io.dataease.commons.utils.LogUtil;
import io.dataease.commons.utils.ServletUtils;
import io.dataease.job.sechedule.ScheduleManager;
import io.dataease.job.sechedule.strategy.TaskHandler;
import io.dataease.plugins.common.entity.GlobalTaskEntity;
import io.dataease.plugins.common.entity.GlobalTaskInstance;
import io.dataease.plugins.config.SpringContextUtil;
import io.dataease.plugins.xpack.email.dto.request.XpackPixelEntity;
import io.dataease.plugins.xpack.email.dto.response.XpackEmailTemplateDTO;
import io.dataease.plugins.xpack.email.service.EmailXpackService;
import io.dataease.service.FileService;
import io.dataease.service.system.EmailService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.*;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.annotation.Resource;
@Service
@@ -34,6 +35,8 @@ public class EmailTaskHandler extends TaskHandler implements Job {
private static final Integer SUCCESS = 1;
private static final Integer ERROR = -1;
@Resource
private AuthUserServiceImpl authUserServiceImpl;
@Override
@@ -44,7 +47,8 @@ public class EmailTaskHandler extends TaskHandler implements Job {
XpackEmailTemplateDTO emailTemplateDTO = emailXpackService.emailTemplate(taskEntity.getTaskId());
jobDataMap.put("emailTemplate", emailTemplateDTO);
SysUserEntity creator = CommonBeanFactory.getBean(AuthUserService.class).getUserById(taskEntity.getCreator());
/*SysUserEntity creator = CommonBeanFactory.getBean(AuthUserService.class).getUserById(taskEntity.getCreator());*/
SysUserEntity creator =authUserServiceImpl.getUserByIdNoCache(taskEntity.getCreator());
jobDataMap.put("creator", creator);
return jobDataMap;
}
@@ -56,6 +60,11 @@ public class EmailTaskHandler extends TaskHandler implements Job {
JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
GlobalTaskEntity taskEntity = (GlobalTaskEntity)jobDataMap.get("taskEntity");
if (taskExpire(taskEntity.getEndTime())) {
ScheduleManager scheduleManager = SpringContextUtil.getBean(ScheduleManager.class);
removeTask(scheduleManager, taskEntity);
return;
}
GlobalTaskInstance taskInstance = buildInstance(taskEntity);
Long instanceId = saveInstance(taskInstance);
@@ -85,11 +94,16 @@ public class EmailTaskHandler extends TaskHandler implements Job {
return taskInstance;
}
private void changeStatus(GlobalTaskInstance taskInstance, Integer status) {
taskInstance.setStatus(status);
if(status == SUCCESS) {
taskInstance.setFinishTime(System.currentTimeMillis());
}
private void success(GlobalTaskInstance taskInstance) {
taskInstance.setStatus(SUCCESS);
taskInstance.setFinishTime(System.currentTimeMillis());
EmailXpackService emailXpackService = SpringContextUtil.getBean(EmailXpackService.class);
emailXpackService.saveInstance(taskInstance);
}
private void error(GlobalTaskInstance taskInstance, Throwable t) {
taskInstance.setStatus(ERROR);
taskInstance.setInfo(t.getMessage());
EmailXpackService emailXpackService = SpringContextUtil.getBean(EmailXpackService.class);
emailXpackService.saveInstance(taskInstance);
}
@@ -99,29 +113,42 @@ public class EmailTaskHandler extends TaskHandler implements Job {
@Async
public void sendReport(GlobalTaskInstance taskInstance, XpackEmailTemplateDTO emailTemplateDTO, SysUserEntity user) {
EmailXpackService emailXpackService = SpringContextUtil.getBean(EmailXpackService.class);
String fileId = emailXpackService.print(panelUrl(emailTemplateDTO.getPanelId()), tokenByUser(user));
// 下面继续执行发送邮件的略记
String recipients = emailTemplateDTO.getRecipients();
byte[] content = emailTemplateDTO.getContent();
EmailService emailService = SpringContextUtil.getBean(EmailService.class);
String contentStr = "";
byte[] bytes = null;
if (ObjectUtils.isNotEmpty(content)) {
try {
try{
byte[] bytes = emailXpackService.printData(panelUrl(emailTemplateDTO.getPanelId()), tokenByUser(user), buildPixel(emailTemplateDTO));
// 下面继续执行发送邮件的
String recipients = emailTemplateDTO.getRecipients();
byte[] content = emailTemplateDTO.getContent();
EmailService emailService = SpringContextUtil.getBean(EmailService.class);
String contentStr = "";
if (ObjectUtils.isNotEmpty(content)) {
contentStr = new String(content, "UTF-8");
FileService fileService = SpringContextUtil.getBean(FileService.class);
bytes = fileService.loadFileAsBytes(fileId);
emailService.sendWithImage(recipients, emailTemplateDTO.getTitle(), contentStr, bytes);
changeStatus(taskInstance, SUCCESS);
} catch (Exception e) {
changeStatus(taskInstance, ERROR);
LogUtil.error(e.getMessage(), e);
throw new RuntimeException(e);
}
emailService.sendWithImage(recipients, emailTemplateDTO.getTitle(), contentStr, bytes);
success(taskInstance);
}catch (Exception e) {
error(taskInstance, e);
LogUtil.error(e.getMessage(), e);
}
}
private XpackPixelEntity buildPixel(XpackEmailTemplateDTO emailTemplateDTO) {
XpackPixelEntity pixelEntity = new XpackPixelEntity();
String pixelStr = emailTemplateDTO.getPixel();
if (StringUtils.isBlank(pixelStr)) return null;
String[] arr = pixelStr.split("\\*");
if (arr.length != 2) return null;
try {
int x = Integer.parseInt(arr[0]);
int y = Integer.parseInt(arr[1]);
pixelEntity.setX(String.valueOf(x));
pixelEntity.setY(String.valueOf(y));
return pixelEntity;
}catch (Exception e) {
return null;
}
}
private String tokenByUser(SysUserEntity user) {
@@ -132,19 +159,8 @@ public class EmailTaskHandler extends TaskHandler implements Job {
}
private String panelUrl(String panelId) {
InetAddress ip = null;
String hostAddress = null;
try {
ip = InetAddress.getLocalHost();
hostAddress = ip.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
Environment environment = SpringContextUtil.getBean(Environment.class);
Integer port = environment.getProperty("server.port", Integer.class);
String url = "http://" + hostAddress + ":"+port + "/#/preview/" + panelId;
return url;
String domain = ServletUtils.domain();
return domain + "/#/preview/" + panelId;
}
}

View File

@@ -3,23 +3,25 @@ package io.dataease.plugins.server;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.dataease.commons.utils.AuthUtils;
import io.dataease.commons.utils.BeanUtils;
import io.dataease.commons.utils.PageUtils;
import io.dataease.commons.utils.Pager;
import io.dataease.commons.exception.DEException;
import io.dataease.commons.utils.*;
import io.dataease.plugins.common.entity.GlobalTaskEntity;
import io.dataease.plugins.common.entity.GlobalTaskInstance;
import io.dataease.plugins.common.entity.XpackGridRequest;
import io.dataease.plugins.config.SpringContextUtil;
import io.dataease.plugins.xpack.email.dto.request.XpackEmailCreate;
import io.dataease.plugins.xpack.email.dto.request.XpackEmailTaskRequest;
import io.dataease.plugins.xpack.email.dto.request.XpackEmailViewRequest;
import io.dataease.plugins.xpack.email.dto.request.XpackPixelEntity;
import io.dataease.plugins.xpack.email.dto.response.XpackTaskGridDTO;
import io.dataease.plugins.xpack.email.dto.response.XpackTaskInstanceDTO;
import io.dataease.plugins.xpack.email.service.EmailXpackService;
import io.dataease.service.ScheduleService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Api(tags = "xpack定时报告")
@@ -70,4 +72,78 @@ public class XEmailTaskServer {
xpackEmailCreate.setRequest(taskForm);
return xpackEmailCreate;
}
@PostMapping("/preview")
public String preview(@RequestBody XpackEmailViewRequest request) {
EmailXpackService emailXpackService = SpringContextUtil.getBean(EmailXpackService.class);
String panelId = request.getPanelId();
String content = request.getContent();
String url = ServletUtils.domain() + "/#/preview/" + panelId;
String token = ServletUtils.getToken();
String fileId = null;
try {
fileId = emailXpackService.print(url, token, buildPixel(request.getPixel()));
} catch (Exception e) {
LogUtil.error(e);
DEException.throwException("预览失败,请联系管理员");
}
String imageUrl = "/system/ui/image/" + fileId;
String html = "<div>" +
"<h2>"+content+"</h2>" +
"<img style='width: 100%;' id='"+panelId+"' src='"+imageUrl+"' />" +
"</div>";
return html;
}
@PostMapping("/delete/{taskId}")
public void delete(@PathVariable Long taskId) {
EmailXpackService emailXpackService = SpringContextUtil.getBean(EmailXpackService.class);
try {
XpackEmailTaskRequest request = emailXpackService.taskForm(taskId);
GlobalTaskEntity globalTaskEntity = BeanUtils.copyBean(new GlobalTaskEntity(), request);
scheduleService.deleteSchedule(globalTaskEntity);
emailXpackService.delete(taskId);
} catch (Exception e) {
LogUtil.error(e);
DEException.throwException(e);
}
}
@PostMapping("/queryInstancies/{goPage}/{pageSize}")
public Pager<List<XpackTaskInstanceDTO>> instancesGrid(@PathVariable int goPage, @PathVariable int pageSize, @RequestBody XpackGridRequest request) {
EmailXpackService emailXpackService = SpringContextUtil.getBean(EmailXpackService.class);
Page<Object> page = PageHelper.startPage(goPage, pageSize, true);
List<XpackTaskInstanceDTO> instances = emailXpackService.taskInstanceGrid(request);
Pager<List<XpackTaskInstanceDTO>> listPager = PageUtils.setPageInfo(page, instances);
return listPager;
}
@PostMapping("/execInfo/{instanceId}")
public String execInfo(@PathVariable Long instanceId) {
EmailXpackService emailXpackService = SpringContextUtil.getBean(EmailXpackService.class);
GlobalTaskInstance instanceForm = emailXpackService.instanceForm(instanceId);
return instanceForm.getInfo();
}
private XpackPixelEntity buildPixel(String pixel) {
if (StringUtils.isBlank(pixel)) return null;
String[] arr = pixel.split("\\*");
if (arr.length != 2) return null;
try {
XpackPixelEntity result = new XpackPixelEntity();
int x = Integer.parseInt(arr[0]);
int y = Integer.parseInt(arr[1]);
result.setX(String.valueOf(x));
result.setY(String.valueOf(y));
return result;
}catch (Exception e) {
return null;
}
}
}

View File

@@ -85,7 +85,6 @@ public class EmailService {
JavaMailSenderImpl driver = driver(mailInfo);
MimeMessage mimeMessage = driver.createMimeMessage();
MimeMessageHelper helper = null;
MimeBodyPart image = new MimeBodyPart();
DataHandler png = new DataHandler(new ByteArrayDataSource(bytes, "image/png"));
@@ -93,8 +92,8 @@ public class EmailService {
String uuid = UUID.randomUUID().toString();
MimeBodyPart text = new MimeBodyPart();
try {
text.setContent(content + "<br/><img src='cid:"+uuid+"' />", "text/html; charset=gb2312");
// text.setText(, "text/html; charset=gb2312");
text.setContent("<h2>"+content+"</h2>" + "<br/><img src='cid:"+uuid+"' />", "text/html; charset=gb2312");
image.setDataHandler(png);
image.setContentID(uuid);
MimeMultipart multipart = new MimeMultipart();