Advertisement
Guest User

Untitled

a guest
Aug 25th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.24 KB | None | 0 0
  1. private final FazonPlusCore core;
  2. private final Logger logger;
  3. private final Path workingDir;
  4.  
  5. private final NetworkManager network;
  6.  
  7. private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
  8.  
  9. private boolean started;
  10.  
  11. private boolean playerTracking;
  12. private ImmutableList<String> loginMessages;
  13.  
  14. // Favicon cache
  15. private final CacheLoader<FaviconSource, Optional<String>> faviconLoader =
  16. new CacheLoader<FaviconSource, Optional<String>>() {
  17. @Override
  18. public Optional<String> load(FaviconSource source) throws Exception {
  19. // Try loading the favicon
  20. BufferedImage image = FaviconHelper.loadSafely(core, source);
  21. if (image == null) return Optional.empty(); // Favicon loading failed
  22. else return Optional.of(Favicon.create(image));
  23. }
  24. };
  25. private LoadingCache<FaviconSource, Optional<String>> faviconCache;
  26.  
  27. public FazonPlusServer(Logger logger) throws UnknownHostException {
  28. checkState(instance == null, "Server was already initialized");
  29. instance = this;
  30.  
  31. this.logger = logger;
  32. this.workingDir = Paths.get("");
  33.  
  34. logger.log(INFO, "Loading...");
  35. this.core = new FazonPlusCore(this, new ServerProfileManager());
  36.  
  37. ServerConf conf = this.core.getConf(ServerConf.class);
  38. this.network = new NetworkManager(this, Netty.parseAddress(conf.Address));
  39. logger.log(INFO, "Successfully loaded!");
  40. }
  41.  
  42. public boolean start() {
  43. this.started = true;
  44. Runtime.getRuntime().addShutdownHook(new Thread(this::stop));
  45.  
  46. try {
  47. this.network.start();
  48. } catch (Exception e) {
  49. this.logger.log(ERROR, "Failed to start network manager", e);
  50. this.stop();
  51. return false;
  52. }
  53.  
  54. core.setBanProvider(new NoBanProvider());
  55.  
  56. return true;
  57. }
  58.  
  59. public void join() throws InterruptedException {
  60. this.network.join();
  61. }
  62.  
  63. public boolean stop() {
  64. if (this.started) {
  65. this.logger.info("Stopping...");
  66.  
  67. try {
  68. this.network.stop();
  69. } catch (Exception e) {
  70. this.logger.log(ERROR, "Failed to stop network manager", e);
  71. return false;
  72. }
  73.  
  74. this.core.stop();
  75.  
  76. this.started = false;
  77. return true;
  78. }
  79.  
  80. return false;
  81. }
  82.  
  83. public static StatusPingResponse postLegacy(InetSocketAddress address, InetSocketAddress virtualHost) {
  84. StatusPingResponse response = instance.handle(new StatusClient(address, OptionalInt.empty(), virtualHost));
  85. response.getVersion().setProtocol(Byte.MAX_VALUE);
  86. if (response.getPlayers() == null) {
  87. response.setPlayers(new StatusPingResponse.Players(0, -1, null));
  88. }
  89. return response;
  90. }
  91.  
  92. public static StatusPingResponse post(StatusClient client) {
  93. return instance.handle(client);
  94. }
  95.  
  96. public static String postLogin(StatusClient client, String name) {
  97. return instance.handleLogin(client, name);
  98. }
  99.  
  100. public String handleLogin(StatusClient client, String name) {
  101. if (this.playerTracking) {
  102. core.updateClient(client.getAddress().getAddress(), null, name);
  103. }
  104.  
  105. String message = Randoms.nextEntry(this.loginMessages);
  106. return Literals.replace(message, "%player%", name);
  107. }
  108.  
  109. public StatusPingResponse handle(StatusClient client) {
  110. StatusPingResponse ping = new StatusPingResponse();
  111.  
  112. StatusRequest request = core.createRequest(client.getAddress().getAddress());
  113. client.getProtocol().ifPresent(request::setProtocolVersion);
  114.  
  115. InetSocketAddress host = client.getVirtualHost();
  116. if (host != null) {
  117. request.setTarget(host);
  118. }
  119.  
  120. final StatusPingResponse.Players players = ping.getPlayers();
  121. final StatusPingResponse.Version version = ping.getVersion();
  122.  
  123. StatusResponse response = request.createResponse(core.getStatus(),
  124. // Return unknown player counts if it has been hidden
  125. new ResponseFetcher() {
  126. @Override
  127. public Integer getOnlinePlayers() {
  128. return players != null ? players.getOnline() : null;
  129. }
  130.  
  131. @Override
  132. public Integer getMaxPlayers() {
  133. return players != null ? players.getMax() : null;
  134. }
  135.  
  136. @Override
  137. public int getProtocolVersion() {
  138. return version != null ? version.getProtocol() : 0;
  139. }
  140. });
  141.  
  142. // Description
  143. String message = response.getDescription();
  144. if (message != null) ping.setDescription(message);
  145.  
  146. if (version != null) {
  147. // Version name
  148. message = response.getVersion();
  149. if (message != null) version.setName(message);
  150. // Protocol version
  151. Integer protocol = response.getProtocolVersion();
  152. if (protocol != null) version.setProtocol(protocol);
  153. }
  154.  
  155. // Favicon
  156. FaviconSource favicon = response.getFavicon();
  157. if (favicon != null) {
  158. Optional<String> icon = faviconCache.getUnchecked(favicon);
  159. if (icon.isPresent()) ping.setFavicon(icon.get());
  160. }
  161.  
  162. if (response.hidePlayers()) {
  163. ping.setPlayers(null);
  164. } else {
  165. StatusPingResponse.Players newPlayers = players;
  166. if (newPlayers == null) {
  167. newPlayers = new StatusPingResponse.Players(0, 0, null);
  168. ping.setPlayers(newPlayers);
  169. }
  170.  
  171. // Online players
  172. Integer count = response.getOnlinePlayers();
  173. if (count != null) newPlayers.setOnline(count);
  174. // Max players
  175. count = response.getMaxPlayers();
  176. if (count != null) newPlayers.setMax(count);
  177.  
  178. // Player hover
  179. message = response.getPlayerHover();
  180. if (message != null && !message.isEmpty()) {
  181. if (response.useMultipleSamples()) {
  182. count = response.getDynamicSamples();
  183. List<String> lines = count != null ? Helper.splitLinesCached(message, count) :
  184. Helper.splitLinesCached(message);
  185.  
  186. UserProfile[] sample = new UserProfile[lines.size()];
  187. for (int i = 0; i < sample.length; i++)
  188. sample[i] = new UserProfile(lines.get(i), StatusManager.EMPTY_UUID);
  189.  
  190. newPlayers.setSample(sample);
  191. } else
  192. newPlayers.setSample(new UserProfile[]{
  193. new UserProfile(message, StatusManager.EMPTY_UUID) });
  194. }
  195. }
  196.  
  197. return ping;
  198. }
  199.  
  200. private static final ImmutableSet<String> COMMAND_ALIASES = ImmutableSet.of("Fazonplus", "serverlist+",
  201. "serverlist", "slp", "sl+", "s++", "serverping+", "serverping", "spp", "slus");
  202. private static final Splitter COMMAND_SPLITTER = Splitter.on(' ').trimResults().omitEmptyStrings();
  203.  
  204. public boolean processCommand(String command) {
  205. if (command.charAt(0) == '/') {
  206. command = command.substring(1);
  207. }
  208.  
  209. String root = command;
  210. int pos = command.indexOf(' ');
  211. if (pos >= 0) {
  212. root = command.substring(0, pos).toLowerCase(Locale.ENGLISH);
  213. }
  214.  
  215. if (COMMAND_ALIASES.contains(root)) {
  216. if (pos >= 0) {
  217. command = command.substring(pos + 1);
  218. } else {
  219. command = "";
  220. }
  221. } else {
  222. root = "Fazonplus";
  223. }
  224.  
  225. command = command.trim();
  226. List<String> args = COMMAND_SPLITTER.splitToList(command);
  227. String subcommand = args.isEmpty() ? "" : args.get(0);
  228. if (subcommand.equalsIgnoreCase("stop")) {
  229. return this.stop();
  230. }
  231.  
  232. this.core.executeCommand(ConsoleCommandSender.INSTANCE, root, args.toArray(new String[args.size()]));
  233. if (subcommand.equalsIgnoreCase("help")) {
  234. ConsoleCommandSender.INSTANCE.sendMessage("/slp stop - Stop the server.");
  235. }
  236.  
  237. return false;
  238. }
  239.  
  240. @Override
  241. public FazonPlusCore getCore() {
  242. return this.core;
  243. }
  244.  
  245. @Override
  246. public ServerType getServerType() {
  247. return ServerType.SERVER;
  248. }
  249.  
  250. @Override
  251. public String getServerImplementation() {
  252. return "FazonPlusServer";
  253. }
  254.  
  255. @Override
  256. public Path getPluginFolder() {
  257. return this.workingDir;
  258. }
  259.  
  260. @Override
  261. public Integer getOnlinePlayers(String location) {
  262. return null;
  263. }
  264.  
  265. @Override
  266. public Iterator<String> getRandomPlayers() {
  267. return null;
  268. }
  269.  
  270. @Override
  271. public Iterator<String> getRandomPlayers(String location) {
  272. return null;
  273. }
  274.  
  275. @Override
  276. public Cache<?, ?> getRequestCache() {
  277. return null;
  278. }
  279.  
  280. @Override
  281. public LoadingCache<FaviconSource, Optional<String>> getFaviconCache() {
  282. return this.faviconCache;
  283. }
  284.  
  285. @Override
  286. public void runAsync(Runnable task) {
  287. this.scheduler.execute(task);
  288. }
  289.  
  290. @Override
  291. public ScheduledTask scheduleAsync(Runnable task, long repeat, TimeUnit unit) {
  292. return new ScheduledFutureTask(this.scheduler.scheduleAtFixedRate(task, 0, repeat, unit));
  293. }
  294.  
  295. @Override
  296. public String colorize(String s) {
  297. return FormattingCodes.colorize(s);
  298. }
  299.  
  300. @Override
  301. public FazonPlusLogger createLogger(FazonPlusCore core) {
  302. return new JavaFazonPlusLogger(this.core, this.logger);
  303. }
  304.  
  305. @Override
  306. public void initialize(FazonPlusCore core) {
  307. core.registerConf(ServerConf.class, new ServerConf(), ServerConf.getExample(), "Server");
  308. }
  309.  
  310. @Override
  311. public void reloadCaches(FazonPlusCore core) {
  312.  
  313. }
  314.  
  315. @Override
  316. public void reloadFaviconCache(CacheBuilderSpec spec) {
  317. if (spec != null) {
  318. this.faviconCache = CacheBuilder.from(spec).build(faviconLoader);
  319. } else {
  320. // Delete favicon cache
  321. faviconCache.invalidateAll();
  322. faviconCache.cleanUp();
  323. this.faviconCache = null;
  324. }
  325. }
  326.  
  327. @Override
  328. public void configChanged(FazonPlusCore core, InstanceStorage<Object> confs) {
  329. this.playerTracking = confs.get(PluginConf.class).PlayerTracking.Enabled;
  330.  
  331. ServerConf conf = confs.get(ServerConf.class);
  332.  
  333. ImmutableList.Builder<String> builder = ImmutableList.builder();
  334. for (String message : conf.Login.Message) {
  335. builder.add(ReplacementManager.replaceStatic(core, message));
  336. }
  337.  
  338. this.loginMessages = builder.build();
  339. }
  340.  
  341. @Override
  342. public void statusChanged(StatusManager status, boolean hasChanges) {
  343.  
  344. }
  345. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement