summaryrefslogtreecommitdiffstats
path: root/Essentials/src/com/earth2me/essentials/EssentialsUpgrade.java
blob: 1ec9130a0ffef0b7ffbc286163c62b34b3434c82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package com.earth2me.essentials;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.inventory.ItemStack;


public class EssentialsUpgrade
{
	private static boolean alreadyRun = false;
	private final static Logger logger = Logger.getLogger("Minecraft");
	private Essentials ess;

	EssentialsUpgrade(String version, Essentials essentials)
	{
		if (alreadyRun == true)
		{
			return;
		}
		alreadyRun = true;
		ess = essentials;
		if (!ess.getDataFolder().exists())
		{
			ess.getDataFolder().mkdirs();
		}
		moveWorthValuesToWorthYml();
		sanitizeAllUserFilenames();
		updateUsersToNewDefaultHome();
		moveUsersDataToUserdataFolder();
		convertWarps();
	}

	private void moveWorthValuesToWorthYml()
	{
		try
		{
			File configFile = new File(ess.getDataFolder(), "config.yml");
			if (!configFile.exists())
			{
				return;
			}
			EssentialsConf conf = new EssentialsConf(configFile);
			conf.load();
			Worth w = new Worth(ess.getDataFolder());
			for (Material mat : Material.values())
			{
				int id = mat.getId();
				double value = conf.getDouble("worth-" + id, Double.NaN);
				if (!Double.isNaN(value))
				{
					w.setPrice(new ItemStack(mat, 1, (short)0, (byte)0), value);
				}
			}
			removeLinesFromConfig(configFile, "\\s*#?\\s*worth-[0-9]+.*", "# Worth values have been moved to worth.yml");
		}
		catch (Throwable e)
		{
			logger.log(Level.SEVERE, "Error while upgrading the files", e);
		}
	}

	private void removeLinesFromConfig(File file, String regex, String info) throws Exception
	{
		boolean needUpdate = false;
		BufferedReader br = new BufferedReader(new FileReader(file));
		File tempFile = File.createTempFile("essentialsupgrade", ".tmp.yml", ess.getDataFolder());
		BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
		do
		{
			String line = br.readLine();
			if (line == null)
			{
				break;
			}
			if (line.matches(regex))
			{
				if (needUpdate == false && info != null)
				{
					bw.write(info, 0, info.length());
					bw.newLine();
				}
				needUpdate = true;
			}
			else
			{
				if (line.endsWith("\r\n"))
				{
					bw.write(line, 0, line.length() - 2);
				}
				else if (line.endsWith("\r") || line.endsWith("\n"))
				{
					bw.write(line, 0, line.length() - 1);
				}
				else
				{
					bw.write(line, 0, line.length());
				}
				bw.newLine();
			}
		}
		while (true);
		br.close();
		bw.close();
		if (needUpdate)
		{
			if (!file.renameTo(new File(file.getParentFile(), file.getName().concat("." + System.currentTimeMillis() + ".upgradebackup"))))
			{
				throw new Exception("Failed to move config.yml to backup location.");
			}
			if (!tempFile.renameTo(file))
			{
				throw new Exception("Failed to rename temp file to config.yml");
			}
		} else {
			tempFile.delete();
		}
	}

	private void updateUsersToNewDefaultHome()
	{
		File userdataFolder = new File(ess.getDataFolder(), "userdata");
		if (!userdataFolder.exists() || !userdataFolder.isDirectory())
		{
			return;
		}
		File[] userFiles = userdataFolder.listFiles();

		for (File file : userFiles)
		{
			if (!file.isFile() || !file.getName().endsWith(".yml"))
			{
				continue;
			}
			EssentialsConf config = new EssentialsConf(file);
			config.load();
			if (config.hasProperty("home") && !config.hasProperty("home.default"))
			{
				@SuppressWarnings("unchecked")
				List<Object> vals = (List<Object>)config.getProperty("home");
				if (vals == null) {
					continue;
				}
				World world = ess.getServer().getWorlds().get(0);
				if (vals.size() > 5)
				{
					world = ess.getServer().getWorld((String)vals.get(5));
				}
				if (world != null)
				{
					Location loc = new Location(
							world,
							((Number)vals.get(0)).doubleValue(),
							((Number)vals.get(1)).doubleValue(),
							((Number)vals.get(2)).doubleValue(),
							((Number)vals.get(3)).floatValue(),
							((Number)vals.get(4)).floatValue());

					String worldName = world.getName().toLowerCase();
					if (worldName != null && !worldName.isEmpty())
					{
						config.removeProperty("home");
						config.setProperty("home.default", worldName);
						config.setProperty("home.worlds." + worldName, loc);
						config.save();
					}
				}
			}
		}
	}

