List of usage examples for java.nio.file StandardOpenOption TRUNCATE_EXISTING
StandardOpenOption TRUNCATE_EXISTING
To view the source code for java.nio.file StandardOpenOption TRUNCATE_EXISTING.
Click Source Link
From source file:de.decoit.visa.rdf.RDFManager.java
/** * Write the RDF model to a RDF/XML file. The output file will be created at * the specified location.// w w w. j a v a2 s . c o m * * @param pFile File object with path and file name of the output file * @throws IOException */ public void writeRDF(Path pFile) throws IOException { OutputStream os = Files.newOutputStream(pFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); writeRDF(os); Set<PosixFilePermission> attrSet = PosixFilePermissions.fromString("rwxrwxrwx"); Files.setPosixFilePermissions(pFile, attrSet); }
From source file:ca.osmcanada.osvuploadr.JPMain.java
private void Process(String dir, String accessToken) { File dir_photos = new File(dir); //filter only .jpgs FilenameFilter fileNameFilter = new FilenameFilter() { public boolean accept(File dir, String name) { if (name.lastIndexOf('.') > 0) { int lastIndex = name.lastIndexOf('.'); String str = name.substring(lastIndex); if (str.toLowerCase().equals(".jpg")) { return true; }//from w ww . j a v a 2 s . c o m } return false; } }; File[] file_list = dir_photos.listFiles(fileNameFilter); System.out.println("Pictures found:" + String.valueOf(file_list.length)); System.out.println("Sorting files"); //sort by modified time Arrays.sort(file_list, new Comparator<File>() { public int compare(File f1, File f2) { return Long.valueOf(Helper.getFileTime(f1)).compareTo(Helper.getFileTime(f2)); } }); System.out.println("End sorting"); File f_sequence = new File(dir + "/sequence_file.txt"); Boolean need_seq = true; long sequence_id = -1; System.out.println("Checking " + f_sequence.getPath() + " for sequence_file"); if (f_sequence.exists()) { try { System.out.println("Found file, reading sequence id"); List<String> id = Files.readAllLines(Paths.get(f_sequence.getPath())); if (id.size() > 0) { sequence_id = Long.parseLong(id.get(0)); need_seq = false; } } catch (Exception ex) { need_seq = true; } } else { System.out.println("Sequence file not found, will need to request new id"); need_seq = true; } //TODO: Load count from file System.out.println("Looking for count file"); int cnt = 0; File f_cnt = new File(dir + "/count_file.txt"); if (f_cnt.exists()) { System.out.println("Found count file:" + f_cnt.toString()); try { List<String> id = Files.readAllLines(Paths.get(f_cnt.getPath())); if (id.size() > 0) { cnt = Integer.parseInt(id.get(0)); } } catch (Exception ex) { cnt = 0; } } else { try { System.out.println("Creating new count file:" + f_cnt.getPath()); f_cnt.createNewFile(); } catch (Exception ex) { Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("Current count at:" + String.valueOf(cnt)); if (cnt > 0) { if (file_list.length > cnt) { File[] tmp = new File[file_list.length - cnt]; int local_cnt = 0; for (int i = cnt; i < file_list.length; i++) { tmp[local_cnt] = file_list[i]; local_cnt++; } file_list = tmp; } } System.out.println("Processing photos..."); //Read file info for (File f : file_list) { try { System.out.println("Processing:" + f.getPath()); ImageProperties imp = Helper.getImageProperties(f); System.out.println("Image Properties:"); System.out.println("Lat:" + String.valueOf(imp.getLatitude()) + " Long:" + String.valueOf(imp.getLongitude()) + "Created:" + String.valueOf(Helper.getFileTime(f))); //TODO: Check that file has GPS coordinates //TODO: Remove invalid photos if (need_seq) { System.out.println("Requesting sequence ID"); sequence_id = getSequence(imp, accessToken); System.out.println("Obtained:" + sequence_id); byte[] bytes = Long.toString(sequence_id).getBytes(StandardCharsets.UTF_8); Files.write(Paths.get(f_sequence.getPath()), bytes, StandardOpenOption.CREATE); need_seq = false; } imp.setSequenceNumber(cnt); cnt++; //TODO: Write count to file System.out.println("Uploading image:" + f.getPath()); Upload_Image(imp, accessToken, sequence_id); System.out.println("Uploaded"); String out = String.valueOf(cnt); Files.write(Paths.get(f_cnt.getPath()), out.getBytes("UTF-8"), StandardOpenOption.TRUNCATE_EXISTING); } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR); } } System.out.println("Sending finish for sequence:" + sequence_id); SendFinished(sequence_id, accessToken); }
From source file:org.wildfly.security.tool.FileSystemRealmCommand.java
/** * Creates the script/commands the user must run for Elytron to recognize * and use the new filesystem-realm/*from w w w . j av a 2s . com*/ */ private void createWildFlyScript() throws Exception { for (Descriptor descriptor : descriptors) { String usersFile = descriptor.getUsersFile(); if (descriptor.getUsersFile() == null || descriptor.getRolesFile() == null || descriptor.getOutputLocation() == null) { continue; } String fileSystemRealmName = descriptor.getFileSystemRealmName(); if (fileSystemRealmName == null || fileSystemRealmName.isEmpty()) { warningHandler(String.format( "No name provided for filesystem-realm, using default filesystem-realm name for %s.", usersFile)); descriptor.setFileSystemRealmName(DEFAULT_FILESYSTEM_REALM_NAME); fileSystemRealmName = DEFAULT_FILESYSTEM_REALM_NAME; } String outputLocation = descriptor.getOutputLocation(); String securityDomainName = descriptor.getSecurityDomainName(); String createScriptCheck = ""; if (Paths.get(String.format("%s.sh", fileSystemRealmName)).toFile().exists()) { createScriptCheck = prompt(false, null, false, ElytronToolMessages.msg .shouldFileBeOverwritten(String.format("%s.sh", fileSystemRealmName))); } String fullOutputPath; if (outputLocation.startsWith(".")) { fullOutputPath = Paths.get(outputLocation.substring(2, outputLocation.length())).toAbsolutePath() .toString(); } else { fullOutputPath = Paths.get(outputLocation).toAbsolutePath().toString(); } if (summaryMode) { summaryString.append(String.format("Configured script for WildFly named %s.sh at %s.", fileSystemRealmName, fullOutputPath)); summaryString.append(System.getProperty("line.separator")); summaryString.append("The script is using the following names:"); summaryString.append(System.getProperty("line.separator")); summaryString.append(String.format("Name of filesystem-realm: %s", fileSystemRealmName)); summaryString.append(System.getProperty("line.separator")); } if (securityDomainName != null && !securityDomainName.isEmpty()) { if (summaryMode) { summaryString.append(String.format("Name of security-domain: %s", securityDomainName)); summaryString.append(System.getProperty("line.separator")); } } else { warningHandler(String.format( "No name provided for security-domain, using default security-domain name for %s.", usersFile)); securityDomainName = DEFAULT_SECURITY_DOMAIN_NAME; } List<String> scriptLines = Arrays.asList( String.format("/subsystem=elytron/filesystem-realm=%s:add(path=%s)", fileSystemRealmName, fullOutputPath), String.format( "/subsystem=elytron/security-domain=%1$s:add(realms=[{realm=%2$s}],default-realm=%2$s,permission-mapper=default-permission-mapper)", securityDomainName, fileSystemRealmName)); if (!createScriptCheck.equals("y") && !createScriptCheck.equals("yes")) { Files.write(Paths.get(String.format("%s/%s.sh", outputLocation, fileSystemRealmName)), scriptLines, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } else { Files.write(Paths.get(String.format("%s/%s.sh", outputLocation, fileSystemRealmName)), scriptLines, StandardOpenOption.APPEND); } } }
From source file:org.codice.ddf.configuration.migration.ConfigurationMigrationManagerTest.java
private void createBrandingFile(String branding) throws IOException { final File brandingFile = new File(ddfHome.resolve("Branding.txt").toString()); brandingFile.createNewFile();//w w w . j a v a 2 s .c o m Files.write(brandingFile.toPath(), branding.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); }
From source file:org.codice.ddf.configuration.migration.ConfigurationMigrationManagerTest.java
private void createVersionFile(String version) throws IOException { File versionFile = new File(ddfHome.resolve("Version.txt").toString()); versionFile.createNewFile();/*from www . j a v a 2 s . c o m*/ Files.write(versionFile.toPath(), version.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); }
From source file:org.codice.ddf.configuration.migration.ConfigurationMigrationManagerTest.java
private void createMigrationPropsFile(String contents) throws IOException { Path migrationPropsPath = ddfHome.resolve(Paths.get("etc", "migration.properties")); Files.createDirectories(migrationPropsPath.getParent()); Files.createFile(migrationPropsPath); Files.write(migrationPropsPath, contents.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); }
From source file:me.mast3rplan.phantombot.PhantomBot.java
private void init() { /* Is the web toggle enabled? */ if (webEnabled) { if (legacyServers) { /* open a normal non ssl server */ httpServer = new HTTPServer(basePort, oauth); /* Start this http server */ httpServer.start();// w ww.j a va 2s . c o m } /* Is the music toggled on? */ if (musicEnabled) { /* Set the music player server */ youtubeSocketServer = new YTWebSocketServer((basePort + 3), youtubeOAuth, youtubeOAuthThro); /* Start this youtube socket server */ youtubeSocketServer.start(); print("YouTubeSocketServer accepting connections on port: " + (basePort + 3)); } /* Checks if the user wants the legacy servers, this is off by default. */ if (legacyServers) { /* Create a event server to get all the events. */ eventWebSocketServer = new EventWebSocketServer((basePort + 2)); /* Start this event server */ eventWebSocketServer.start(); print("EventSocketServer accepting connections on port: " + (basePort + 2)); /* make the event bus register this event server */ EventBus.instance().register(eventWebSocketServer); } if (useHttps) { /* Set up the panel socket server */ panelSocketSecureServer = new PanelSocketSecureServer((basePort + 4), webOAuth, webOAuthThro, httpsFileName, httpsPassword); /* Start the panel socket server */ panelSocketSecureServer.start(); print("PanelSocketSecureServer accepting connections on port: " + (basePort + 4) + " (SSL)"); /* Set up a new https server */ newHttpsServer = new NEWHTTPSServer((basePort + 5), oauth, webOAuth, panelUsername, panelPassword, httpsFileName, httpsPassword); print("New HTTPS server accepting connection on port: " + (basePort + 5) + " (SSL)"); } else { /* Set up the panel socket server */ panelSocketServer = new PanelSocketServer((basePort + 4), webOAuth, webOAuthThro); /* Start the panel socket server */ panelSocketServer.start(); print("PanelSocketServer accepting connections on port: " + (basePort + 4)); /* Set up a new http server */ newHttpServer = new NEWHTTPServer((basePort + 5), oauth, webOAuth, panelUsername, panelPassword); print("New HTTP server accepting connection on port: " + (basePort + 5)); } } /* Enable GameWisp if the oAuth is set */ if (!gameWispOAuth.isEmpty() && checkModuleEnabled("./handlers/gameWispHandler.js")) { /* Set the oAuths */ GameWispAPIv1.instance().SetAccessToken(gameWispOAuth); GameWispAPIv1.instance().SetRefreshToken(gameWispRefresh); SingularityAPI.instance().setAccessToken(gameWispOAuth); SingularityAPI.instance().StartService(); /* get a fresh token */ doRefreshGameWispToken(); } /* Connect to Discord if the data is present. */ if (!discordToken.isEmpty()) { DiscordAPI.instance().connect(discordToken); } /* Set Streamlabs currency code, if possible */ if (dataStore.HasKey("donations", "", "currencycode")) { TwitchAlertsAPIv1.instance().SetCurrencyCode(dataStore.GetString("donations", "", "currencycode")); } /* Check to see if all the Twitter info needed is there */ if (!twitterUsername.isEmpty() && !twitterAccessToken.isEmpty() && !twitterConsumerToken.isEmpty() && !twitterConsumerSecret.isEmpty() && !twitterSecretToken.isEmpty()) { /* Set the Twitter tokens */ TwitterAPI.instance().setUsername(twitterUsername); TwitterAPI.instance().setAccessToken(twitterAccessToken); TwitterAPI.instance().setSecretToken(twitterSecretToken); TwitterAPI.instance().setConsumerKey(twitterConsumerToken); TwitterAPI.instance().setConsumerSecret(twitterConsumerSecret); /* Check to see if the tokens worked */ this.twitterAuthenticated = TwitterAPI.instance().authenticate(); } /* print a extra line in the console. */ print(""); /* Create configuration for YTPlayer v2.0 for the WS port. */ String data = ""; String http = (useHttps ? "https://" : "http://"); try { data += "//Configuration for YTPlayer\r\n"; data += "//Automatically Generated by PhantomBot at Startup\r\n"; data += "//Do NOT Modify! Overwritten when PhantomBot is restarted!\r\n"; data += "var playerPort = " + (basePort + 3) + ";\r\n"; data += "var channelName = \"" + channelName + "\";\r\n"; data += "var auth=\"" + youtubeOAuth + "\";\r\n"; data += "var http=\"" + http + "\";\r\n"; data += "function getPlayerPort() { return playerPort; }\r\n"; data += "function getChannelName() { return channelName; }\r\n"; data += "function getAuth() { return auth; }\r\n"; data += "function getProtocol() { return http; }\r\n"; /* Create a new file if it does not exist */ if (!new File("./web/ytplayer/").exists()) new File("./web/ytplayer/").mkdirs(); if (!new File("./web/ytplayer/js").exists()) new File("./web/ytplayer/js").mkdirs(); /* Write the data to that file */ Files.write(Paths.get("./web/ytplayer/js/playerConfig.js"), data.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } /* Create configuration for YTPlayer v2.0 for the WS port. */ data = ""; try { data += "//Configuration for YTPlayer\r\n"; data += "//Automatically Generated by PhantomBot at Startup\r\n"; data += "//Do NOT Modify! Overwritten when PhantomBot is restarted!\r\n"; data += "var playerPort = " + (basePort + 3) + ";\r\n"; data += "var channelName = \"" + channelName + "\";\r\n"; data += "var auth=\"" + youtubeOAuthThro + "\";\r\n"; data += "var http=\"" + http + "\";\r\n"; data += "function getPlayerPort() { return playerPort; }\r\n"; data += "function getChannelName() { return channelName; }\r\n"; data += "function getAuth() { return auth; }\r\n"; data += "function getProtocol() { return http; }\r\n"; /* Create a new file if it does not exist */ if (!new File("./web/playlist/").exists()) new File("./web/playlist/").mkdirs(); if (!new File("./web/playlist/js").exists()) new File("./web/playlist/js").mkdirs(); /* Write the data to that file */ Files.write(Paths.get("./web/playlist/js/playerConfig.js"), data.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } /* Create configuration for WebPanel for the WS port. */ data = ""; try { data += "//Configuration for Control Panel\r\n"; data += "//Automatically Generated by PhantomBot at Startup\r\n"; data += "//Do NOT Modify! Overwritten when PhantomBot is restarted!\r\n"; data += "var panelSettings = {\r\n"; data += " panelPort : " + (basePort + 4) + ",\r\n"; data += " channelName : \"" + channelName + "\",\r\n"; data += " auth : \"" + webOAuth + "\",\r\n"; data += " http : \"" + http + "\"\r\n"; data += "};\r\n\r\n"; data += "function getPanelPort() { return panelSettings.panelPort; }\r\n"; data += "function getChannelName() { return panelSettings.channelName; }\r\n"; data += "function getAuth() { return panelSettings.auth; }\r\n"; data += "function getProtocol() { return panelSettings.http; }\r\n"; /* Create a new file if it does not exist */ if (!new File("./web/panel/").exists()) new File("./web/panel/").mkdirs(); if (!new File("./web/panel/js").exists()) new File("./web/panel/js").mkdirs(); /* Write the data to that file */ Files.write(Paths.get("./web/panel/js/panelConfig.js"), data.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } /* Create configuration for Read-Only Access to WS port. */ data = ""; try { data += "//Configuration for Control Panel\r\n"; data += "//Automatically Generated by PhantomBot at Startup\r\n"; data += "//Do NOT Modify! Overwritten when PhantomBot is restarted!\r\n"; data += "var panelSettings = {\r\n"; data += " panelPort : " + (basePort + 4) + ",\r\n"; data += " channelName : \"" + channelName + "\",\r\n"; data += " auth : \"" + webOAuthThro + "\",\r\n"; data += " http : \"" + http + "\"\r\n"; data += "};\r\n\r\n"; data += "function getPanelPort() { return panelSettings.panelPort; }\r\n"; data += "function getChannelName() { return panelSettings.channelName; }\r\n"; data += "function getAuth() { return panelSettings.auth; }\r\n"; data += "function getProtocol() { return panelSettings.http; }\r\n"; /* Create a new file if it does not exist */ if (!new File("./web/common/").exists()) new File("./web/common/").mkdirs(); if (!new File("./web/common/js").exists()) new File("./web/common/js").mkdirs(); /* Write the data to that file */ Files.write(Paths.get("./web/common/js/wsConfig.js"), data.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } /* check if the console is interactive */ if (interactive) { ConsoleInputListener consoleIL = new ConsoleInputListener(); /* Start the Console Input Listener */ consoleIL.start(); } /* Register PhantomBot (this) with the event bus. */ EventBus.instance().register(this); /* Register the script manager with the event bus. */ EventBus.instance().register(ScriptEventManager.instance()); /* Load the datastore config */ dataStore.LoadConfig(dataStoreConfig); /* Export all these to the $. api in the scripts. */ Script.global.defineProperty("inidb", dataStore, 0); Script.global.defineProperty("username", UsernameCache.instance(), 0); Script.global.defineProperty("twitch", TwitchAPIv3.instance(), 0); Script.global.defineProperty("botName", botName, 0); Script.global.defineProperty("channelName", channelName, 0); Script.global.defineProperty("channels", channels, 0); Script.global.defineProperty("ownerName", ownerName, 0); Script.global.defineProperty("ytplayer", youtubeSocketServer, 0); Script.global.defineProperty("panelsocketserver", (useHttps ? panelSocketSecureServer : panelSocketServer), 0); Script.global.defineProperty("random", random, 0); Script.global.defineProperty("youtube", YouTubeAPIv3.instance(), 0); Script.global.defineProperty("shortenURL", GoogleURLShortenerAPIv1.instance(), 0); Script.global.defineProperty("gamewisp", GameWispAPIv1.instance(), 0); Script.global.defineProperty("twitter", TwitterAPI.instance(), 0); Script.global.defineProperty("twitchCacheReady", PhantomBot.twitchCacheReady, 0); Script.global.defineProperty("isNightly", isNightly(), 0); Script.global.defineProperty("version", botVersion(), 0); Script.global.defineProperty("changed", newSetup, 0); Script.global.defineProperty("discordAPI", DiscordAPI.instance(), 0); Script.global.defineProperty("hasDiscordToken", hasDiscordToken(), 0); Script.global.defineProperty("customAPI", CustomAPI.instance(), 0); /* open a new thread for when the bot is exiting */ Thread thread = new Thread(() -> { onExit(); }); /* Get the un time for that new thread we just created */ Runtime.getRuntime().addShutdownHook(thread); /* And finally try to load init, that will then load the scripts */ try { ScriptManager.loadScript(new File("./scripts/init.js")); } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } /* Check for a update with PhantomBot */ doCheckPhantomBotUpdate(); /* Perform SQLite datbase backups. */ if (this.backupSQLiteAuto) { doBackupSQLiteDB(); } }
From source file:tv.phantombot.PhantomBot.java
private void init() { /* Is the web toggle enabled? */ if (webEnabled) { try {//from ww w . ja v a 2 s .c o m checkPortAvailabity(basePort); checkPortAvailabity(panelSocketPort); /* Is the music toggled on? */ if (musicEnabled) { checkPortAvailabity(ytSocketPort); if (useHttps) { /* Set the music player server */ youtubeSocketSecureServer = new YTWebSocketSecureServer(bindIP, ytSocketPort, youtubeOAuth, youtubeOAuthThro, httpsFileName, httpsPassword, socketServerTasksSize); /* Start this youtube socket server */ youtubeSocketSecureServer.start(); print("YouTubeSocketSecureServer accepting connections on port: " + ytSocketPort + " (SSL)"); } else { /* Set the music player server */ youtubeSocketServer = new YTWebSocketServer(bindIP, ytSocketPort, youtubeOAuth, youtubeOAuthThro); /* Start this youtube socket server */ youtubeSocketServer.start(); print("YouTubeSocketServer accepting connections on port: " + ytSocketPort); } } if (useHttps) { if (testPanelServer) { newPanelSocketServer = new NewPanelSocketServer(panelSocketPort, webOAuth, webOAuthThro, httpsFileName, httpsPassword); newPanelSocketServer.start(); print("TEST PanelSocketSecureServer accepting connections on port: " + panelSocketPort + " (SSL)"); } else { /* Set up the panel socket server */ panelSocketSecureServer = new PanelSocketSecureServer(bindIP, panelSocketPort, webOAuth, webOAuthThro, httpsFileName, httpsPassword, socketServerTasksSize); /* Start the panel socket server */ panelSocketSecureServer.start(); print("PanelSocketSecureServer accepting connections on port: " + panelSocketPort + " (SSL)"); } /* Set up a new https server */ httpsServer = new HTTPSServer(bindIP, (basePort), oauth, webOAuth, panelUsername, panelPassword, httpsFileName, httpsPassword); print("HTTPS server accepting connection on port: " + basePort + " (SSL)"); } else { if (testPanelServer) { newPanelSocketServer = new NewPanelSocketServer(panelSocketPort, webOAuth, webOAuthThro); newPanelSocketServer.start(); print("TEST PanelSocketServer accepting connections on port: " + panelSocketPort); } else { /* Set up the panel socket server */ panelSocketServer = new PanelSocketServer(bindIP, panelSocketPort, webOAuth, webOAuthThro); /* Set up the NEW panel socket server */ /* Start the panel socket server */ panelSocketServer.start(); print("PanelSocketServer accepting connections on port: " + panelSocketPort); } /* Set up a new http server */ httpServer = new HTTPServer(bindIP, (basePort), oauth, webOAuth, panelUsername, panelPassword); print("HTTP server accepting connection on port: " + basePort); } } catch (Exception ex) { print("Exception occurred in one of the socket based services, PhantomBot will now exit."); System.exit(0); } } /* Enable GameWisp if the oAuth is set */ if (!gameWispOAuth.isEmpty() && checkModuleEnabled("./handlers/gameWispHandler.js")) { /* Set the oAuths */ GameWispAPIv1.instance().SetAccessToken(gameWispOAuth); GameWispAPIv1.instance().SetRefreshToken(gameWispRefresh); SingularityAPI.instance().setAccessToken(gameWispOAuth); SingularityAPI.instance().StartService(); /* get a fresh token */ doRefreshGameWispToken(); } /* Connect to Discord if the data is present. */ if (!discordToken.isEmpty()) { DiscordAPI.instance().connect(discordToken); } /* Set Streamlabs currency code, if possible */ if (dataStore.HasKey("donations", "", "currencycode")) { TwitchAlertsAPIv1.instance().SetCurrencyCode(dataStore.GetString("donations", "", "currencycode")); } /* Check to see if all the Twitter info needed is there */ if (!twitterUsername.isEmpty() && !twitterAccessToken.isEmpty() && !twitterConsumerToken.isEmpty() && !twitterConsumerSecret.isEmpty() && !twitterSecretToken.isEmpty()) { /* Set the Twitter tokens */ TwitterAPI.instance().setUsername(twitterUsername); TwitterAPI.instance().setAccessToken(twitterAccessToken); TwitterAPI.instance().setSecretToken(twitterSecretToken); TwitterAPI.instance().setConsumerKey(twitterConsumerToken); TwitterAPI.instance().setConsumerSecret(twitterConsumerSecret); /* Check to see if the tokens worked */ this.twitterAuthenticated = TwitterAPI.instance().authenticate(); } /* print a extra line in the console. */ print(""); /* Create configuration for YTPlayer v2.0 for the WS port. */ String data = ""; String http = (useHttps ? "https://" : "http://"); try { data += "// Configuration for YTPlayer\r\n"; data += "// Automatically Generated by PhantomBot at Startup\r\n"; data += "// Do NOT Modify! Overwritten when PhantomBot is restarted!\r\n"; data += "var playerPort = " + ytSocketPort + ";\r\n"; data += "var channelName = \"" + channelName + "\";\r\n"; data += "var auth=\"" + youtubeOAuth + "\";\r\n"; data += "var http=\"" + http + "\";\r\n"; data += "function getPlayerPort() { return playerPort; }\r\n"; data += "function getChannelName() { return channelName; }\r\n"; data += "function getAuth() { return auth; }\r\n"; data += "function getProtocol() { return http; }\r\n"; /* Create a new file if it does not exist */ if (!new File("./web/ytplayer/").exists()) new File("./web/ytplayer/").mkdirs(); if (!new File("./web/ytplayer/js").exists()) new File("./web/ytplayer/js").mkdirs(); /* Write the data to that file */ Files.write(Paths.get("./web/ytplayer/js/playerConfig.js"), data.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } /* Create configuration for YTPlayer Playlist v2.0 for the WS port. */ data = ""; try { data += "//Configuration for YTPlayer\r\n"; data += "//Automatically Generated by PhantomBot at Startup\r\n"; data += "//Do NOT Modify! Overwritten when PhantomBot is restarted!\r\n"; data += "var playerPort = " + ytSocketPort + ";\r\n"; data += "var channelName = \"" + channelName + "\";\r\n"; data += "var auth=\"" + youtubeOAuthThro + "\";\r\n"; data += "var http=\"" + http + "\";\r\n"; data += "function getPlayerPort() { return playerPort; }\r\n"; data += "function getChannelName() { return channelName; }\r\n"; data += "function getAuth() { return auth; }\r\n"; data += "function getProtocol() { return http; }\r\n"; /* Create a new file if it does not exist */ if (!new File("./web/playlist/").exists()) new File("./web/playlist/").mkdirs(); if (!new File("./web/playlist/js").exists()) new File("./web/playlist/js").mkdirs(); /* Write the data to that file */ Files.write(Paths.get("./web/playlist/js/playerConfig.js"), data.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } /* Create configuration for WebPanel for the WS port. */ data = ""; try { data += "// Configuration for Control Panel\r\n"; data += "// Automatically Generated by PhantomBot at Startup\r\n"; data += "// Do NOT Modify! Overwritten when PhantomBot is restarted!\r\n"; data += "var panelSettings = {\r\n"; data += " panelPort : " + panelSocketPort + ",\r\n"; data += " channelName : \"" + channelName + "\",\r\n"; data += " auth : \"" + webOAuth + "\",\r\n"; data += " http : \"" + http + "\"\r\n"; data += "};\r\n\r\n"; data += "function getPanelPort() { return panelSettings.panelPort; }\r\n"; data += "function getChannelName() { return panelSettings.channelName; }\r\n"; data += "function getAuth() { return panelSettings.auth; }\r\n"; data += "function getProtocol() { return panelSettings.http; }\r\n"; /* Create a new file if it does not exist */ if (!new File("./web/panel/").exists()) new File("./web/panel/").mkdirs(); if (!new File("./web/panel/js").exists()) new File("./web/panel/js").mkdirs(); byte[] bytes = data.getBytes(StandardCharsets.UTF_8); /* Write the data to that file */ Files.write(Paths.get("./web/panel/js/panelConfig.js"), bytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); // If betap write the file in that folder too. if (PhantomBot.betap) { Files.write(Paths.get("./web/beta-panel/js/utils/panelConfig.js"), bytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } /* Create configuration for Read-Only Access to WS port. */ data = ""; try { data += "// Configuration for Control Panel\r\n"; data += "// Automatically Generated by PhantomBot at Startup\r\n"; data += "// Do NOT Modify! Overwritten when PhantomBot is restarted!\r\n"; data += "var panelSettings = {\r\n"; data += " panelPort : " + panelSocketPort + ",\r\n"; data += " channelName : \"" + channelName + "\",\r\n"; data += " auth : \"" + webOAuthThro + "\",\r\n"; data += " http : \"" + http + "\"\r\n"; data += "};\r\n\r\n"; data += "function getPanelPort() { return panelSettings.panelPort; }\r\n"; data += "function getChannelName() { return panelSettings.channelName; }\r\n"; data += "function getAuth() { return panelSettings.auth; }\r\n"; data += "function getProtocol() { return panelSettings.http; }\r\n"; /* Create a new file if it does not exist */ if (!new File("./web/common/").exists()) new File("./web/common/").mkdirs(); if (!new File("./web/common/js").exists()) new File("./web/common/js").mkdirs(); /* Write the data to that file */ Files.write(Paths.get("./web/common/js/wsConfig.js"), data.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } /* check if the console is interactive */ if (interactive) { ConsoleInputListener consoleIL = new ConsoleInputListener(); /* Start the Console Input Listener */ consoleIL.start(); } /* Register PhantomBot (this) with the event bus. */ EventBus.instance().register(this); /* Register the script manager with the event bus. */ EventBus.instance().register(ScriptEventManager.instance()); /* Register the console event handler */ EventBus.instance().register(ConsoleEventHandler.instance()); /* Load the datastore config */ dataStore.LoadConfig(dataStoreConfig); /* Export all these to the $. api in the scripts. */ Script.global.defineProperty("inidb", dataStore, 0); Script.global.defineProperty("username", UsernameCache.instance(), 0); Script.global.defineProperty("twitch", TwitchAPIv5.instance(), 0); Script.global.defineProperty("botName", botName.toLowerCase(), 0); Script.global.defineProperty("channelName", channelName.toLowerCase(), 0); Script.global.defineProperty("ownerName", ownerName.toLowerCase(), 0); Script.global.defineProperty("ytplayer", (useHttps ? youtubeSocketSecureServer : youtubeSocketServer), 0); if (testPanelServer) { Script.global.defineProperty("panelsocketserver", newPanelSocketServer, 0); } else { Script.global.defineProperty("panelsocketserver", (useHttps ? panelSocketSecureServer : panelSocketServer), 0); } Script.global.defineProperty("random", random, 0); Script.global.defineProperty("youtube", YouTubeAPIv3.instance(), 0); Script.global.defineProperty("shortenURL", GoogleURLShortenerAPIv1.instance(), 0); Script.global.defineProperty("gamewisp", GameWispAPIv1.instance(), 0); Script.global.defineProperty("twitter", TwitterAPI.instance(), 0); Script.global.defineProperty("twitchCacheReady", PhantomBot.twitchCacheReady, 0); Script.global.defineProperty("isNightly", isNightly(), 0); Script.global.defineProperty("isPrerelease", isPrerelease(), 0); Script.global.defineProperty("version", botVersion(), 0); Script.global.defineProperty("changed", newSetup, 0); Script.global.defineProperty("discordAPI", DiscordAPI.instance(), 0); Script.global.defineProperty("hasDiscordToken", hasDiscordToken(), 0); Script.global.defineProperty("customAPI", CustomAPI.instance(), 0); Script.global.defineProperty("dataRenderServiceAPI", DataRenderServiceAPIv1.instance(), 0); /* open a new thread for when the bot is exiting */ Thread thread = new Thread(() -> { onExit(); }, "tv.phantombot.PhantomBot::onExit"); /* Get the un time for that new thread we just created */ Runtime.getRuntime().addShutdownHook(thread); /* And finally try to load init, that will then load the scripts */ try { ScriptManager.loadScript(new File("./scripts/init.js")); } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } // Moved this to debug only. People are already asking questions. if (PhantomBot.enableDebugging) { /* Check for bot verification. */ print("Bot Verification Status: " + (TwitchAPIv5.instance().getBotVerified(this.botName) ? "" : " NOT ") + "Verified."); } /* Check for a update with PhantomBot */ doCheckPhantomBotUpdate(); /* Perform SQLite datbase backups. */ if (this.backupSQLiteAuto) { doBackupSQLiteDB(); } }
From source file:me.gloriouseggroll.quorrabot.Quorrabot.java
@Subscribe public void onConsoleMessage(ConsoleInputEvent msg) { String message = msg.getMsg(); boolean changed = false; if (message == null) { return;/*from ww w .j ava 2 s .c o m*/ } if (message.equals("debugon")) { Quorrabot.setDebugging(true); } //used for testing notifications if (message.equalsIgnoreCase("subtest")) { String randomUser = generateRandomString(10); EventBus.instance().post( new IrcPrivateMessageEvent(this.session, "twitchnotify", randomUser + " just subscribed!")); } if (message.equalsIgnoreCase("resubtest")) { String randomUser = generateRandomString(10); EventBus.instance().post(new IrcPrivateMessageEvent(this.session, "twitchnotify", randomUser + " just subscribed for 10 months in a row!")); } if (message.equalsIgnoreCase("followtest")) { String randomUser = generateRandomString(10); EventBus.instance().post(new TwitchFollowEvent(randomUser, this.channel)); } if (message.equalsIgnoreCase("hosttest")) { String randomUser = generateRandomString(10); EventBus.instance().post(new TwitchHostedEvent(randomUser, this.tcechannel)); } if (message.equals("debugoff")) { Quorrabot.setDebugging(false); } if (message.startsWith("inidb.get")) { String spl[] = message.split(" ", 4); com.gmt2001.Console.out.println(dataStoreObj.GetString(spl[1], spl[2], spl[3])); } if (message.startsWith("inidb.set")) { String spl[] = message.split(" ", 5); dataStoreObj.SetString(spl[1], spl[2], spl[3], spl[4]); com.gmt2001.Console.out.println(dataStoreObj.GetString(spl[1], spl[2], spl[3])); } if (message.equals("apioauth")) { com.gmt2001.Console.out.print("Please enter the bot owner's api oauth string: "); String newoauth = System.console().readLine().trim(); TwitchAPIv3.instance().SetOAuth(newoauth); apioauth = newoauth; changed = true; } if (message.equalsIgnoreCase("mysqlsetup")) { try { com.gmt2001.Console.out.println(""); com.gmt2001.Console.out.println("QuorraBot MySQL setup."); com.gmt2001.Console.out.println(""); com.gmt2001.Console.out.print("Please enter your MySQL host name or IP: "); String newHost = System.console().readLine().trim(); mySqlHost = newHost; com.gmt2001.Console.out.print("Please enter your MySQL port: "); String newPost = System.console().readLine().trim(); mySqlPort = newPost; com.gmt2001.Console.out.print("Please enter your MySQL db name: "); String newName = System.console().readLine().trim(); mySqlName = newName; com.gmt2001.Console.out.print("Please enter a username for MySQL: "); String newUser = System.console().readLine().trim(); mySqlUser = newUser; com.gmt2001.Console.out.print("Please enter a password for MySQL: "); String newPass = System.console().readLine().trim(); mySqlPass = newPass; datastore = "MySQLStore"; dataStoreObj = MySQLStore.instance(); if (mySqlPort.isEmpty()) { mySqlConn = "jdbc:mariadb://" + mySqlHost + "/" + mySqlName; } else { mySqlConn = "jdbc:mariadb://" + mySqlHost + ":" + mySqlPort + "/" + mySqlName; } /** * Check to see if we can create a connection */ if (dataStoreObj.CreateConnection(mySqlConn, mySqlUser, mySqlPass) == null) { com.gmt2001.Console.out .println("Could not create a connection with MySql. QuorraBot now shutting down..."); System.exit(0); } if (IniStore.instance().GetFileList().length > 0) { ini2MySql(true); } else if (SqliteStore.instance().GetFileList().length > 0) { sqlite2MySql(); } com.gmt2001.Console.out.println("QuorraBot MySQL setup done."); changed = true; } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } } if (message.equals("clientid")) { com.gmt2001.Console.out.print("Please enter the bot api clientid string: "); String newclientid = System.console().readLine().trim(); TwitchAPIv3.instance().SetClientID(newclientid); clientid = newclientid; changed = true; } if (message.equals("baseport")) { com.gmt2001.Console.out.print("Please enter a new base port: "); String newbaseport = System.console().readLine().trim(); baseport = Integer.parseInt(newbaseport); changed = true; } if (message.equals("ip")) { com.gmt2001.Console.out.print("Please enter an IP address to bind to: "); String ipstr = System.console().readLine().trim(); try { InetAddress newip = InetAddress.getByName(ipstr); ip = newip; changed = true; } catch (UnknownHostException e) { com.gmt2001.Console.out.print("Error binding to IP address, please double check your IP entry."); return; } } if (message.equals("youtubekey")) { com.gmt2001.Console.out.print("Please enter a new YouTube API key: "); String newyoutubekey = System.console().readLine().trim(); YouTubeAPIv3.instance().SetAPIKey(newyoutubekey); youtubekey = newyoutubekey; changed = true; } if (message.equals("twitchalerts")) { com.gmt2001.Console.out.print("Please enter a new TwitchAlerts Access Token: "); String newtwitchalertstoken = System.console().readLine().trim(); DonationHandlerAPI.instance().SetAccessToken(newtwitchalertstoken, "twitchalerts"); twitchalertstoken = newtwitchalertstoken; changed = true; } if (message.equals("lastfm")) { com.gmt2001.Console.out.print("Please enter a last.fm username: "); String newlastfmuser = System.console().readLine().trim(); LastFMAPI.instance().SetUsername(newlastfmuser); lastfmuser = newlastfmuser; changed = true; } if (message.equals("tipeeestream")) { com.gmt2001.Console.out.print("Please enter a new Tipeeestream Access Token: "); String newtpetoken = System.console().readLine().trim(); DonationHandlerAPI.instance().SetAccessToken(newtpetoken, "tpestream"); tpetoken = newtpetoken; changed = true; } if (message.equals("twitter")) { com.gmt2001.Console.out .print("Please visit this url to grant QuorraBot twitter access, then enter your pin" + "\n"); com.gmt2001.Console.out.print(TwitterAPI.instance().getRequestTokenURL() + "\n"); com.gmt2001.Console.out.print("Twitter PIN:"); String newtwittertoken = System.console().readLine().trim(); TwitterAPI.instance().CreateAccessToken(newtwittertoken); twittertoken = TwitterAPI.instance().getAccessToken(); twittertokensecret = TwitterAPI.instance().getAccessTokenSecret(); changed = true; } if (message.equals("streamtip")) { com.gmt2001.Console.out.print("Please enter a new StreamTip Client ID: "); String newstreamtipid = System.console().readLine().trim(); DonationHandlerAPI.instance().SetClientID(newstreamtipid, "streamtip"); streamtipid = newstreamtipid; com.gmt2001.Console.out.print("Please enter a new StreamTip Access Token: "); String newstreamtiptoken = System.console().readLine().trim(); DonationHandlerAPI.instance().SetAccessToken(newstreamtiptoken, "streamtip"); streamtiptoken = newstreamtiptoken; changed = true; } if (message.equals("gamewisp")) { com.gmt2001.Console.out.print("Please enter a new GameWisp Access Token: "); String newgamewispauth = System.console().readLine().trim(); gamewispauth = newgamewispauth; GameWispAPI.instance().SetAccessToken(gamewispauth); SingularityAPI.instance().setAccessToken(gamewispauth); com.gmt2001.Console.out.print("Please enter a new GameWisp Refresh Token: "); String newgamewisprefresh = System.console().readLine().trim(); gamewisprefresh = newgamewisprefresh; GameWispAPI.instance().SetRefreshToken(gamewisprefresh); doRefreshGameWispToken(); changed = true; } if (message.equals("discord")) { com.gmt2001.Console.out.print("Please enter a new Discord Access Token: "); String newdiscordtoken = System.console().readLine().trim(); discordToken = newdiscordtoken; com.gmt2001.Console.out.print("Please enter the name of the discord channel for the bot to join: "); String newdiscordmainchannel = System.console().readLine().trim(); discordMainChannel = newdiscordmainchannel; changed = true; } if (message.equals("testgwrefresh")) { com.gmt2001.Console.out.println("[CONSOLE] Executing testgwrefresh"); updateGameWispTokens(GameWispAPI.instance().refreshToken()); changed = true; } if (message.equals("testgwsub")) { com.gmt2001.Console.out.println("[CONSOLE] Executing testgwsub"); EventBus.instance().post(new GameWispSubscribeEvent(this.username, 1)); return; } if (message.equals("testgwresub")) { com.gmt2001.Console.out.println("[CONSOLE] Executing testgwresub"); EventBus.instance().post(new GameWispAnniversaryEvent(this.username, 2, 3)); return; } if (message.equals("webenable")) { com.gmt2001.Console.out.print( "Please note that the music server will also be disabled if the web server is disabled. The bot will require a restart for this to take effect. Type true or false to enable/disable web server: "); String newwebenable = System.console().readLine().trim(); changed = true; if (newwebenable.equalsIgnoreCase("1") || newwebenable.equalsIgnoreCase("true")) { webenable = true; } else { webenable = false; } } if (message.equals("musicenable")) { if (!webenable) { com.gmt2001.Console.out.println("Web server must be enabled first. "); } else { com.gmt2001.Console.out.print( "The bot will require a restart for this to take effect. Please type true or false to enable/disable music server: "); String newmusicenable = System.console().readLine().trim(); changed = true; if (newmusicenable.equalsIgnoreCase("1") || newmusicenable.equalsIgnoreCase("true")) { musicenable = true; } else { musicenable = false; } } } if (changed) { try { String data = ""; data += "user=" + username + "\r\n"; data += "oauth=" + oauth + "\r\n"; data += "apioauth=" + apioauth + "\r\n"; data += "clientid=" + clientid + "\r\n"; data += "webauth=" + webauth + "\r\n"; data += "webauthro=" + webauthro + "\r\n"; data += "owner=" + ownerName + "\r\n"; data += "channel=" + channelName + "\r\n"; data += "baseport=" + baseport + "\r\n"; data += "ip=" + ip.getHostAddress() + "\r\n"; data += "hostname=" + hostname + "\r\n"; data += "port=" + port + "\r\n"; data += "msglimit30=" + msglimit30 + "\r\n"; data += "datastore=" + datastore + "\r\n"; data += "youtubekey=" + youtubekey + "\r\n"; data += "twitchalertstoken=" + twitchalertstoken + "\r\n"; data += "gamewispauth=" + gamewispauth + "\r\n"; data += "gamewisprefresh=" + gamewisprefresh + "\r\n"; data += "lastfmuser=" + lastfmuser + "\r\n"; data += "tpetoken=" + tpetoken + "\r\n"; data += "twittertoken=" + twittertoken + "\r\n"; data += "twittertokensecret=" + twittertokensecret + "\r\n"; data += "streamtiptoken=" + streamtiptoken + "\r\n"; data += "streamtipid=" + streamtipid + "\r\n"; data += "webenable=" + webenable + "\r\n"; data += "musicenable=" + musicenable + "\r\n"; data += "usehttps=" + usehttps + "\r\n"; data += "logtimezone=" + timeZone + "\r\n"; data += "mysqlhost=" + mySqlHost + "\r\n"; data += "mysqlport=" + mySqlPort + "\r\n"; data += "mysqlname=" + mySqlName + "\r\n"; data += "mysqluser=" + mySqlUser + "\r\n"; data += "mysqlpass=" + mySqlPass + "\r\n"; data += "keystorepath=" + keystorepath + "\r\n"; data += "discordtoken=" + discordToken + "\r\n"; data += "discordmainchannel=" + discordMainChannel + "\r\n"; Files.write(Paths.get("./botlogin.txt"), data.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); SingularityAPI.instance().setAccessToken(gamewispauth); if (webenable) { com.gmt2001.Console.out.println("[SHUTDOWN] Terminating web server..."); eventsocketserver.dispose(); if (musicenable) { com.gmt2001.Console.out.println("[SHUTDOWN] Terminating music server..."); musicsocketserver.dispose(); } httpserver.dispose(); startWebServices(); } if (!discordToken.isEmpty()) { DiscordAPI.instance().reconnect(); connectDiscord(); } com.gmt2001.Console.out.println( "Changes have been saved! Some changes may only take place after QuorraBot is restarted."); } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } } if (message.equals("save")) { dataStoreObj.SaveAll(true); } if (message.equals("quicksave")) { dataStoreObj.SaveChangedNow(); } if (message.equals("exit")) { System.exit(0); } Map<String, String> tags = new HashMap<>(); handleCommand(username, message, tags, channel, ownerName); }
From source file:me.gloriouseggroll.quorrabot.Quorrabot.java
public static void main(String[] args) throws IOException { String user = ""; String oauth = ""; String apioauth = ""; String channelName = ""; String webauth = ""; String webauthro = ""; String clientid = ""; String owner = ""; String hostname = ""; int baseport = 25300; InetAddress ip = InetAddress.getByName("127.0.0.1"); int port = 0; double msglimit30 = 18.75; String datastore = ""; String datastoreconfig = ""; String youtubekey = ""; String gamewispauth = ""; String gamewisprefresh = ""; String twitchalertstoken = ""; String lastfmuser = ""; String tpetoken = ""; String twittertoken = ""; String twittertokensecret = ""; String streamtiptoken = ""; String streamtipid = ""; boolean webenable = true; boolean musicenable = true; boolean usehttps = false; String keystorepath = ""; String keystorepassword = ""; String timeZone = ""; String mySqlConn = ""; String mySqlHost = ""; String mySqlPort = ""; String mySqlName = ""; String mySqlUser = ""; String mySqlPass = ""; FollowersCache followersCache;/*from w w w . ja v a2 s .c om*/ ChannelUsersCache channelUsersCache; ChannelHostCache hostCache; SubscribersCache subscribersCache; String discordToken = ""; String discordMainChannel = ""; boolean changed = false; try { if (new File("./botlogin.txt").exists()) { String data = FileUtils.readFileToString(new File("./botlogin.txt")); String[] lines = data.replaceAll("\\r", "").split("\\n"); for (String line : lines) { if (line.startsWith("logtimezone=") && line.length() >= 15) { timeZone = line.substring(12); } if (line.startsWith("websocketircab")) { Quorrabot.webSocketIRCAB = true; } if (line.startsWith("user=") && line.length() > 8) { user = line.substring(5); } if (line.startsWith("oauth=") && line.length() > 9) { oauth = line.substring(6); } if (line.startsWith("apioauth=") && line.length() > 12) { apioauth = line.substring(9); } if (line.startsWith("clientid=") && line.length() > 12) { clientid = line.substring(9); } if (line.startsWith("channel=") && line.length() > 11) { channelName = line.substring(8); } if (line.startsWith("owner=") && line.length() > 9) { owner = line.substring(6); } if (line.startsWith("baseport=") && line.length() > 10) { baseport = Integer.parseInt(line.substring(9)); } if (line.startsWith("ip=") && line.length() > 4) { ip = InetAddress.getByName(line.substring(3)); } if (line.startsWith("hostname=") && line.length() > 10) { hostname = line.substring(9); } if (line.startsWith("port=") && line.length() > 6) { port = Integer.parseInt(line.substring(5)); } if (line.startsWith("msglimit30=") && line.length() > 12) { msglimit30 = Double.parseDouble(line.substring(11)); } if (line.startsWith("datastore=") && line.length() > 11) { datastore = line.substring(10); } if (line.startsWith("youtubekey=") && line.length() > 12) { youtubekey = line.substring(11); } if (line.startsWith("gamewispauth=") && line.length() > 14) { gamewispauth = line.substring(13); } if (line.startsWith("gamewisprefresh=") && line.length() > 17) { gamewisprefresh = line.substring(16); } if (line.startsWith("twitchalertstoken=") && line.length() > 19) { twitchalertstoken = line.substring(18); } if (line.startsWith("lastfmuser=") && line.length() > 12) { lastfmuser = line.substring(11); } if (line.startsWith("tpetoken=") && line.length() > 10) { tpetoken = line.substring(9); } if (line.startsWith("twittertoken=") && line.length() > 14) { twittertoken = line.substring(13); } if (line.startsWith("twittertokensecret=") && line.length() > 20) { twittertokensecret = line.substring(19); } if (line.startsWith("streamtiptoken=") && line.length() > 16) { streamtiptoken = line.substring(15); } if (line.startsWith("streamtipid=") && line.length() > 13) { streamtipid = line.substring(12); } if (line.startsWith("webenable=") && line.length() > 11) { webenable = Boolean.valueOf(line.substring(10)); } if (line.startsWith("musicenable=") && line.length() > 13) { musicenable = Boolean.valueOf(line.substring(12)); } if (line.startsWith("usehttps=") && line.length() > 10) { usehttps = Boolean.valueOf(line.substring(9)); } if (line.startsWith("mysqlhost=") && line.length() > 11) { mySqlHost = line.substring(10); } if (line.startsWith("mysqlport=") && line.length() > 11) { mySqlPort = line.substring(10); } if (line.startsWith("mysqlname=") && line.length() > 11) { mySqlName = line.substring(10); } if (line.startsWith("mysqluser=") && line.length() > 11) { mySqlUser = line.substring(10); } if (line.startsWith("mysqlpass=") && line.length() > 11) { mySqlPass = line.substring(10); } if (line.startsWith("keystorepath=") && line.length() > 14) { keystorepath = line.substring(13); } if (line.startsWith("keystorepassword=") && line.length() > 18) { keystorepassword = line.substring(17); } if (line.startsWith("webauth=") && line.length() > 9) { webauth = line.substring(8); } if (line.startsWith("webauthro=") && line.length() > 11) { webauthro = line.substring(10); } if (line.startsWith("discordtoken=") && line.length() >= 14) { discordToken = line.substring(13); } if (line.startsWith("discordmainchannel=") && line.length() >= 20) { discordMainChannel = line.substring(19); } } } } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } /** * Check to see if there's a soundboardauth set */ if (webauth.isEmpty()) { webauth = generateWebAuth(); com.gmt2001.Console.debug.println("New webauth key has been generated for botlogin.txt"); changed = true; } /** * Check to see if there's a soundboardauthread set */ if (webauthro.isEmpty()) { webauthro = generateWebAuth(); com.gmt2001.Console.debug.println("New webauth read-only key has been generated for botlogin.txt"); changed = true; } try { if (user.isEmpty()) { com.gmt2001.Console.out.print("Please enter the bot's twitch username: "); user = System.console().readLine().trim().toLowerCase(); changed = true; } if (oauth.isEmpty()) { com.gmt2001.Console.out.println( "Visit http://quorrabot.com/pages/twitchapi/ to generate oAuth tokens for both the bot and the channel owner accounts (including 'oauth:') & type it below."); com.gmt2001.Console.out .println("IMPORTANT: This MUST be done while logged in as the BOT account!" + "\n"); com.gmt2001.Console.out.println("Please enter the bot's tmi oauth token: "); oauth = System.console().readLine().trim(); changed = true; } if (channelName.isEmpty()) { com.gmt2001.Console.out.print( "Please enter the name of the twitch channel the bot should join (not the url, just the name): "); channelName = System.console().readLine().trim().toLowerCase(); changed = true; } if (apioauth.isEmpty()) { com.gmt2001.Console.out.println( "Visit http://quorrabot.com/pages/twitchapi/ to generate oAuth tokens for both the bot and the channel owner accounts (including 'oauth:') & type it below."); com.gmt2001.Console.out.println( "IMPORTANT: This MUST be done while logged in on the CHANNEL OWNER account!" + "\n"); com.gmt2001.Console.out.println("Please enter the channel owner's tmi oauth token: "); apioauth = System.console().readLine().trim(); changed = true; } } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } if (owner.isEmpty()) { owner = channelName; changed = true; } if (args.length > 0) { for (String arg : args) { if (arg.equalsIgnoreCase("printlogin")) { com.gmt2001.Console.out.println("user='" + user + "'"); com.gmt2001.Console.out.println("oauth='" + oauth + "'"); com.gmt2001.Console.out.println("apioauth='" + apioauth + "'"); com.gmt2001.Console.out.println("clientid='" + clientid + "'"); com.gmt2001.Console.out.println("channel='" + channelName + "'"); com.gmt2001.Console.out.println("owner='" + owner + "'"); com.gmt2001.Console.out.println("baseport='" + baseport + "'"); com.gmt2001.Console.out.println("ip='" + ip.getHostAddress() + "'"); com.gmt2001.Console.out.println("hostname='" + hostname + "'"); com.gmt2001.Console.out.println("port='" + port + "'"); com.gmt2001.Console.out.println("msglimit30='" + msglimit30 + "'"); com.gmt2001.Console.out.println("datastore='" + datastore + "'"); com.gmt2001.Console.out.println("youtubekey='" + youtubekey + "'"); com.gmt2001.Console.out.println("gamewispauth=" + gamewispauth + "'"); com.gmt2001.Console.out.println("gamewisprefresh=" + gamewisprefresh + "'"); com.gmt2001.Console.out.println("twitchalertstoken='" + twitchalertstoken + "'"); com.gmt2001.Console.out.println("lastfmuser='" + lastfmuser + "'"); com.gmt2001.Console.out.println("tpetoken='" + tpetoken + "'"); com.gmt2001.Console.out.println("twittertoken='" + twittertoken + "'"); com.gmt2001.Console.out.println("twittertokensecret='" + twittertokensecret + "'"); com.gmt2001.Console.out.println("streamtiptoken='" + streamtiptoken + "'"); com.gmt2001.Console.out.println("streamtipid='" + streamtipid + "'"); com.gmt2001.Console.out.println("webenable=" + webenable); com.gmt2001.Console.out.println("musicenable=" + musicenable); com.gmt2001.Console.out.println("usehttps=" + usehttps); com.gmt2001.Console.out.println("keystorepath='" + keystorepath + "'"); com.gmt2001.Console.out.println("keystorepassword='" + keystorepassword + "'"); com.gmt2001.Console.out.println("discordtoken='" + discordToken + "'"); com.gmt2001.Console.out.println("discordmainchannel='" + discordMainChannel + "'"); } if (arg.equalsIgnoreCase("debugon")) { Quorrabot.enableDebugging = true; } if (arg.equalsIgnoreCase("ini2sqlite")) { com.gmt2001.Console.out.println("Converting default IniStore to default SqliteStore..."); ini2sqlite(false); com.gmt2001.Console.out.println("Operation complete. The bot will now exit"); System.exit(0); return; } if (arg.toLowerCase().startsWith("user=") && arg.length() > 8) { if (!user.equals(arg.substring(5))) { user = arg.substring(5).toLowerCase(); changed = true; } } if (arg.toLowerCase().startsWith("oauth=") && arg.length() > 9) { if (!oauth.equals(arg.substring(6))) { oauth = arg.substring(6); changed = true; } } if (arg.toLowerCase().startsWith("apioauth=") && arg.length() > 12) { if (!apioauth.equals(arg.substring(9))) { apioauth = arg.substring(9); changed = true; } } if (arg.toLowerCase().startsWith("mysqlhost=") && arg.length() > 11) { if (!mySqlHost.equals(arg.substring(10))) { mySqlHost = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("mysqlport=") && arg.length() > 11) { if (!mySqlPort.equals(arg.substring(10))) { mySqlPort = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("mysqlname=") && arg.length() > 11) { if (!mySqlName.equals(arg.substring(10))) { mySqlName = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("mysqluser=") && arg.length() > 11) { if (!mySqlUser.equals(arg.substring(14))) { mySqlUser = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("mysqlpass=") && arg.length() > 11) { if (!mySqlPass.equals(arg.substring(10))) { mySqlPass = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("clientid=") && arg.length() > 12) { if (!clientid.equals(arg.substring(9))) { clientid = arg.substring(9); changed = true; } } if (arg.toLowerCase().startsWith("channel=") && arg.length() > 11) { if (!channelName.equals(arg.substring(8))) { channelName = arg.substring(8).toLowerCase(); changed = true; } } if (arg.toLowerCase().startsWith("owner=") && arg.length() > 9) { if (!owner.equals(arg.substring(6))) { owner = arg.substring(6).toLowerCase(); changed = true; } } if (arg.toLowerCase().startsWith("baseport=") && arg.length() > 10) { if (baseport != Integer.parseInt(arg.substring(9))) { baseport = Integer.parseInt(arg.substring(9)); changed = true; } } if (arg.toLowerCase().startsWith("ip=") && arg.length() > 4) { if (ip != InetAddress.getByName(arg.substring(3))) { ip = InetAddress.getByName(arg.substring(3)); changed = true; } } if (arg.toLowerCase().startsWith("hostname=") && arg.length() > 10) { if (!hostname.equals(arg.substring(9))) { hostname = arg.substring(9); changed = true; } } if (arg.toLowerCase().startsWith("port=") && arg.length() > 6) { if (port != Integer.parseInt(arg.substring(5))) { port = Integer.parseInt(arg.substring(5)); changed = true; } } if (arg.toLowerCase().startsWith("msglimit30=") && arg.length() > 12) { if (msglimit30 != Double.parseDouble(arg.substring(11))) { msglimit30 = Double.parseDouble(arg.substring(11)); changed = true; } } if (arg.toLowerCase().startsWith("datastore=") && arg.length() > 11) { if (!datastore.equals(arg.substring(10))) { datastore = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("datastoreconfig=") && arg.length() > 17) { datastoreconfig = arg.substring(16); } if (arg.toLowerCase().startsWith("youtubekey=") && arg.length() > 12) { if (!youtubekey.equals(arg.substring(11))) { youtubekey = arg.substring(11); changed = true; } } if (arg.toLowerCase().startsWith("gamewispauth=") && arg.length() > 14) { if (!gamewispauth.equals(arg.substring(13))) { gamewispauth = arg.substring(13); changed = true; } } if (arg.toLowerCase().startsWith("gamewisprefresh=") && arg.length() > 17) { if (!gamewisprefresh.equals(arg.substring(16))) { gamewisprefresh = arg.substring(16); changed = true; } } if (arg.toLowerCase().startsWith("twitchalertstoken=") && arg.length() > 19) { if (!twitchalertstoken.equals(arg.substring(18))) { twitchalertstoken = arg.substring(18); changed = true; } } if (arg.toLowerCase().startsWith("lastfmuser=") && arg.length() > 12) { if (!lastfmuser.equals(arg.substring(11))) { lastfmuser = arg.substring(11); changed = true; } } if (arg.toLowerCase().startsWith("tpetoken=") && arg.length() > 10) { if (!tpetoken.equals(arg.substring(9))) { tpetoken = arg.substring(9); changed = true; } } if (arg.toLowerCase().startsWith("twittertoken=") && arg.length() > 14) { if (!twittertoken.equals(arg.substring(13))) { twittertoken = arg.substring(13); changed = true; } } if (arg.toLowerCase().startsWith("twittertokensecret=") && arg.length() > 20) { if (!twittertokensecret.equals(arg.substring(19))) { twittertokensecret = arg.substring(19); changed = true; } } if (arg.toLowerCase().startsWith("streamtiptoken=") && arg.length() > 16) { if (!streamtiptoken.equals(arg.substring(15))) { streamtiptoken = arg.substring(15); changed = true; } } if (arg.toLowerCase().startsWith("streamtipid=") && arg.length() > 13) { if (!streamtipid.equals(arg.substring(12))) { streamtipid = arg.substring(12); changed = true; } } if (arg.toLowerCase().startsWith("webenable=") && arg.length() > 11) { if (webenable != Boolean.valueOf(arg.substring(10))) { webenable = Boolean.valueOf(arg.substring(10)); changed = true; } } if (arg.toLowerCase().startsWith("musicenable=") && arg.length() > 13) { if (musicenable != Boolean.valueOf(arg.substring(12))) { musicenable = Boolean.valueOf(arg.substring(12)); changed = true; } } if (arg.toLowerCase().startsWith("usehttps=") && arg.length() > 10) { if (usehttps != Boolean.valueOf(arg.substring(9))) { usehttps = Boolean.valueOf(arg.substring(9)); changed = true; } } if (arg.toLowerCase().startsWith("keystorepath=") && arg.length() > 14) { if (!keystorepath.equals(arg.substring(13))) { keystorepath = arg.substring(13); changed = true; } } if (arg.toLowerCase().startsWith("keystorepassword=") && arg.length() > 18) { if (!keystorepassword.equals(arg.substring(17))) { keystorepassword = arg.substring(17); changed = true; } } if (arg.equalsIgnoreCase("help") || arg.equalsIgnoreCase("--help") || arg.equalsIgnoreCase("-h") || arg.equalsIgnoreCase("-?")) { com.gmt2001.Console.out.println( "Usage: java -Dfile.encoding=UTF-8 -jar QuorraBot.jar [printlogin] [user=<bot username>] " + "[oauth=<bot irc oauth>] [apioauth=<editor oauth>] [clientid=<oauth clientid>] [channel=<channel to join>] " + "[owner=<bot owner username>] [baseport=<bot webserver port, music server will be +1>] [ip=<IP address (optional) to bind to>] [hostname=<custom irc server>] " + "[port=<custom irc port>] [msglimit30=<message limit per 30 seconds>] " + "[datastore=<DataStore type, for a list, run java -jar QuorraBot.jar storetypes>] " + "[datastoreconfig=<Optional DataStore config option, different for each DataStore type>] " + "[youtubekey=<youtube api key>] [webenable=<true | false>] [musicenable=<true | false>] " + "[gamewispauth=<gamewisp oauth>] " + "[gamewisprefresh=<gamewisp refresh key>] " + "[twitchalertstoken=<TwitchAlerts access token>] " + "[lastfmuser=<Last.FM username>] " + "[tpetoken=<Tipeeestream access token>] " + "[streamtiptoken=<StreamTip access token>] " + "[streamtipid=<StreamTip Client ID>] " + "[twittertoken=<Twitter access token>] " + "[twittertokensecret=<Twitter access token secret>]"); return; } if (arg.equalsIgnoreCase("storetypes")) { com.gmt2001.Console.out.println( "DataStore types: IniStore (datastoreconfig parameter is folder name, stores in .ini files), " + "TempStore (Stores in memory, lost on shutdown), " + "SqliteStore (Default, Stores in a SQLite3 database, datastoreconfig parameter is a config file"); return; } } } if (changed) { String data = ""; data += "user=" + user + "\r\n"; data += "oauth=" + oauth + "\r\n"; data += "apioauth=" + apioauth + "\r\n"; data += "clientid=" + clientid + "\r\n"; data += "webauth=" + webauth + "\r\n"; data += "webauthro=" + webauthro + "\r\n"; data += "channel=" + channelName + "\r\n"; data += "owner=" + owner + "\r\n"; data += "baseport=" + baseport + "\r\n"; data += "ip=" + ip.getHostAddress() + "\r\n"; data += "hostname=" + hostname + "\r\n"; data += "port=" + port + "\r\n"; data += "msglimit30=" + msglimit30 + "\r\n"; data += "datastore=" + datastore + "\r\n"; data += "youtubekey=" + youtubekey + "\r\n"; data += "gamewispauth=" + gamewispauth + "\r\n"; data += "gamewisprefresh=" + gamewisprefresh + "\r\n"; data += "twitchalertstoken=" + twitchalertstoken + "\r\n"; data += "lastfmuser=" + lastfmuser + "\r\n"; data += "tpetoken=" + tpetoken + "\r\n"; data += "twittertoken=" + twittertoken + "\r\n"; data += "twittertokensecret=" + twittertokensecret + "\r\n"; data += "streamtiptoken=" + streamtiptoken + "\r\n"; data += "streamtipid=" + streamtipid + "\r\n"; data += "webenable=" + webenable + "\r\n"; data += "musicenable=" + musicenable + "\r\n"; data += "usehttps=" + usehttps + "\r\n"; data += "logtimezone=" + timeZone + "\r\n"; data += "mysqlhost=" + mySqlHost + "\r\n"; data += "mysqlport=" + mySqlPort + "\r\n"; data += "mysqlname=" + mySqlName + "\r\n"; data += "mysqluser=" + mySqlUser + "\r\n"; data += "mysqlpass=" + mySqlPass + "\r\n"; data += "keystorepath=" + keystorepath + "\r\n"; data += "keystorepassword=" + keystorepassword + "\r\n"; data += "discordtoken=" + discordToken + "\r\n"; data += "discordmainchannel=" + discordMainChannel; Files.write(Paths.get("./botlogin.txt"), data.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } channelUsersCache = ChannelUsersCache.instance(owner); followersCache = FollowersCache.instance(owner); hostCache = ChannelHostCache.instance(owner); subscribersCache = SubscribersCache.instance(owner); Quorrabot.instance = new Quorrabot(user, oauth, apioauth, clientid, channelName, owner, baseport, ip, hostname, port, msglimit30, datastore, datastoreconfig, youtubekey, gamewispauth, gamewisprefresh, twitchalertstoken, lastfmuser, tpetoken, twittertoken, twittertokensecret, streamtiptoken, streamtipid, webenable, webauth, webauthro, musicenable, usehttps, timeZone, mySqlHost, mySqlPort, mySqlConn, mySqlPass, mySqlUser, mySqlName, keystorepath, followersCache, hostCache, channelUsersCache, subscribersCache, discordToken, discordMainChannel); }