All pastes #951079 Raw Edit

Something

public text v1 · immutable
·published 2008-03-21 00:40 UTC
rendered paste body
import es, urllib, threading, os, usermsg, playerlib, popuplib, bz2

urls = ["http://localhost/maps/"]
addmap_fastdownload = 0

def load():
    if not es.exists("command", "AddMap"):
        es.regcmd("AddMap", "AddMap/AddMap")

def AddMap():
    if es.getargc() >= 2 and es.getargc() <= 4:
        map = es.getargv(1)
        if es.getargc() == 3:
            add = es.getargv(2)
        else:
            add = 0
        if es.getargc() == 4:
            overwrite = es.getargv(3)
        else:
            overwrite = 0
        AddMap2(map, add, overwrite).start()
    else:
        es.dbgmsg(0, "Syntax: AddMap <map> [add to maplists] [overwrite existing]")

class progressBar:
    def __init__(self, minValue = 0, maxValue = 10, totalWidth=12):
        self.progBar = "[]"
        self.min = minValue
        self.max = maxValue
        self.span = maxValue - minValue
        self.width = totalWidth
        self.amount = 0
        self.updateAmount(0)

    def updateAmount(self, newAmount = 0):
        if newAmount < self.min: newAmount = self.min
        if newAmount > self.max: newAmount = self.max
        self.amount = newAmount
        diffFromMin = float(self.amount - self.min)
        percentDone = (diffFromMin / float(self.span)) * 100.0
        percentDone = round(percentDone)
        percentDone = int(percentDone)
        allFull = self.width - 2
        numHashes = (percentDone / 100.0) * allFull
        numHashes = int(round(numHashes))
        self.progBar = "[" + '|'*numHashes + ' '*(allFull-numHashes) + "]"
        percentPlace = (len(self.progBar) / 2) - len(str(percentDone))
        percentString = str(percentDone) + "%"
        self.progBar = self.progBar[0:percentPlace] + self.progBar[percentPlace+len(percentString):] + " " + percentString

    def __str__(self):
        return str(self.progBar)
        
def MapReportHook(count, blockSize, totalSize):
    prog = progressBar(0, totalSize, 50)
    prog.updateAmount(count * blockSize)
    hudhint("Downloading: " + str(prog))

class AddMap2(threading.Thread):
    def __init__(self, map, add, overwrite, url=None):
        self.map, self.add, self.overwrite, self.url = map, add, overwrite, url
        threading.Thread.__init__(self)

    def run(self):
        try:
            if self.url:
                mapurl = self.url
            else:
                hudhint("[AddMap] Retrieving maps from file database.")
                maps = getMapsFromFile()
                hudhint("[AddMap] Maps retrieved from file database.")
                mapurl = None
                if self.map in maps:
                    mapurl = maps[self.map]
                else:
                    hudhint("[AddMap] Retrieving maps from url database.")
                    maps = self.getMapsFromUrl()
                    hudhint("[AddMap] Maps retrieved from url database.")
                    for url in maps:
                        for checkmap in maps[url]:
                            if checkmap.split(".")[0] == self.map.split(".")[0]:
                                mapurl = "%s%s" % (url, checkmap)
                                break
                if not mapurl == None:
                    hudhint("[AddMap] Map %s located at: %s" % (self.map, mapurl))
                    self.downloadMap(mapurl)
        except:
            hudhint("[AddMap] An unknown error occured.")

    def getMapsFromUrl(self):
        try:
            maps = {}
            for url in urls:
                maps[url] = []
                html = urllib.urlopen(url).read()
                for line in html.split("\n"):
                    if ".bsp" in line:
                        if len(line.split('"')) >= 5:
                            map = line.split('"')[5]
                            maps[url].append(map)
                            self.WriteMap(map, "%s%s" % (url, map))
                return maps
        except Exception, e:
            hudhint("[AddMap] Could not download map: %s" % self.map)

    def WriteMap(self, map, url):
        try:
            path = "%s/maps.txt" % es.getAddonPath("AddMap")
            if os.path.exists(path):
                if not map in getMapsFromFile():
                    maps = open(path, "a")
                    maps.write("%s,%s\n" % (map, url))
                    maps.close()
       except:
           pass

    def downloadMap(self, mapurl):
        try:
            mapext = mapurl.split(self.map)[1]
            es.msg(mapext)
            filename = "%s\maps\%s%s" % (str(es.ServerVar("eventscripts_gamedir")), self.map, mapext)
            es.msg(filename)
            if not os.path.exists(filename) or int(self.overwrite) == 1:
                hudhint("[AddMap] Downloading map: %s" % self.map)
                bsp = urllib.urlretrieve(mapurl, filename, reporthook=MapReportHook)
                hudhint("[AddMap] %s added to server!" % self.map)
                if addmap_fastdownload == 1:
                    if filename.endswith(".bsp"):
                        BZ2_Compress(filename)
                else:
                    if filename.endswith(".bz2"):
                        BZ2_Decompress(filename)
            else:
                hudhint("[AddMap] Map already exists on server: %s" % self.map)
        except:
            hudhint("[AddMap] An error occured whilst downloading map: %s" % self.map)

    def BZ2_Compress(self, bz2file):
        try:
            output = bz2file + ".bz2"
            if os.path.exists(bz2file):
                normfile = open(bz2file, "r").read()
                file = bz2.BZ2File(output, "w")
                file.write(normfile)
                file.close()
                hudhint("[AddMap] %s bzipped sucessfully!" % self.map)
        except:
            hudhint("[AddMap] %s could not be bzipped." % self.map)

    def BZ2_Decompress(self, normfile):
        try:
            output = normfile.replace(".bz2", "")
            if os.path.exists(normfile):
                bz2file = bz2.BZ2File(normfile, "r").read()
                file = open(output, "w")
                file.write(bz2file)
                file.close()
                hudhint("[AddMap] %s unbzipped sucessfully!" % self.map)
        except:
            hudhint("[AddMap] %s could not be unbzipped." % self.map)

def getMapsFromFile():
    maplist = {}
    path = "%s/maps.txt" % es.getAddonPath("AddMap")
    if os.path.exists(path):
        maps = open(path, "r").read()
        for map in maps.split("\n"):
            if not map.strip() == "" and not map.startswith("//"):
                map = map.split(",")
                maplist[map[0]] = map[1]
    return maplist

def player_say(event_var):
    if event_var["text"] == "!maps":
        maps = getMapsFromFile()
        p_maps = popuplib.easymenu("maps", "_popup_choice", mapinfo)
        p_maps.settitle("-AddMap-\nAvailable Maps")
        for map in maps:
            p_maps.addoption("%s,%s" % (map, maps[map]), map)
        p_maps.send(event_var["userid"])

def mapinfo(userid, choice, popup):
    choice = choice.split(",")
    map = choice[0]
    url = choice[1]
    AddMap2(map, 0, 0, url).start()

def hudhint(text):
    for userid in playerlib.getUseridList("#all"):
        usermsg.hudhint(userid, text)
    es.dbgmsg(0, text)