	private void moveUsersDataToUserdataFolder()
	{
		File usersFile = new File(ess.getDataFolder(), "users.yml");
		if (!usersFile.exists())
		{
			return;
		}
		EssentialsConf usersConfig = new EssentialsConf(usersFile);
		usersConfig.load();
		for (String username : usersConfig.getKeys(null))
		{
			User user = new User(new OfflinePlayer(username), ess);
			String nickname = usersConfig.getString(username + ".nickname");
			if (nickname != null && !nickname.isEmpty() && !nickname.equals(username))
			{
				user.setNickname(nickname);
			}
			List<String> mails = usersConfig.getStringList(username + ".mail", null);
			if (mails != null && !mails.isEmpty())
			{
				user.setMails(mails);
			}
			if (!user.hasHome())
			{
				@SuppressWarnings("unchecked")
				List<Object> vals = (List<Object>)usersConfig.getProperty(username + ".home");
				if (vals != null) {
					World world = ess.getServer().getWorlds().get(0);
					if (vals.size() > 5)
					{
						world = ess.getWorld((String)vals.get(5));
					}
					if (world != null)
					{
						user.setHome(new Location(world,
												  ((Number)vals.get(0)).doubleValue(),
												  ((Number)vals.get(1)).doubleValue(),
												  ((Number)vals.get(2)).doubleValue(),
												  ((Number)vals.get(3)).floatValue(),
												  ((Number)vals.get(4)).floatValue()), true);
					}
				}
			}
		}
		usersFile.renameTo(new File(usersFile.getAbsolutePath() + ".old"));
	}

	private void convertWarps()
	{
		File warpsFolder = new File(ess.getDataFolder(), "warps");
		if (!warpsFolder.exists())
		{
			warpsFolder.mkdirs();
		}
		File[] listOfFiles = warpsFolder.listFiles();
		if (listOfFiles.length >= 1)
		{
			for (int i = 0; i < listOfFiles.length; i++)
			{
				String filename = listOfFiles[i].getName();
				if (listOfFiles[i].isFile() && filename.endsWith(".dat"))
				{
					try
					{
						BufferedReader rx = new BufferedReader(new FileReader(listOfFiles[i]));
						double x = Double.parseDouble(rx.readLine().trim());
						double y = Double.parseDouble(rx.readLine().trim());
						double z = Double.parseDouble(rx.readLine().trim());
						float yaw = Float.parseFloat(rx.readLine().trim());
						float pitch = Float.parseFloat(rx.readLine().trim());
						String worldName = rx.readLine();
						rx.close();
						World w = null;
						for (World world : ess.getServer().getWorlds())
						{
							if (world.getEnvironment() != World.Environment.NETHER)
							{
								w = world;
								break;
							}
						}
						boolean forceWorldName = false;
						if (worldName != null)
						{
							worldName.trim();
							World w1 = null;
							w1 = ess.getWorld(worldName);
							if (w1 != null)
							{
								w = w1;
							}
						}
						Location loc = new Location(w, x, y, z, yaw, pitch);
						Essentials.getWarps().setWarp(filename.substring(0, filename.length() - 4), loc);
						if (!listOfFiles[i].renameTo(new File(warpsFolder, filename + ".old")))
						{
							throw new Exception("Renaming file " + filename + " failed");
						}
					}
					catch (Exception ex)
					{
						logger.log(Level.SEVERE, null, ex);
					}
				}
			}

		}
		File warpFile = new File(ess.getDataFolder(), "warps.txt");
		if (warpFile.exists())
		{
			try
			{
				BufferedReader rx = new BufferedReader(new FileReader(warpFile));
				for (String[] parts = new String[0]; rx.ready(); parts = rx.readLine().split(":"))
				{
					if (parts.length < 6)
					{
						continue;
					}
					String name = parts[0];
					double x = Double.parseDouble(parts[1].trim());
					double y = Double.parseDouble(parts[2].trim());
					double z = Double.parseDouble(parts[3].trim());
					float yaw = Float.parseFloat(parts[4].trim());
					float pitch = Float.parseFloat(parts[5].trim());
					if (name.isEmpty())
					{
						continue;
					}
					World w = null;
					for (World world : ess.getServer().getWorlds())
					{
						if (world.getEnvironment() != World.Environment.NETHER)
						{
							w = world;
							break;
						}
					}
					Location loc = new Location(w, x, y, z, yaw, pitch);
					Essentials.getWarps().setWarp(name, loc);
					if (!warpFile.renameTo(new File(ess.getDataFolder(), "warps.txt.old")))
					{
						throw new Exception("Renaming warps.txt failed");
					}
				}
			}
			catch (Exception ex)
			{
				logger.log(Level.SEVERE, null, ex);
			}
		}
	}

	private void sanitizeAllUserFilenames()
	{
		File usersFolder = new File(ess.getDataFolder(), "userdata");
		if (!usersFolder.exists())
		{
			return;
		}
		File[] listOfFiles = usersFolder.listFiles();
		for (int i = 0; i < listOfFiles.length; i++)
		{
			String filename = listOfFiles[i].getName();
			if (!listOfFiles[i].isFile() || !filename.endsWith(".yml"))
			{
				continue;
			}
			String sanitizedFilename = Util.sanitizeFileName(filename.substring(0, filename.length() - 4)) + ".yml";
			if (sanitizedFilename.equals(filename))
			{
				continue;
			}
			File tmpFile = new File(listOfFiles[i].getParentFile(), sanitizedFilename + ".tmp");
			File newFile = new File(listOfFiles[i].getParentFile(), sanitizedFilename);
			if (!listOfFiles[i].renameTo(tmpFile)) {
				logger.log(Level.WARNING, "Failed to move userdata/"+filename+" to userdata/"+sanitizedFilename+".tmp");
				continue;
			}
			if (newFile.exists())
			{
				logger.log(Level.WARNING, "Duplicated userdata: "+filename+" and "+sanitizedFilename);
				continue;
			}
			if (!tmpFile.renameTo(newFile)) {
				logger.log(Level.WARNING, "Failed to move userdata/"+sanitizedFilename+".tmp to userdata/"+sanitizedFilename);
			}
		}
	}
}