sakthivikram/geo-location
0
1package com.georeport.service;2 3import com.twilio.Twilio;4import com.twilio.rest.api.v2010.account.Message;5import com.twilio.type.PhoneNumber;6import jakarta.annotation.PostConstruct;7import org.slf4j.Logger;8import org.slf4j.LoggerFactory;9import org.springframework.beans.factory.annotation.Autowired;10import org.springframework.beans.factory.annotation.Value;11import org.springframework.stereotype.Service;12 13@Service14public class TwilioSmsService implements SmsService {15 private static final Logger logger = LoggerFactory.getLogger(TwilioSmsService.class);16 17 @Autowired18 private SmsBroadcastService smsBroadcastService;19 20 @Value("${twilio.account-sid}")21 private String accountSid;22 23 @Value("${twilio.auth-token}")24 private String authToken;25 26 @Value("${twilio.phone-number}")27 private String fromPhoneNumber;28 29 @PostConstruct30 public void init() {31 if (isConfigured()) {32 Twilio.init(accountSid, authToken);33 logger.info("Twilio initialized with Account SID: {}", accountSid);34 } else {35 logger.warn("Twilio is not fully configured. SMS sending will be disabled or fail.");36 }37 }38 39 @Override40 public void sendSms(String to, String messageContent) {41 // Always broadcast to Dev Dashboard for real-time testing42 smsBroadcastService.broadcastSms(to, messageContent);43 44 if (!isConfigured()) {45 logger.info("SMS SIMULATION: To: {}, Content: {}", to, messageContent);46 return;47 }48 49 try {50 // Twilio strictly requires E.164 formatting (+CountryCodeNumber)51 String formattedPhone = to.trim();52 if (!formattedPhone.startsWith("+")) {53 formattedPhone = "+91" + formattedPhone; // Default to India (+91)54 }55 56 Message message = Message.creator(57 new PhoneNumber(formattedPhone),58 new PhoneNumber(fromPhoneNumber),59 messageContent60 ).create();61 62 logger.info("SMS sent to {}. SID: {}", formattedPhone, message.getSid());63 } catch (Exception e) {64 logger.error("Failed to send SMS to {}: {}", to, e.getMessage());65 throw new RuntimeException("SMS sending failed: " + e.getMessage());66 }67 }68 69 private boolean isConfigured() {70 return accountSid != null && !accountSid.isEmpty() && !accountSid.contains("YOUR_ACCOUNT_SID") &&71 authToken != null && !authToken.isEmpty() && !authToken.contains("YOUR_AUTH_TOKEN") &&72 fromPhoneNumber != null && !fromPhoneNumber.isEmpty() && !fromPhoneNumber.contains("YOUR_TWILIO_NUMBER");73 }74}75 