Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.29 KB | None | 0 0
  1. package dev.espi.ebackup;
  2.  
  3. import com.jcraft.jsch.*;
  4. import org.apache.commons.net.ftp.FTPClient;
  5. import org.bukkit.Bukkit;
  6. import org.bukkit.World;
  7.  
  8. import java.io.File;
  9. import java.io.FileInputStream;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.nio.file.Paths;
  13. import java.text.SimpleDateFormat;
  14. import java.util.*;
  15. import java.util.concurrent.atomic.AtomicBoolean;
  16. import java.util.zip.ZipEntry;
  17. import java.util.zip.ZipOutputStream;
  18.  
  19. /*
  20. Copyright 2019 EstiNet
  21.  
  22. Licensed under the Apache License, Version 2.0 (the "License");
  23. you may not use this file except in compliance with the License.
  24. You may obtain a copy of the License at
  25.  
  26. http://www.apache.org/licenses/LICENSE-2.0
  27.  
  28. Unless required by applicable law or agreed to in writing, software
  29. distributed under the License is distributed on an "AS IS" BASIS,
  30. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  31. See the License for the specific language governing permissions and
  32. limitations under the License.
  33.  
  34. */
  35.  
  36. public class BackupUtil {
  37.  
  38. // delete old backups (when limit reached)
  39. private static void checkMaxBackups() {
  40. if (eBackup.getPlugin().maxBackups <= 0) return;
  41.  
  42. int backups = 0;
  43. SortedMap<Long, File> m = new TreeMap<>(); // oldest files to newest
  44.  
  45. for (File f : eBackup.getPlugin().backupPath.listFiles()) {
  46. if (f.getName().endsWith(".zip")) {
  47. backups++;
  48. m.put(f.lastModified(), f);
  49. }
  50. }
  51.  
  52. // delete old backups
  53. while (backups-- >= eBackup.getPlugin().maxBackups) {
  54. m.get(m.firstKey()).delete();
  55. m.remove(m.firstKey());
  56. }
  57. }
  58.  
  59. // upload single file
  60. // run async plz
  61. public static void doFileUpload() {
  62. eBackup.getPlugin().getLogger().info("Starting file upload...");
  63. try {
  64. // check if file exists before uploading
  65. if (!new File(eBackup.getPlugin().filePath).exists())
  66. {
  67. eBackup.getPlugin().getLogger().info("File not found...");
  68. return;
  69. }
  70. // upload to ftp/sftp
  71. if (eBackup.getPlugin().fileEnable && eBackup.getPlugin().ftpEnable) {
  72.  
  73. if (eBackup.getPlugin().ftpType.equals("sftp")) {
  74. eBackup.getPlugin().getLogger().info("Uploading file to SFTP server...");
  75. uploadSFTP(new File(eBackup.getPlugin().filePath));
  76. } else if (eBackup.getPlugin().fileEnable && eBackup.getPlugin().ftpType.equals("ftp")) {
  77. eBackup.getPlugin().getLogger().info("Uploading backup to FTP server...");
  78. uploadFTP(new File(eBackup.getPlugin().filePath));
  79. }
  80. }
  81.  
  82. } catch (Exception e) {
  83. e.printStackTrace();
  84. } finally {
  85. for (World w : Bukkit.getWorlds()) {
  86. w.setAutoSave(true);
  87. }
  88. }
  89. eBackup.getPlugin().getLogger().info("File upload complete!");
  90. }
  91.  
  92. // actually do the backup
  93. // run async plz
  94. public static void doBackup(boolean uploadToServer) {
  95. List<File> tempIgnore = new ArrayList<>();
  96. eBackup.getPlugin().getLogger().info("Starting backup...");
  97. try {
  98. // find plugin data to ignore
  99. for (File f : new File("plugins").listFiles()) {
  100. if ((!eBackup.getPlugin().backupPluginJars && f.getName().endsWith(".jar")) || (!eBackup.getPlugin().backupPluginConfs && f.isDirectory())) {
  101. tempIgnore.add(f);
  102. eBackup.getPlugin().ignoredFiles.add(f);
  103. }
  104. }
  105.  
  106. // delete old backups
  107. checkMaxBackups();
  108.  
  109. // zip
  110. String fileName = eBackup.getPlugin().backupFormat.replace("{DATE}", new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date()));
  111. FileOutputStream fos = new FileOutputStream(eBackup.getPlugin().backupPath + "/" + fileName + ".zip");
  112. ZipOutputStream zipOut = new ZipOutputStream(fos);
  113.  
  114. // backup worlds first
  115. for (World w : Bukkit.getWorlds()) {
  116. File world = new File(w.getName());
  117. // check if world is in ignored list
  118. boolean skip = false;
  119. for (File f : eBackup.getPlugin().ignoredFiles) {
  120. if (f.getAbsolutePath().equals(world.getAbsolutePath())) {
  121. skip = true;
  122. break;
  123. }
  124. }
  125. if (skip) continue;
  126.  
  127. AtomicBoolean saved = new AtomicBoolean(false);
  128. Bukkit.getScheduler().runTask(eBackup.getPlugin(), () -> {
  129. w.save();
  130. saved.set(true);
  131. });
  132.  
  133. while (!saved.get()) Thread.sleep(500);
  134.  
  135. w.setAutoSave(false); // make sure autosave doesn't screw everything over
  136. eBackup.getPlugin().getLogger().info("Backing up world " + world.getName() + "...");
  137. zipFile(world, world.getName(), zipOut);
  138. w.setAutoSave(true);
  139.  
  140. // ignore in dfs
  141. tempIgnore.add(world);
  142. eBackup.getPlugin().ignoredFiles.add(world);
  143. }
  144.  
  145. // dfs all other files
  146. eBackup.getPlugin().getLogger().info("Backing up other files...");
  147. zipFile(new File(Paths.get(".").toAbsolutePath().normalize().toString()), "", zipOut);
  148. zipOut.close();
  149. fos.close();
  150.  
  151. // upload to ftp/sftp
  152. if (uploadToServer && eBackup.getPlugin().ftpEnable) {
  153. if (eBackup.getPlugin().ftpType.equals("sftp")) {
  154. eBackup.getPlugin().getLogger().info("Uploading backup to SFTP server...");
  155. uploadSFTP(new File(eBackup.getPlugin().backupPath + "/" + fileName + ".zip"));
  156. } else if (uploadToServer && eBackup.getPlugin().ftpType.equals("ftp")) {
  157. eBackup.getPlugin().getLogger().info("Uploading backup to FTP server...");
  158. uploadFTP(new File(eBackup.getPlugin().backupPath + "/" + fileName + ".zip"));
  159. }
  160. }
  161.  
  162. } catch (Exception e) {
  163. e.printStackTrace();
  164. } finally {
  165. for (World w : Bukkit.getWorlds()) {
  166. w.setAutoSave(true);
  167. }
  168. // restore tempignore
  169. for (File f : tempIgnore) {
  170. eBackup.getPlugin().ignoredFiles.remove(f);
  171. }
  172. }
  173. eBackup.getPlugin().getLogger().info("Backup complete!");
  174. }
  175.  
  176. private static void uploadSFTP(File f) throws JSchException, SftpException {
  177. JSch jsch = new JSch();
  178. Session session = jsch.getSession(eBackup.getPlugin().ftpUser, eBackup.getPlugin().ftpHost, eBackup.getPlugin().ftpPort);
  179. session.setPassword(eBackup.getPlugin().ftpPass);
  180. session.setConfig("StrictHostKeyChecking", "no");
  181. session.connect();
  182. Channel channel = session.openChannel("sftp");
  183. channel.connect();
  184. ChannelSftp sftpChannel = (ChannelSftp) channel;
  185. sftpChannel.put(f.getAbsolutePath(), eBackup.getPlugin().ftpPath + "/" + f.getName());
  186. sftpChannel.exit();
  187. session.disconnect();
  188. }
  189.  
  190. private static void uploadFTP(File f) {
  191. FTPClient ftpClient = new FTPClient();
  192. try (FileInputStream fio = new FileInputStream(f)) {
  193. ftpClient.connect(eBackup.getPlugin().ftpHost, eBackup.getPlugin().ftpPort);
  194. ftpClient.login(eBackup.getPlugin().ftpUser, eBackup.getPlugin().ftpPass);
  195. ftpClient.storeFile(f.getAbsolutePath(), fio);
  196. } catch (Exception e) {
  197. e.printStackTrace();
  198. } finally {
  199. try {
  200. ftpClient.disconnect();
  201. } catch (IOException e) {
  202. e.printStackTrace();
  203. }
  204. }
  205. }
  206.  
  207. // recursively compress files and directories
  208. private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {
  209. if (fileToZip.isHidden() && !fileToZip.getPath().equals(".")) return;
  210. for (File f : eBackup.getPlugin().ignoredFiles) { // return if it is ignored file
  211. if (f.getAbsolutePath().equals(fileToZip.getAbsolutePath())) return;
  212. }
  213.  
  214. if (fileToZip.isDirectory()) { // recursively search
  215. if (fileName.endsWith("/")) {
  216. zipOut.putNextEntry(new ZipEntry(fileName));
  217. zipOut.closeEntry();
  218. } else {
  219. zipOut.putNextEntry(new ZipEntry(fileName + "/"));
  220. zipOut.closeEntry();
  221. }
  222. File[] children = fileToZip.listFiles();
  223. for (File childFile : children) {
  224. zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
  225. }
  226. return;
  227. }
  228. FileInputStream fis = new FileInputStream(fileToZip);
  229. ZipEntry zipEntry = new ZipEntry(fileName);
  230. zipOut.putNextEntry(zipEntry);
  231. byte[] bytes = new byte[1024];
  232. int length;
  233. while ((length = fis.read(bytes)) >= 0) {
  234. zipOut.write(bytes, 0, length);
  235. }
  236. fis.close();
  237. }
  238. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement