DomainOrderService.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. package com.izouma.nineth.service;
  2. import com.alibaba.excel.util.StringUtils;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alibaba.fastjson.TypeReference;
  5. import com.google.zxing.WriterException;
  6. import com.izouma.nineth.config.RedisKeys;
  7. import com.izouma.nineth.domain.Asset;
  8. import com.izouma.nineth.domain.DomainOrder;
  9. import com.izouma.nineth.domain.FileObject;
  10. import com.izouma.nineth.domain.User;
  11. import com.izouma.nineth.dto.PageQuery;
  12. import com.izouma.nineth.enums.AssetStatus;
  13. import com.izouma.nineth.enums.CollectionStatus;
  14. import com.izouma.nineth.enums.OrderStatus;
  15. import com.izouma.nineth.enums.PayMethod;
  16. import com.izouma.nineth.exception.BusinessException;
  17. import com.izouma.nineth.repo.AssetRepo;
  18. import com.izouma.nineth.repo.DomainOrderRepo;
  19. import com.izouma.nineth.repo.UserRepo;
  20. import com.izouma.nineth.service.storage.StorageService;
  21. import com.izouma.nineth.utils.ImageUtils;
  22. import com.izouma.nineth.utils.JpaUtils;
  23. import com.izouma.nineth.utils.SecurityUtils;
  24. import lombok.AllArgsConstructor;
  25. import lombok.extern.slf4j.Slf4j;
  26. import org.apache.commons.lang3.RandomStringUtils;
  27. import org.springframework.data.annotation.Transient;
  28. import org.springframework.data.domain.Page;
  29. import org.springframework.data.domain.PageRequest;
  30. import org.springframework.data.domain.Pageable;
  31. import org.springframework.data.domain.Sort;
  32. import org.springframework.data.redis.core.BoundValueOperations;
  33. import org.springframework.data.redis.core.RedisTemplate;
  34. import org.springframework.stereotype.Service;
  35. import javax.imageio.ImageIO;
  36. import java.awt.*;
  37. import java.awt.image.BufferedImage;
  38. import java.io.ByteArrayInputStream;
  39. import java.io.ByteArrayOutputStream;
  40. import java.io.IOException;
  41. import java.io.InputStream;
  42. import java.math.BigDecimal;
  43. import java.text.SimpleDateFormat;
  44. import java.time.LocalDateTime;
  45. import java.util.*;
  46. import java.util.List;
  47. import java.util.concurrent.TimeUnit;
  48. import java.util.concurrent.atomic.AtomicBoolean;
  49. import java.util.regex.Matcher;
  50. import java.util.regex.Pattern;
  51. @Service
  52. @AllArgsConstructor
  53. @Slf4j
  54. public class DomainOrderService {
  55. private DomainOrderRepo domainOrderRepo;
  56. private ContentAuditService contentAuditService;
  57. private UserRepo userRepo;
  58. private AssetService assetService;
  59. private SysConfigService sysConfigService;
  60. private StorageService storageService;
  61. private RockRecordService rockRecordService;
  62. private AssetRepo assetRepo;
  63. private RedisTemplate<String, Object> redisTemplate;
  64. public Page<DomainOrder> all(PageQuery pageQuery) {
  65. return domainOrderRepo
  66. .findAll(JpaUtils.toSpecification(pageQuery, DomainOrder.class), JpaUtils.toPageRequest(pageQuery));
  67. }
  68. public boolean isContainChinese(String str) {
  69. if (StringUtils.isEmpty(str)) {
  70. throw new BusinessException("sms context is empty!");
  71. }
  72. Pattern p = Pattern.compile("[\u4E00-\u9FA5|\\!|\\,|\\。|\\(|\\)|\\《|\\》|\\“|\\”|\\?|\\:|\\;|\\【|\\】]");
  73. Matcher m = p.matcher(str);
  74. if (m.find()) {
  75. return true;
  76. }
  77. return false;
  78. }
  79. public DomainOrder create(Long userId, String domain, BigDecimal price, Long year) {
  80. AtomicBoolean checkPoint = checkPoint(userId);
  81. List<DomainOrder> notPaidOrders = domainOrderRepo.findAllByUserIdAndOrderStatus(userId, OrderStatus.NOT_PAID);
  82. Long superUserId = Long.valueOf(sysConfigService.getString("domain_superUserId"));
  83. if (notPaidOrders.size() > 0) {
  84. throw new BusinessException("已存在未支付订单,不可继续下单");
  85. }
  86. if (domain.contains(".uni")) {
  87. throw new BusinessException("域名后缀不符合规定.");
  88. }
  89. if (!superUserId.equals(SecurityUtils.getAuthenticatedUser().getId())) {
  90. if (isContainChinese(domain)) {
  91. throw new BusinessException("禁止注册中文域名");
  92. }
  93. if (!checkPoint.get()) {
  94. if (domain.length() < 9 || domain.length() > 20) {
  95. throw new BusinessException("四位及以下域名只能官方创建。");
  96. }
  97. } else {
  98. if (domain.length() < 8 || domain.length() > 20) {
  99. throw new BusinessException("四位及以下域名只能官方创建。");
  100. }
  101. }
  102. }
  103. String realName;
  104. int dotIndex = domain.indexOf(".");
  105. realName = domain.substring(0, dotIndex);
  106. Map<String, Object> checkResult = check(realName);
  107. if (!(Boolean) checkResult.get("result")) {
  108. throw new BusinessException(checkResult.get("reason").toString());
  109. }
  110. BigDecimal singlePrice = sysConfigService.getBigDecimal("domain_price");
  111. if (singlePrice.multiply(BigDecimal.valueOf(year)).compareTo(price) != 0) {
  112. throw new BusinessException("价格不符");
  113. }
  114. // LocalDateTime startTime = LocalDateTime.of(2023, 2, 10, 17, 0, 0);
  115. // if (LocalDateTime.now().isBefore(startTime)) {
  116. // throw new BusinessException("时间不符");
  117. // }
  118. // if (price.compareTo(BigDecimal.valueOf(40L)) != 0) {
  119. // throw new BusinessException("订单价格与配置不符,请重新下单.");
  120. // }
  121. User user = userRepo.findById(userId).orElseThrow(new BusinessException("未找到用户"));
  122. if (domain.contains(".")) {
  123. int dotIndex1 = domain.indexOf(".");
  124. domain = domain.substring(0, dotIndex1);
  125. }
  126. DomainOrder domainOrder = new DomainOrder();
  127. // domainOrder.setPic(Collections.singletonList(fileObject));
  128. domainOrder.setPicName(domain);
  129. domainOrder.setPrice(price);
  130. domainOrder.setDomainName((domain + ".nft").toLowerCase());
  131. domainOrder.setYears(year);
  132. domainOrder.setStatus(CollectionStatus.PENDING);
  133. domainOrder.setOrderStatus(OrderStatus.NOT_PAID);
  134. domainOrder.setUserId(user.getId());
  135. domainOrder.setUserAvatar(user.getAvatar());
  136. domainOrder.setUserName(user.getNickname());
  137. if (checkPoint.get()) {
  138. if (realName.length() < 5) {
  139. increaseCount(userId, 1);
  140. }
  141. }
  142. return domainOrderRepo.save(domainOrder);
  143. }
  144. public void increaseCount(Long userId, Integer count) {
  145. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.DOMAIN_COUNT + userId);
  146. if (ops.get() == null) {
  147. Boolean success = ops.setIfAbsent(0);
  148. log.info("创建redis域名统计:{}", success);
  149. }
  150. ops.increment(count);
  151. }
  152. public void decreaseCount(Long userId) {
  153. increaseCount(userId, -1);
  154. }
  155. public AtomicBoolean checkPoint(Long userId) {
  156. Map<Long, Long> collections = JSONObject.parseObject(sysConfigService
  157. .getString("domain_collection"), new TypeReference<HashMap<Long, Long>>() {
  158. });
  159. if (collections.size() == 0) {
  160. return new AtomicBoolean(false);
  161. }
  162. List<AssetStatus> statuses = new ArrayList<>();
  163. statuses.add(AssetStatus.NORMAL);
  164. statuses.add(AssetStatus.AUCTIONING);
  165. AtomicBoolean vipPoint = new AtomicBoolean(false);
  166. collections.forEach((k, v) -> {
  167. List<Asset> assets = assetRepo.findAllByCollectionIdAndStatusInAndUserId(k, statuses, userId);
  168. if (assets.size() > 0) {
  169. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.DOMAIN_COUNT + userId);
  170. Integer count = (Integer) ops.get();
  171. if (count != null) {
  172. if (count < v) {
  173. vipPoint.set(true);
  174. }
  175. } else {
  176. vipPoint.set(true);
  177. }
  178. }
  179. });
  180. return vipPoint;
  181. }
  182. public Map<String, Object> check(String domain) {
  183. AtomicBoolean checkPoint = checkPoint(SecurityUtils.getAuthenticatedUser().getId());
  184. Map<String, Object> result = new HashMap<>();
  185. Long superUserId = Long.valueOf(sysConfigService.getString("domain_superUserId"));
  186. String visibleDomain = domain;
  187. if (domain.contains(".uni")) {
  188. result.put("result", false);
  189. result.put("reason", "禁止使用.uni");
  190. return result;
  191. }
  192. if (!domain.contains(".nft")) {
  193. visibleDomain = domain + ".nft";
  194. }
  195. List<String> keywords = Arrays.asList(sysConfigService.getString("domain_keyword").split(","));
  196. if (!superUserId.equals(SecurityUtils.getAuthenticatedUser().getId())) {
  197. if (keywords.stream().anyMatch(keyword -> org.apache.commons.lang.StringUtils.equals(keyword, domain))) {
  198. result.put("result", false);
  199. result.put("reason", "包含敏感关键字");
  200. return result;
  201. }
  202. if (!checkPoint.get()) {
  203. if (visibleDomain.length() < 9 || visibleDomain.length() > 20) {
  204. result.put("result", false);
  205. result.put("reason", "域名长度不合规");
  206. return result;
  207. }
  208. } else {
  209. if (visibleDomain.length() < 8 || visibleDomain.length() > 20) {
  210. result.put("result", false);
  211. result.put("reason", "域名长度不合规");
  212. return result;
  213. }
  214. }
  215. if (!contentAuditService.auditText(domain)) {
  216. result.put("result", false);
  217. result.put("reason", "该域名内容不合规");
  218. return result;
  219. }
  220. }
  221. Integer count = domainOrderRepo
  222. .countAllByDomainNameEqualsAndOrderStatusNot(visibleDomain, OrderStatus.CANCELLED);
  223. if (count > 0) {
  224. result.put("result", false);
  225. result.put("reason", "该域名已被注册");
  226. return result;
  227. }
  228. result.put("result", true);
  229. result.put("reason", "可以注册");
  230. return result;
  231. }
  232. public List<Map<String, Object>> search(String domain) {
  233. if (domain.contains(".")) {
  234. int dotIndex = domain.indexOf(".");
  235. domain = domain.substring(0, dotIndex);
  236. }
  237. Pageable pageable = PageRequest.of(0, 10, Sort.by("createdAt").descending());
  238. List<DomainOrder> used = domainOrderRepo.searchUsedDomain("%" + domain + "%", OrderStatus.CANCELLED, pageable)
  239. .getContent();
  240. String n = domain.substring(domain.length() - 1);
  241. List<Map<String, Object>> recommend = new ArrayList<>();
  242. for (int i = 0; i < 100; i++) {
  243. if (i != 0) {
  244. domain = domain + n;
  245. }
  246. Map<String, Object> checkResult = check(domain);
  247. if ((Boolean) checkResult.get("result")) {
  248. Map<String, Object> sold = new HashMap<>();
  249. sold.put("domain", (domain + ".nft").toLowerCase());
  250. sold.put("sold", false);
  251. recommend.add(sold);
  252. }
  253. if (recommend.size() > 2) {
  254. break;
  255. }
  256. }
  257. List<Map<String, Object>> result = new ArrayList<>(recommend);
  258. used.forEach(domainOrder -> {
  259. Map<String, Object> sold = new HashMap<>();
  260. if (!domainOrder.getDomainName().contains(".uni")) {
  261. sold.put("domain", domainOrder.getDomainName().toLowerCase());
  262. sold.put("endTime", domainOrder.getEndTime());
  263. sold.put("sold", true);
  264. result.add(sold);
  265. }
  266. });
  267. return result;
  268. }
  269. @Transient
  270. public void notify(Long id, PayMethod payMethod, String transactionId) throws FontFormatException, IOException, WriterException {
  271. DomainOrder domainOrder = domainOrderRepo.findById(id).orElseThrow(new BusinessException("未找到星图"));
  272. if (!domainOrder.getOrderStatus().equals(OrderStatus.NOT_PAID)) {
  273. throw new BusinessException("订单已经处理");
  274. }
  275. BufferedImage img = domainImg(domainOrder.getDomainName());
  276. ByteArrayOutputStream os = new ByteArrayOutputStream();
  277. ImageIO.write(img, "jpg", os);
  278. InputStream input = new ByteArrayInputStream(os.toByteArray());
  279. String path = "image/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  280. + RandomStringUtils.randomAlphabetic(8) + ".jpg";
  281. String realUrl = storageService.uploadFromInputStream(input, path);
  282. FileObject fileObject = new FileObject();
  283. fileObject.setName(domainOrder.getDomainName());
  284. fileObject.setType("image/jpeg");
  285. fileObject.setUrl(realUrl);
  286. domainOrder.setOrderStatus(OrderStatus.FINISH);
  287. domainOrder.setPayMethod(payMethod);
  288. domainOrder.setPic(Collections.singletonList(fileObject));
  289. domainOrder.setTransactionId(transactionId);
  290. domainOrder.setStatus(CollectionStatus.SUCCESS);
  291. domainOrder.setCreateAssetId(createAsset(domainOrder));
  292. domainOrder.setEndTime(LocalDateTime.now().plusYears(domainOrder.getYears()));
  293. domainOrderRepo.save(domainOrder);
  294. rockRecordService.addRock(domainOrder.getUserId(), domainOrder.getPrice(), "购买");
  295. }
  296. public void cancel(DomainOrder domainOrder) {
  297. domainOrder.setOrderStatus(OrderStatus.CANCELLED);
  298. domainOrder.setStatus(CollectionStatus.FAIL);
  299. if (domainOrder.getPicName().length() < 5) {
  300. decreaseCount(domainOrder.getUserId());
  301. }
  302. domainOrderRepo.save(domainOrder);
  303. }
  304. public Long createAsset(DomainOrder domainOrder) {
  305. return assetService.createAsset(domainOrder, userRepo.findById(domainOrder.getUserId())
  306. .orElseThrow(new BusinessException("无用户记录")), null, domainOrder.getPrice(), "域名", null, false).getId();
  307. }
  308. public BufferedImage domainImg(String domain) throws IOException, FontFormatException, WriterException {
  309. String domainName;
  310. if (domain.contains(".")) {
  311. int dotIndex = domain.indexOf(".");
  312. domainName = domain.substring(0, dotIndex).toUpperCase();
  313. } else {
  314. domainName = domain.toUpperCase();
  315. }
  316. InputStream is1 = this.getClass()
  317. .getResourceAsStream("/font/VonwaonBitmap_16pxLite.ttf");
  318. Font font1 = Font.createFont(Font.TRUETYPE_FONT, is1);
  319. is1.close();
  320. InputStream is2 = this.getClass()
  321. .getResourceAsStream("/font/VonwaonBitmap_12pxLite.ttf");
  322. Font font2 = Font.createFont(Font.TRUETYPE_FONT, is2);
  323. is2.close();
  324. int length = domainName.length();
  325. BufferedImage shareImg;
  326. if (length <= 2) {
  327. InputStream is3 = this.getClass().getResourceAsStream("/static/img/png_jing.png");
  328. shareImg = ImageIO.read(is3);
  329. is3.close();
  330. } else if (length <= 4) {
  331. InputStream is3 = this.getClass().getResourceAsStream("/static/img/png_lv.png");
  332. shareImg = ImageIO.read(is3);
  333. is3.close();
  334. } else {
  335. InputStream is3 = this.getClass().getResourceAsStream("/static/img/png_zi.png");
  336. shareImg = ImageIO.read(is3);
  337. is3.close();
  338. }
  339. BufferedImage result = new BufferedImage(shareImg.getWidth(), shareImg.getHeight(), BufferedImage.TYPE_INT_RGB);
  340. Graphics2D g = result.createGraphics();
  341. g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
  342. // g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  343. // g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
  344. g.setComposite(AlphaComposite.SrcOver);
  345. g.drawImage(shareImg, 0, 0, null);
  346. // BufferedImage avatarImg = ImageUtils.makeRoundedCorner(ImageUtils.scale(ImageIO.read(new URL(user.getAvatar())),
  347. // 80, 80,
  348. // ImageUtils.Fit.COVER), 40);
  349. // g.drawImage(avatarImg, 334, 136, null);
  350. int domainLength = domainName.length();
  351. if (domainLength > 10) {
  352. g.setColor(new Color(255, 255, 255));
  353. Font topFont = font1.deriveFont(Font.PLAIN, 130f);
  354. Font downFont = font2.deriveFont(Font.BOLD, 36f);
  355. int subIndex = domainLength / 3;
  356. String str1 = domainName.substring(0, subIndex);
  357. String str2 = domainName.substring(subIndex, subIndex + subIndex);
  358. String str3 = domainName.substring(subIndex + subIndex, domainLength);
  359. ImageUtils.drawCenteredString(g, str1, new Rectangle(0, 180, shareImg
  360. .getWidth(), 86), topFont);
  361. ImageUtils.drawCenteredString(g, str2, new Rectangle(0, 300, shareImg
  362. .getWidth(), 86), topFont);
  363. ImageUtils.drawCenteredString(g, str3, new Rectangle(0, 420, shareImg
  364. .getWidth(), 86), topFont);
  365. ImageUtils.drawCenteredString(g, ".NFT", new Rectangle(0, 540, shareImg
  366. .getWidth(), 86), topFont);
  367. g.setColor(new Color(255, 255, 255));
  368. ImageUtils.drawCenteredString(g, domain, new Rectangle(0, 650, shareImg
  369. .getWidth(), 12), downFont);
  370. }
  371. if (domainLength > 5 & domainLength <= 10) {
  372. g.setColor(new Color(255, 255, 255));
  373. Font topFont = font1.deriveFont(Font.PLAIN, 190f);
  374. Font downFont = font2.deriveFont(Font.BOLD, 36f);
  375. int subIndex = domainLength / 2;
  376. String str1 = domainName.substring(0, subIndex);
  377. String str2 = domainName.substring(subIndex, domainLength);
  378. ImageUtils.drawCenteredString(g, str1, new Rectangle(0, 180, shareImg
  379. .getWidth(), 86), topFont);
  380. ImageUtils.drawCenteredString(g, str2, new Rectangle(0, 350, shareImg
  381. .getWidth(), 86), topFont);
  382. ImageUtils.drawCenteredString(g, ".NFT", new Rectangle(0, 520, shareImg
  383. .getWidth(), 86), topFont);
  384. g.setColor(new Color(255, 255, 255));
  385. ImageUtils.drawCenteredString(g, domain, new Rectangle(0, 650, shareImg
  386. .getWidth(), 12), downFont);
  387. }
  388. if (domainLength <= 5) {
  389. g.setColor(new Color(255, 255, 255));
  390. Font topFont = font1.deriveFont(Font.PLAIN, 240f);
  391. Font downFont = font2.deriveFont(Font.BOLD, 36f);
  392. ImageUtils.drawCenteredString(g, domainName, new Rectangle(17, 220, shareImg
  393. .getWidth(), 86), topFont);
  394. ImageUtils.drawCenteredString(g, ".NFT", new Rectangle(-10, 420, shareImg
  395. .getWidth(), 86), topFont);
  396. g.setColor(new Color(255, 255, 255));
  397. ImageUtils.drawCenteredString(g, domain, new Rectangle(0, 620, shareImg
  398. .getWidth(), 12), downFont);
  399. }
  400. //二维码
  401. // QRCodeWriter qrCodeWriter = new QRCodeWriter();
  402. // Map<EncodeHintType, Object> hints = new HashMap<>();
  403. // hints.put(EncodeHintType.MARGIN, 2);
  404. // BitMatrix bitMatrix = qrCodeWriter
  405. // .encode(env.getProperty("general.host") + "/wx/share?invitor=" + user.getId(),
  406. // BarcodeFormat.QR_CODE, 252, 252, hints);
  407. // g.drawImage(MatrixToImageWriter.toBufferedImage(bitMatrix), 250, 386, null);
  408. return result;
  409. }
  410. }