package ir.peeco.pline.init; import ir.peeco.pline.models.*; import ir.peeco.pline.models.fax.TblFaxSetting; import ir.peeco.pline.models.outbounRoutes.TblOutboundRoute; import ir.peeco.pline.models.outbounRoutes.TblOutboundRoutePattern; import ir.peeco.pline.models.plineUser.TblPlineUser; import ir.peeco.pline.models.sipUsers.TblSipUser; import ir.peeco.pline.plineServer.LicenseService; import ir.peeco.pline.plineServer.DialableNumberConflictService; import ir.peeco.pline.plineServer.PlineTools; import ir.peeco.pline.plineServer.fileGeneratorTools.File_Generator; import ir.peeco.pline.repositories.fax.FaxSettingsRepository; import ir.peeco.pline.repositories.outboundRoutes.OutboundRoutePatternsRepository; import ir.peeco.pline.repositories.outboundRoutes.OutboundRouteRepository; import ir.peeco.pline.repositories.plineUser.PlineUsersRepository; import ir.peeco.pline.repositories.*; import ir.peeco.pline.repositories.cdr.CdrSettingsRepository; import ir.peeco.pline.plineServer.tools.GlobalTools; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.JdbcTemplate; @Configuration public class Initializer { @Value("${spring.banner.location}") private String banner; @Value("${pline.app_name}") private String appName; private PlineUsersRepository plineUsersRepository; private SipProfilesRepository sipProfilesRepository; private SipProfileDetailsRepository profileDetailsRepository; private SipParameterRepository parameterRepository; private File_Generator fileGenerator; private SipUsersRepository sipUsersRepository; private SipUserGroupsRepository sipUserGroupsRepository; private HttpRepository httpRepository; private MusicOnHoldsRepository musicOnHoldsRepository; private CdrSettingsRepository cdrSettingsRepository; private LicenseService licenseService; private DialableNumberConflictService dialableNumberConflictService; private OutboundRouteRepository outboundRouteRepository; private OutboundRoutePatternsRepository outboundRoutePatternsRepository; private FaxSettingsRepository faxSettingsRepository; private Environment env; private AppSettingsRepository appSettingsRepository; private JdbcTemplate jdbcTemplate; @Autowired public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Autowired public void setAppSettingsRepository(AppSettingsRepository appSettingsRepository) { this.appSettingsRepository = appSettingsRepository; } @Autowired public void setEnv(Environment env) { this.env = env; } @Autowired public void setFaxSettingsRepository(FaxSettingsRepository faxSettingsRepository) { this.faxSettingsRepository = faxSettingsRepository; } @Autowired public void setOutboundRoutePatternsRepository(OutboundRoutePatternsRepository outboundRoutePatternsRepository) { this.outboundRoutePatternsRepository = outboundRoutePatternsRepository; } @Autowired public void setOutboundRouteRepository(OutboundRouteRepository outboundRouteRepository) { this.outboundRouteRepository = outboundRouteRepository; } @Autowired public void setLicenseService(LicenseService licenseService) { this.licenseService = licenseService; } @Autowired public void setDialableNumberConflictService(DialableNumberConflictService dialableNumberConflictService) { this.dialableNumberConflictService = dialableNumberConflictService; } @Autowired public void setCdrSettingsRepository(CdrSettingsRepository cdrSettingsRepository) { this.cdrSettingsRepository = cdrSettingsRepository; } @Autowired public void setMusicOnHoldsRepository(MusicOnHoldsRepository musicOnHoldsRepository) { this.musicOnHoldsRepository = musicOnHoldsRepository; } @Autowired public void setHttpRepository(HttpRepository httpRepository) { this.httpRepository = httpRepository; } @Autowired public void setSipUserGroupsRepository(SipUserGroupsRepository sipUserGroupsRepository) { this.sipUserGroupsRepository = sipUserGroupsRepository; } @Autowired public void setSipUsersRepository(SipUsersRepository sipUsersRepository) { this.sipUsersRepository = sipUsersRepository; } @Autowired public void setFileGenerator(File_Generator fileGenerator) { this.fileGenerator = fileGenerator; } @Autowired public void setParameterRepository(SipParameterRepository parameterRepository) { this.parameterRepository = parameterRepository; } @Autowired public void setUsersRepository(PlineUsersRepository usersRepository) { this.plineUsersRepository = usersRepository; } @Autowired public void setSipProfilesRepository(SipProfilesRepository sipProfilesRepository) { this.sipProfilesRepository = sipProfilesRepository; } @Autowired public void setProfileDetailsRepository(SipProfileDetailsRepository profileDetailsRepository) { this.profileDetailsRepository = profileDetailsRepository; } private PlineTools plineTools; @Autowired public void setPlineTools(PlineTools plineTools) { this.plineTools = plineTools; } @Bean @Order(20) protected CommandLineRunner init() { return args -> { removeObsoleteManyToOneUniqueConstraints(); licenseService.checkLicense(); if (parameterRepository.count() == 0) { Iterable iterator = Arrays.asList(GlobalTools.getPjSipParameters()); parameterRepository.saveAll(iterator); } if (httpRepository.count() == 0 /* && plineTools.CreateWebRtcCert() != null */) { var http = new TblHttp(); http.setEnable(true); http.setEnabled(true); http.setTlsEnable(false); http.setTlsCertFile(plineTools.getConfigPath() + "keys/p-line.crt"); http.setTlsPrivateKey(plineTools.getConfigPath() + "keys/p-line.key"); httpRepository.save(http); } String username = env.getProperty("spring.datasource.username"); String password = env.getProperty("spring.datasource.password"); String url = env.getProperty("spring.datasource.url"); if (cdrSettingsRepository.count() == 0) { var cdr = new TblCdrSetting(); cdr.setHostname(GlobalTools.getHostnameDatabase(url)); cdr.setPort(GlobalTools.getPortDatabase(url)); cdr.setDbName(GlobalTools.getDatabaseName(url)); cdr.setDbUser(username); cdr.setDbPassword(password); cdr.setTimezone(GlobalTools.getTimeZone()); cdrSettingsRepository.save(cdr); } else { var cdr = cdrSettingsRepository.findById(1L); cdr.ifPresent(c -> { c.setHostname(GlobalTools.getHostnameDatabase(url)); c.setPort(GlobalTools.getPortDatabase(url)); c.setDbUser(username); c.setDbPassword(password); c.setDbName(GlobalTools.getDatabaseName(url)); c.setTimezone(GlobalTools.getTimeZone()); cdrSettingsRepository.save(c); }); } if (appSettingsRepository.count() == 0) { appSettingsRepository.save(new TblAppSettings()); } if (plineUsersRepository.findByUsername("admin").isEmpty()) { TblPlineUser plineUser = new TblPlineUser(); plineUser.setFullname("Administrator"); plineUser.setUsername("admin"); plineUser.setPassword(GlobalTools.MD5("admin")); plineUser.setEnable(true); plineUser.setRoles("ADMIN,CLIENT"); plineUsersRepository.save(plineUser); } // var p = plineUsersRepository.findByUsername("admin").get(); // p.setPassword(GlobalTools.MD5("admin")); // plineUsersRepository.save(p); if (sipProfilesRepository.count() == 0 || sipUserGroupsRepository.countAllByName("Default") == 0 || sipUsersRepository.findByUid("1001").isEmpty()) { TblSipProfile profileU = getOrCreateSipProfile("Default SIP Profile UDP", ".:: Default Sip User Profile UDP ::."); TblSipProfile profileT = getOrCreateSipProfile("Default SIP Profile TCP", ".:: Default Webrtc Profile TCP ::."); TblSipProfile profileWebrtc = getOrCreateSipProfile("Default Webrtc Profile", ".:: Default Webrtc Profile ::."); TblSipProfile profileCisco = getOrCreateSipProfile("Default Cisco Profile", ".:: Default Cisco Profile ::."); Object[][] def = new Object[][] { { profileU, "endpoint", "context", "default" }, { profileU, "endpoint", "allow", "[\"ulaw\",\"alaw\",\"gsm\",\"h264\",\"h263\"]" }, { profileU, "endpoint", "device_state_busy_at", "2" }, { profileU, "endpoint", "dtmf_mode", "auto" }, { profileU, "endpoint", "subscribe_context", appName + "-subscribe" }, { profileU, "endpoint", "sdp_owner", appName }, { profileU, "endpoint", "sdp_session", appName }, { profileU, "endpoint", "sdp_session", appName }, { profileU, "endpoint", "direct_media", "no" }, // No cisco force { profileU, "endpoint", "rewrite_contact", "yes" }, // No cisco force { profileU, "endpoint", "force_rport", "yes" }, // No cisco force { profileU, "endpoint", "rtp_symmetric", "yes" }, { profileU, "endpoint", "rewrite_contact", "no" }, { profileU, "endpoint", "force_rport", "no" }, { profileU, "endpoint", "t38_udptl_maxdatagram", "400" }, { profileU, "endpoint", "fax_detect", "yes" }, { profileU, "endpoint", "t38_udptl_ec", "redundancy" }, { profileU, "auth", "auth_type", "userpass" }, { profileU, "aor", "max_contacts", "1" }, // No cisco force { profileT, "aor", "remove_existing", "yes" }, { profileU, "aor", "qualify_frequency", "60" }, { profileU, "aor", "qualify_timeout", "3" }, { profileU, "aor", "default_expiration", "3600" }, { profileU, "transport", "protocol", "udp" }, { profileU, "transport", "bind", "0.0.0.0:5060" }, /*********************************************************************** */ { profileT, "endpoint", "context", "default" }, { profileT, "endpoint", "allow", "[\"vp8" + "\",\"gsm\",\"ulaw\",\"alaw\",\"h264\",\"h263\"]" }, { profileT, "endpoint", "device_state_busy_at", "2" }, { profileT, "endpoint", "dtmf_mode", "auto" }, { profileT, "endpoint", "subscribe_context", appName + "-subscribe" }, { profileT, "endpoint", "sdp_owner", appName }, { profileT, "endpoint", "sdp_session", appName }, { profileT, "endpoint", "sdp_session", appName }, { profileT, "endpoint", "direct_media", "no" }, // No cisco force { profileT, "endpoint", "rewrite_contact", "yes" }, // No cisco force { profileT, "endpoint", "force_rport", "yes" }, // No cisco force { profileT, "endpoint", "rtp_symmetric", "yes" }, { profileT, "endpoint", "t38_udptl_maxdatagram", "400" }, { profileT, "endpoint", "fax_detect", "yes" }, { profileT, "endpoint", "t38_udptl_ec", "redundancy" }, { profileT, "auth", "auth_type", "userpass" }, { profileT, "aor", "max_contacts", "1" }, // No cisco force { profileT, "aor", "remove_existing", "yes" }, { profileT, "aor", "qualify_frequency", "60" }, { profileT, "aor", "qualify_timeout", "3" }, { profileT, "aor", "default_expiration", "3600" }, { profileT, "transport", "protocol", "tcp" }, { profileT, "transport", "bind", "0.0.0.0:5060" }, /*********************************************************************** */ { profileWebrtc, "endpoint", "context", "default" }, { profileWebrtc, "endpoint", "device_state_busy_at", "2" }, { profileWebrtc, "endpoint", "dtmf_mode", "auto" }, { profileWebrtc, "endpoint", "subscribe_context", appName + "-subscribe" }, { profileWebrtc, "endpoint", "sdp_owner", appName }, { profileWebrtc, "endpoint", "sdp_session", appName }, { profileWebrtc, "endpoint", "sdp_session", appName }, { profileWebrtc, "endpoint", "dtls_auto_generate_cert", "yes" }, { profileWebrtc, "endpoint", "webrtc", "yes" }, { profileWebrtc, "endpoint", "allow", "[\"vp8" + "\",\"gsm\",\"ulaw\",\"alaw\",\"h264\",\"h263\"]" }, { profileWebrtc, "endpoint", "direct_media", "no" }, { profileWebrtc, "auth", "auth_type", "userpass" }, { profileWebrtc, "aor", "max_contacts", "1" }, { profileWebrtc, "aor", "remove_existing", "yes" }, { profileWebrtc, "transport", "protocol", "wss" }, { profileWebrtc, "transport", "bind", "0.0.0.0:5060" }, { profileWebrtc, "aor", "qualify_frequency", "60" }, { profileWebrtc, "aor", "qualify_timeout", "3" }, { profileWebrtc, "aor", "default_expiration", "3600" }, /*************************************************************************/ { profileCisco, "endpoint", "context", "default" }, { profileCisco, "endpoint", "allow", "[\"ulaw\",\"alaw\",\"gsm\",\"h264\",\"h263\"]" }, { profileCisco, "endpoint", "device_state_busy_at", "2" }, { profileCisco, "endpoint", "dtmf_mode", "auto" }, { profileCisco, "endpoint", "subscribe_context", appName + "-subscribe" }, { profileCisco, "endpoint", "sdp_owner", appName }, { profileCisco, "endpoint", "sdp_session", appName }, { profileCisco, "endpoint", "sdp_session", appName }, { profileCisco, "endpoint", "direct_media", "no" }, // cisco force { profileCisco, "endpoint", "rewrite_contact", "no" }, // cisco force { profileCisco, "endpoint", "force_rport", "no" }, // cisco force { profileCisco, "endpoint", "rtp_symmetric", "yes" }, { profileCisco, "endpoint", "t38_udptl_maxdatagram", "400" }, { profileCisco, "endpoint", "fax_detect", "yes" }, { profileCisco, "endpoint", "t38_udptl_ec", "redundancy" }, { profileCisco, "auth", "auth_type", "userpass" }, { profileCisco, "aor", "max_contacts", "1" }, // cisco force { profileCisco, "aor", "remove_existing", "no" }, { profileCisco, "aor", "qualify_frequency", "60" }, { profileCisco, "aor", "qualify_timeout", "3" }, { profileCisco, "aor", "default_expiration", "3600" }, }; Set existingProfileDetails = new HashSet<>(); for (TblSipProfile profile : List.of(profileU, profileT, profileWebrtc, profileCisco)) { for (TblSipProfileDetails existing : profileDetailsRepository.getBySipProfileId(profile.getId())) { existingProfileDetails.add(profileDetailIdentity(existing.getSipProfile().getId(), existing.getType(), existing.getKey(), existing.getValue())); } } for (Object[] objects : def) { TblSipProfileDetails d = new TblSipProfileDetails(); d.setSipProfile((TblSipProfile) objects[0]); d.setType(objects[1].toString()); d.setKey(objects[2].toString()); d.setValue(objects[3].toString()); String identity = profileDetailIdentity(d.getSipProfile().getId(), d.getType(), d.getKey(), d.getValue()); if (existingProfileDetails.add(identity)) { profileDetailsRepository.save(d); } } var userGroup = sipUserGroupsRepository.findByName("Default"); if (userGroup == null) { userGroup = new TblSipUserGroup(); userGroup.setName("Default"); userGroup.setDescription(".:: Default ::."); sipUserGroupsRepository.save(userGroup); } if (sipUsersRepository.count() == 0) { for (int i = 1001; i <= 1050; i++) { var user = new TblSipUser(); user.setAcl(""); user.setUid(String.valueOf(i)); user.setPassword(GlobalTools.getRandomString(12)); if (i > 1024) user.setSipProfile(profileWebrtc); else user.setSipProfile(profileU); user.setSipUserGroup(userGroup); user.setCallerIdName(i + ""); user.setCallerIdNumber(String.valueOf(i)); user.setOutboundCallerIdName("[uid]"); user.setOutboundCallerIdNumber(appName + "-[uid]"); var conflicts = dialableNumberConflictService.validateSipUser(user.getUid(), null); if (conflicts.isEmpty()) { sipUsersRepository.save(user); } else { plineTools.plineLogger("Default SIP User UID conflicts with another dialable number (" + user.getUid() + "): " + String.join(", ", conflicts)); } } } // This block can run again when any default SIP entity is missing. // Keep default media initialization idempotent and preserve customer files. if (musicOnHoldsRepository.findByName("default").isEmpty()) { var music = new TblMusicOnHold(); music.setName("default"); music.setEnable(true); music.setKey("*"); music.setDescription(".:: Default ::."); music.setPaths(new String[] { "pline-hold.wav" }); musicOnHoldsRepository.save(music); } GlobalTools.createFolderIfNotExist(plineTools.getDefaultMusicOnHoldPath()); File defaultMohFile = new File(plineTools.getDefaultMusicOnHoldPath() + "/pline-hold.wav"); if (!defaultMohFile.exists()) { GlobalTools.copyFileUsingStream(GlobalTools.getBaseDir() + "/resource/pline-hold.wav", defaultMohFile.getPath()); } File moh = new File(plineTools.getMusicOnHoldPath() + "/class-music-1"); if (!moh.isDirectory()) moh.mkdirs(); File classMohFile = new File(moh, "pline-hold.wav"); if (!classMohFile.exists()) { GlobalTools.copyFileUsingStream(GlobalTools.getBaseDir() + "/resource/pline-hold.wav", classMohFile.getPath()); } if (outboundRouteRepository.findByName("default").isEmpty()) { TblOutboundRoute outRoute = new TblOutboundRoute(); outRoute.setName("default"); outRoute.setEnable(true); outRoute.setDescription("This routing directs all the numbers that start with 9 to the outside." + "In this routing, it is not possible to make international calls."); outRoute = outboundRouteRepository.save(outRoute); String[] patternStr = new String[] { "9ZX.", "9XZ.", "1Z.", }; List listPattern = new ArrayList<>(); for (var item : patternStr) { TblOutboundRoutePattern pattern = new TblOutboundRoutePattern(); pattern.setEnable(true); pattern.setPattern(item); pattern.setDropNumber(1); pattern.setPrefixNum(""); pattern.setOutboundRoute(outRoute); listPattern.add(pattern); } outboundRoutePatternsRepository.saveAll(listPattern); } } if (faxSettingsRepository.count() == 0) { var fax = new TblFaxSetting(); fax.setEnabled(true); faxSettingsRepository.save(fax); } if (banner == null || banner.trim().isEmpty()) System.out.println(""" \t\t\t*********************************************** \t\t\t# ██████╗ ██╗ ██╗███╗ ██╗███████╗ # \t\t\t# ██╔══██╗ ██║ ██║████╗ ██║██╔════╝ # \t\t\t# ██████╔╝█████╗██║ ██║██╔██╗ ██║█████╗ # \t\t\t# ██╔═══╝ ╚════╝██║ ██║██║╚██╗██║██╔══╝ # \t\t\t# ██║ ███████╗██║██║ ╚████║███████╗ # \t\t\t# ╚═╝ ╚══════╝╚═╝╚═╝ ╚═══╝╚══════╝ # \t\t\t*********************************************** """); fileGenerator.GenerateFiles(); dialableNumberConflictService.findExistingConflicts() .forEach(plineTools::plineLogger); System.out.println("App Name:\t\t" + appName); System.out.println("Date-Time:\t\t" + GlobalTools.getWeekDay() + " " + GlobalTools.getDate() + " - " + GlobalTools.getTime() + " (" + GlobalTools.getTimeZone() + ")"); System.out.println("HDD:\t\t"); var h = GlobalTools.getHardDiskInfo(plineTools.getCallRecordPath()); System.out.println(h.getFileStore() + " " + GlobalTools.formatSize(h.getTotalSpace()) + " " + GlobalTools.formatSize(h.getUsableSpace()) + " " + GlobalTools.formatSize(h.getFreeSpace())); System.out.println("App WbSite:\t\t" + plineTools.getAppWebsite()); System.out.println("App Footer:\t\t" + plineTools.getAppFooter()); System.out.println("App Version:\t\t" + plineTools.getVersion()); System.out.println("App Serial:\t\t" + GlobalTools.getHostUUID()); }; } private TblSipProfile getOrCreateSipProfile(String name, String description) { return sipProfilesRepository.findByName(name).orElseGet(() -> { TblSipProfile profile = new TblSipProfile(); profile.setName(name); profile.setDescription(description); profile.setEnable(true); return sipProfilesRepository.save(profile); }); } private static String profileDetailIdentity(long profileId, String type, String key, String value) { return profileId + "\u0000" + type + "\u0000" + key + "\u0000" + value; } /** * Older releases mapped several many-to-one relations as one-to-one. Remove only * single-column UNIQUE constraints that conflict with the current entity mappings. * The scan is schema-aware because the installer and application DB roles can have * different PostgreSQL search paths. Existing rows and foreign keys are preserved. */ private void removeObsoleteManyToOneUniqueConstraints() { jdbcTemplate.execute(""" DO $$ DECLARE target RECORD; table_row RECORD; constraint_row RECORD; BEGIN FOR target IN SELECT * FROM (VALUES ('tbl_sip_profile_details', 'sip_profile_id'), ('tbl_sip_users', 'sip_profile_id'), ('tbl_sip_users', 'sip_user_group_id'), ('tbl_sip_trunks', 'sip_profile_id'), ('tbl_call_access_list_members', 'tbl_call_access_list_id'), ('tbl_call_access_list_members', 'sip_user_id'), ('tbl_outbound_route_trunks', 'sip_trunk_id'), ('tbl_ringing_music_on_holds', 'internal_music_hold_id'), ('tbl_ringing_music_on_holds', 'external_music_hold_id') ) AS relations(table_name, column_name) LOOP FOR table_row IN SELECT t.oid AS table_oid, n.nspname AS schema_name, t.relname AS table_name, a.attnum AS column_number FROM pg_class t JOIN pg_namespace n ON n.oid = t.relnamespace JOIN pg_attribute a ON a.attrelid = t.oid WHERE t.relname = target.table_name AND t.relkind IN ('r', 'p') AND n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname NOT LIKE 'pg_%' AND a.attname = target.column_name AND NOT a.attisdropped LOOP FOR constraint_row IN SELECT c.conname FROM pg_constraint c WHERE c.conrelid = table_row.table_oid AND c.contype = 'u' AND c.conkey = ARRAY[table_row.column_number]::smallint[] LOOP RAISE NOTICE 'Removing obsolete UNIQUE constraint %.%.%', table_row.schema_name, table_row.table_name, constraint_row.conname; EXECUTE format('ALTER TABLE %I.%I DROP CONSTRAINT %I', table_row.schema_name, table_row.table_name, constraint_row.conname); END LOOP; END LOOP; END LOOP; END; $$ """); } }