| 1 |
package com.paymentlink.service; |
| 2 |
|
| 3 |
import jakarta.annotation.PostConstruct; |
| 4 |
import org.slf4j.Logger; |
| 5 |
import org.slf4j.LoggerFactory; |
| 6 |
import org.springframework.beans.factory.annotation.Value; |
| 7 |
import org.springframework.http.ResponseEntity; |
| 8 |
import org.springframework.stereotype.Service; |
| 9 |
import org.springframework.web.client.RestTemplate; |
| 10 |
|
| 11 |
@Service |
| 12 |
public class DnsService { |
| 13 |
|
| 14 |
private static final Logger logger = LoggerFactory.getLogger(DnsService.class); |
| 15 |
|
| 16 |
@Value("${cloudns.auth.id:}") |
| 17 |
private String authId; |
| 18 |
|
| 19 |
@Value("${cloudns.auth.password:}") |
| 20 |
private String authPassword; |
| 21 |
|
| 22 |
@Value("${app.tld:ironpath.ai}") |
| 23 |
private String tld; |
| 24 |
|
| 25 |
private final NodeIdService nodeIdService; |
| 26 |
private final RestTemplate restTemplate = new RestTemplate(); |
| 27 |
|
| 28 |
public DnsService(NodeIdService nodeIdService) { |
| 29 |
this.nodeIdService = nodeIdService; |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
* Update or create DNS record on startup |
| 34 |
*/ |
| 35 |
@PostConstruct |
| 36 |
public void updateOrCreateDNSRecord() { |
| 37 |
if (authId == null || authId.isEmpty() || authPassword == null || authPassword.isEmpty()) { |
| 38 |
logger.warn("CloudNS credentials not configured, skipping DNS update"); |
| 39 |
return; |
| 40 |
} |
| 41 |
|
| 42 |
try { |
| 43 |
String serverIP = getServerIP(); |
| 44 |
String shortId = nodeIdService.getShortId(); |
| 45 |
|
| 46 |
logger.info("Updating DNS record for {} with IP {}", shortId, serverIP); |
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
logger.info("DNS record update completed (simulated)"); |
| 55 |
|
| 56 |
} catch (Exception e) { |
| 57 |
logger.error("Failed to update DNS record", e); |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
|
| 62 |
* Get server's public IP address |
| 63 |
*/ |
| 64 |
private String getServerIP() { |
| 65 |
try { |
| 66 |
|
| 67 |
String url = "https://api.ipify.org?format=text"; |
| 68 |
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); |
| 69 |
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) { |
| 70 |
return response.getBody().trim(); |
| 71 |
} |
| 72 |
} catch (Exception e) { |
| 73 |
logger.warn("Failed to get IP from ipify, trying fallback", e); |
| 74 |
} |
| 75 |
|
| 76 |
try { |
| 77 |
|
| 78 |
String url = "https://ipapi.co/ip/"; |
| 79 |
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); |
| 80 |
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) { |
| 81 |
return response.getBody().trim(); |
| 82 |
} |
| 83 |
} catch (Exception e) { |
| 84 |
logger.error("Failed to get IP from fallback", e); |
| 85 |
} |
| 86 |
|
| 87 |
throw new RuntimeException("Could not determine server IP"); |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
|