DomainOrderService.java 21 KB

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