Unofficial RPS Minecraft server automapper


/ Published in: Python
Save to your folder(s)

Downloads the latest backup of the Unofficial RPS Minecraft server and generates a map using Cartograph. You will need to modify MAP DIRECTORY and APP PATH to point to the relevant places on your machine.


Copy this code and paste it in your HTML
  1. from __future__ import division
  2. from __future__ import print_function
  3.  
  4. import os
  5. import subprocess
  6. import urllib2
  7. import time
  8. import re
  9. import tarfile
  10. from PIL import Image
  11.  
  12.  
  13. # Note: don't put trailing slashes on any filepaths or URLs
  14.  
  15. # Where all the files and maps are saved
  16. MAP_DIRECTORY = "C:/Cartograph"
  17.  
  18. # The filepath to Cartograph
  19. APP_PATH = "F:/Programs/Minecraft/Alpha/Cartograph"
  20. APP_NAME = "Cartograph.exe"
  21.  
  22. # The arguments to pass to Cartograph. Check the Cartograph help for more info
  23. APP_ARGUMENTS_1 = "normal 0 0 0 0"
  24. APP_ARGUMENTS_2 = "obliqueangle 0 0 0 0 0"
  25.  
  26. # The map name(s)
  27. MAP_NAME_1 = "top_down"
  28. MAP_NAME_2 = "oblique_angled"
  29.  
  30. # Delete the archive after extracting?
  31. DELETE_ARCHIVE = True
  32.  
  33. # Where the backups are downloaded from. Leave this as it is
  34. BASEURL = "http://rps.fragwith.us/backups"
  35.  
  36.  
  37. _CHUNK_SIZE = 1024 * 8
  38. _MB = 1024 * 1024
  39.  
  40. def main():
  41. curTime = time.time()
  42.  
  43. print("Finding most recent backup...")
  44.  
  45. for i in range(-1, 5):
  46. date = _subtractDays(curTime, i)
  47. try:
  48. html = urllib2.urlopen(BASEURL + '/' + date + '/')
  49. except urllib2.HTTPError:
  50. continue
  51.  
  52. archivename = re.findall('<a href="world\..*\.tar\.gz">',
  53. html.read())[-1].split('"')[1]
  54. print("Most recent backup is {0}.".format(archivename))
  55. datetimestring = archivename.split('.')[1]
  56. datetime = time.strptime(datetimestring, '%d-%m-%Y_%H%M%S')
  57. filepath = "{0}/{1}/".format(MAP_DIRECTORY,
  58. time.strftime('%Y-%m-%d_%H-%M-%S', datetime))
  59. if not os.path.exists(filepath):
  60. os.mkdir(filepath)
  61.  
  62. print("Downloading {0} to {1}".format(archivename, filepath))
  63. startTime = time.time()
  64. download(BASEURL + '/' + date + '/' + archivename, filepath +
  65. archivename)
  66. print("Downloaded in {0}.".format(_timeTaken(startTime, time.time())))
  67.  
  68. print("Extracting contents from archive...")
  69. startTime = time.time()
  70. extract(filepath, archivename)
  71. print("Extracted in {0}.".format(_timeTaken(startTime, time.time())))
  72.  
  73. if DELETE_ARCHIVE:
  74. print("Deleting archive...")
  75. os.remove(filepath + archivename)
  76. print("Archive deleted.")
  77.  
  78. map(filepath)
  79.  
  80. break
  81.  
  82. def download(url, filepath):
  83. bytesSoFar = 0
  84. percent = -1
  85. partfile = filepath + '.part'
  86. opener = urllib2.build_opener()
  87. response = opener.open(url)
  88.  
  89. totalSize = response.info().getheader("Content-Length")
  90. if totalSize is not None:
  91. totalSize = int(totalSize.strip())
  92.  
  93. if not os.path.exists(filepath):
  94. fp = open(partfile, 'wb')
  95.  
  96. chunk = True
  97. while chunk:
  98. chunk = response.read(_CHUNK_SIZE)
  99. bytesSoFar += len(chunk)
  100. fp.write(chunk)
  101. percent = _percentageDone(bytesSoFar, totalSize, percent)
  102.  
  103. print("")
  104. fp.close()
  105. response.close()
  106. os.rename(partfile, filepath)
  107. else:
  108. print("{0} already exists".format(filepath))
  109.  
  110. def extract(filepath, filename):
  111. tar = tarfile.open(filepath + filename, 'r')
  112. tar.extractall(filepath)
  113.  
  114. def map(path):
  115. os.chdir(APP_PATH)
  116.  
  117. inputPath = path + "world"
  118. print("Generating map 1...")
  119. outputPath = path + MAP_NAME_1 + ".png"
  120. startTime = time.time()
  121. app = subprocess.Popen('{0} 6 {1} "{2}" "{3}"'.format(APP_NAME,
  122. APP_ARGUMENTS_1, outputPath, inputPath))
  123. app.wait()
  124. print("Map generated in {0}.".format(_timeTaken(startTime, time.time())))
  125. print("Map 1 generated.")
  126. # Rotate the image so that north is actually north. Obviously this won't
  127. # work on oblique maps.
  128. print("Rotating...")
  129. _rotateImage(outputPath)
  130. print("Map 1 finished.")
  131.  
  132. # Map 2 generation commented out because oblique mode crashes on my system
  133. # for very large maps. YMMV.
  134.  
  135. # print("Generating map 2...")
  136. # outputPath = path + '/' + MAP_NAME_2 + ".png"
  137. # app = subprocess.Popen('{0} 6 {1} "{2}" "{3}"'.format(APP_NAME,
  138. # APP_ARGUMENTS_2, outputPath, inputPath))
  139. # app.wait()
  140. # print("Map 2 generated.")
  141. # print("Map 2 finished.")
  142.  
  143. def _rotateImage(file):
  144. im = Image.open(file)
  145. im = im.rotate(-90)
  146. im.save(file)
  147.  
  148. def _percentageDone(bytesSoFar, totalSize, curPercent):
  149. if totalSize == 0 or totalSize is None:
  150. return -1
  151. percent = (bytesSoFar / totalSize) * 100
  152. if int(percent) > int(curPercent):
  153. print("\n {0:3}% downloaded ({1:6.2f}MB of {2:6.2f}MB)".format(
  154. int(percent), bytesSoFar/_MB, totalSize/_MB), end='')
  155. if int(percent * 10) > int(curPercent * 10) and int(percent) < 100:
  156. print('.', end='')
  157. return percent
  158.  
  159. def _subtractDays(t, n):
  160. t -= (n * 86400)
  161. date = time.strftime("%d-%m-%Y", time.localtime(t))
  162. return date
  163.  
  164. def _timeTaken(start, finish):
  165. timeTaken = int(finish - start)
  166.  
  167. numHours = timeTaken // 3600
  168. timeTaken %= 3600
  169.  
  170. numMins = timeTaken // 60
  171. timeTaken %= 60
  172.  
  173. numSecs = timeTaken
  174.  
  175. ret = ""
  176.  
  177. if numHours == 1:
  178. ret += "{0} hour, ".format(numHours)
  179. elif numHours > 1:
  180. ret += "{0} hours, ".format(numHours)
  181.  
  182. if numMins == 1:
  183. ret += "{0} minute and ".format(numMins)
  184. elif numMins > 1 or numHours > 0:
  185. ret += "{0} minutes and ".format(numMins)
  186.  
  187. if numSecs == 1:
  188. ret += "{0} second".format(numSecs)
  189. else:
  190. ret += "{0} seconds".format(numSecs)
  191.  
  192. return ret
  193.  
  194. if __name__ == "__main__":
  195. main()

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.