Mercurial > traipse_dev
changeset 119:9314d63c0941 alpha
Traipse Alpha 'OpenRPG' {091029-00}
Traipse is a distribution of OpenRPG that is designed to be easy to setup and go.
Traipse also makes it easy for developers to work on code without fear of
sacrifice. 'Ornery-Orc' continues the trend of 'Grumpy' and adds fixes to the
code. 'Ornery-Orc's main goal is to offer more advanced features and enhance the
productivity of the user.
Update Summary:
Adds Bookmarks (Alpha) with cool Smiley Star and Plus Symbol images!
Changes made to the map for increased portability. SnowDog has changes planned in
Core, though.
Added an initial push to the BCG. Not much to see, just shows off how it is
re-writing Main code.
Fix to remote admin commands
Minor fix to texted based server, works in /System/ folder
Some Core changes to gametree to correctly disply Pretty Print, thanks David!
Fix to Splitter Nodes not being created.
Added images to Plugin Control panel for Autostart feature
Fix to massive amounts of images loading; from Core
fix to gsclient so with_statement imports
Added 'boot' command to remote admin
Prep work in Pass tool for remote admin rankings and different passwords, ei,
Server, Admin, Moderator, etc.
Remote Admin Commands more organized, more prep work.
Added Confirmation window for sent nodes.
Minor changes to allow for portability to an OpenSUSE linux OS (hopefully without
breaking)
{091028}
00:
Made changes to gametree to start working with Element Tree, mostly from Core
Minor changes to Map to start working with Element Tree, from Core
Preliminary changes to map efficiency, from FlexiRPG
Miniatures Layer pop up box allows users to turn off Mini labels, from FlexiRPG
Changes to main.py to start working with Element Tree
{091029}
00:
Changes made to server to start working with Element Tree.
Changes made to Meta Server Lib. Prepping test work for a multi meta network
page.
Minor bug fixed with mini to gametree
Zoom Mouse plugin added.
Known Issue: Disconnecting causes an server side error. XML data is not being
passed correctly.
line wrap: on
line diff
--- a/orpg/chat/commands.py Wed Oct 28 14:24:54 2009 -0500 +++ b/orpg/chat/commands.py Thu Oct 29 20:35:28 2009 -0500 @@ -315,12 +315,9 @@ def postLoggingState( self ): logfile = self.settings.get_setting( 'GameLogPrefix' ) try: - if logfile[0] != ANTI_LOG_CHAR: - comment = 'is' - else: - comment = 'is not' - except: - comment = 'is not' + if logfile[0] != ANTI_LOG_CHAR: comment = 'is' + else: comment = 'is not' + except: comment = 'is not' suffix = time.strftime( '-%d-%m-%y.html', time.localtime( time.time() ) ) self.chat.InfoPost('Log filename is "%s%s", system is %s logging.' % (logfile, suffix, comment) ) @@ -339,7 +336,6 @@ self.session.set_name(str(cmdargs)) # def on_status - end - # This subroutine will set the players netork status. # # !self : instance of self @@ -404,7 +400,6 @@ if self.shortcmdlist[shortcmd] == cmd: msg += ', <b><font color="#0000CC">%s</font></b>' % (shortcmd) msg += ' %s' % (self.cmdlist[cmd]['help']) - self.chat.InfoPost(msg) # This subroutine will either show the list of currently ignored users @@ -459,8 +454,7 @@ if role_pwd != None: for m in player_ids: self.session.set_role(m.strip(),role,role_pwd) - except: - traceback.print_exc() + except: traceback.print_exc() # return # This subroutine implements the whisper functionality that enables a user @@ -475,13 +469,11 @@ delim = cmdargs.find("=") if delim < 0: - if self.previous_whisper: - player_ids = self.previous_whisper + if self.previous_whisper: player_ids = self.previous_whisper else: self.chat.InfoPost("**Incorrect syntax for whisper." + str(delim)) return - else: - player_ids = string.split(cmdargs[:delim], ",") + else: player_ids = string.split(cmdargs[:delim], ",") self.previous_whisper = player_ids mesg = string.strip(cmdargs[delim+1:]) self.chat.whisper_to_players(mesg,player_ids) @@ -494,8 +486,7 @@ args = string.split(cmdargs,None,-1) delim = cmdargs.find("=") - if delim > 0: - group_ids = string.split(cmdargs[:delim], ",") + if delim > 0: group_ids = string.split(cmdargs[:delim], ",") elif args[0] == "add": if not orpg.player_list.WG_LIST.has_key(args[2]): orpg.player_list.WG_LIST[args[2]] = {} @@ -540,10 +531,8 @@ for gid in group_ids: idList = "" for n in orpg.player_list.WG_LIST[gid]: - if idList == "": - idList = str(n) - else: - idList = str(n) + ", " + idList + if idList == "": idList = str(n) + else: idList = str(n) + ", " + idList self.on_whisper(idList + "=" + self.settings.get_setting("gwtext") + msg) #--------------------------------------------------------- @@ -559,12 +548,10 @@ if len(the_gms): gmstring = "" for each_gm in the_gms: - if gmstring != "": - gmstring += "," + if gmstring != "": gmstring += "," gmstring += each_gm self.on_whisper(gmstring + "=" + cmdargs) - else: - self.chat.InfoPost("**No GMs to Whisper to.") + else: self.chat.InfoPost("**No GMs to Whisper to.") @debugging def on_moderate(self, cmdargs): @@ -572,20 +559,16 @@ pos = cmdargs.find("=") if (pos < 0): plist = "" - if cmdargs.lower() == "on": - action = "enable" - elif cmdargs.lower() == "off": - action="disable" + if cmdargs.lower() == "on": action = "enable" + elif cmdargs.lower() == "off": action="disable" else: self.chat.InfoPost("Wrong syntax for moderate command!") return else: plist = string.strip(cmdargs[:pos]) tag = string.strip(cmdargs[pos+1:]) - if tag.lower() == "on": - action = "addvoice" - elif tag.lower() == "off": - action = "delvoice" + if tag.lower() == "on": action = "addvoice" + elif tag.lower() == "off": action = "delvoice" else: self.chat.InfoPost("Wrong syntax for moderate command!") return @@ -594,8 +577,7 @@ msg = "<moderate" msg += " action = '" + action + "'" msg +=" from = '" + self.session.id + "' pwd='" + pwd + "'" - if (plist != ""): - msg += " users='"+plist+"'" + if (plist != ""): msg += " users='"+plist+"'" msg += " />" self.session.outbox.put(msg) pass @@ -630,8 +612,7 @@ if (panel.sendtarget == playerid): self.chat.Post("Cannot invoke tab: Tab already exists.") return - try: - displaypanel = self.chat.parent.create_whisper_tab(playerid) + try: displaypanel = self.chat.parent.create_whisper_tab(playerid) except: self.chat.Post("That ID# is not valid.") return @@ -661,8 +642,7 @@ #raw command return state info msg = "<br /><b>Remote Administrator Config:</b>" if pass_state != 1 : msg += " Password not set. Remote admin functions disabled<br />" - else: - msg += " Enabled. Using password '"+pwd+"'<br />" + else: msg += " Enabled. Using password '"+pwd+"'<br />" self.chat.SystemPost(msg) return
--- a/orpg/gametree/gametree.py Wed Oct 28 14:24:54 2009 -0500 +++ b/orpg/gametree/gametree.py Thu Oct 29 20:35:28 2009 -0500 @@ -177,7 +177,7 @@ @debugging def on_char(self, evt): key_code = evt.GetKeyCode() - curSelection = self.GetSelection() # Get the current selection + curSelection = self.GetSelection() # Get the current selection if evt.ShiftDown() and ((key_code == wx.WXK_UP) or (key_code == wx.WXK_DOWN)) and not self.dragging: curSelection = self.GetSelection() obj = self.GetPyData(curSelection) @@ -238,14 +238,6 @@ f.close() self.xml_root = None ### Alpha ### Doing some work on Gametree to add Element Tree, slowly at first. - - try: - logger.info("Reading Gametree file: " + filename + "...", True) - xml_doc = xml.parseXml(tostring(self.xml_root)) - if xml_doc == None: pass - else: xml_dom = xml_doc._get_documentElement() - logger.info("done.", True) - except: pass if not self.xml_root: os.rename(filename,filename+".corrupt")
--- a/orpg/main.py Wed Oct 28 14:24:54 2009 -0500 +++ b/orpg/main.py Thu Oct 29 20:35:28 2009 -0500 @@ -96,7 +96,7 @@ "on_password_signal":self.on_password_signal, "orpgFrame":self} self.settings = component.get('settings') #Arbitrary until settings updated with Core. - self.session = orpg.networking.mplay_client.mplay_client(self.settings.get_setting("player"), call_backs) + self.session = orpg.networking.mplay_client.mplay_client(self.settings.get("player"), call_backs) self.poll_timer = wx.Timer(self, wx.NewId()) self.Bind(wx.EVT_TIMER, self.session.poll, self.poll_timer) self.poll_timer.Start(100) @@ -104,7 +104,7 @@ self.Bind(wx.EVT_TIMER, self.session.update, self.ping_timer) # create roller manager - self.DiceManager = DiceManager(settings.get_setting("dieroller")) + self.DiceManager = DiceManager(settings.get("dieroller")) component.add('DiceManager', self.DiceManager) #create password manager --SD 8/03 @@ -123,7 +123,7 @@ component.add("alias", self.aliaslib) logger.debug("openrpg components all added") - self.tree.load_tree(settings.get_setting("gametree")) + self.tree.load_tree(settings.get("gametree")) logger.debug("Tree Loaded") self.players.size_cols() @@ -235,10 +235,10 @@ ]] self.mainmenu = MenuBarEx(self, menu) - if settings.get_setting('Heartbeat') == '1': + if settings.get('Heartbeat') == '1': self.mainmenu.SetMenuState("GameServerServerHeartbeat", True) - tabtheme = settings.get_setting('TabTheme') #This change is stable. TaS. + tabtheme = settings.get('TabTheme') #This change is stable. TaS. self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedColorful", tabtheme == 'slanted&colorful') self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedBlackandWhite", tabtheme == 'slanted&bw') self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedAqua", tabtheme == 'slanted&aqua') @@ -247,7 +247,7 @@ self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedCustom", tabtheme == 'customslant') self.mainmenu.SetMenuState("OpenRPGTabStylesFlatCustom", tabtheme == 'customflat') - lvl = int(settings.get_setting('LoggingLevel')) + lvl = int(settings.get('LoggingLevel')) if lvl & ORPG_DEBUG: self.mainmenu.SetMenuState("ToolsLoggingLevelDebug", True) if lvl & ORPG_DEBUG: self.mainmenu.SetMenuState("ToolsLoggingLevelNote", True) if lvl & ORPG_INFO: self.mainmenu.SetMenuState("ToolsLoggingLevelInfo", True) @@ -303,7 +303,7 @@ @debugging def SetTabStyles(self, *args, **kwargs): - tabtheme = settings.get_setting('TabTheme') #This change is stable. TaS. + tabtheme = settings.get('TabTheme') #This change is stable. TaS. self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedColorful", tabtheme == 'slanted&colorful') self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedBlackandWhite", tabtheme == 'slanted&bw') self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedAqua", tabtheme == 'slanted&aqua') @@ -338,7 +338,7 @@ component.add("tabbedWindows", tabbedwindows) #Run though the new list and set the proper styles - tabbg = settings.get_setting('TabBackgroundGradient') + tabbg = settings.get('TabBackgroundGradient') (red, green, blue) = self.rgb.rgb_tuple(tabbg) for wnd in tabbedwindows: @@ -361,14 +361,14 @@ @debugging def OnMB_OpenRPGTabStylesSlantedColorful(self): if self.mainmenu.GetMenuState("OpenRPGTabStylesSlantedColorful"): - settings.set_setting('TabTheme', 'slanted&colorful') + settings.change('TabTheme', 'slanted&colorful') self.SetTabStyles("OpenRPGTabStylesSlantedColorful", FNB.FNB_VC8|FNB.FNB_COLORFUL_TABS) else: self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedColorful", True) @debugging def OnMB_OpenRPGTabStylesSlantedBlackandWhite(self): if self.mainmenu.GetMenuState("OpenRPGTabStylesSlantedBlackandWhite"): - settings.set_setting('TabTheme', 'slanted&bw') + settings.change('TabTheme', 'slanted&bw') self.SetTabStyles("OpenRPGTabStylesSlantedBlackandWhite", FNB.FNB_VC8, graidentTo=wx.WHITE, graidentFrom=wx.WHITE, textColor=wx.BLACK) else: self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedBlackandWhite", True) @@ -376,7 +376,7 @@ @debugging def OnMB_OpenRPGTabStylesSlantedAqua(self): if self.mainmenu.GetMenuState("OpenRPGTabStylesSlantedAqua"): - settings.set_setting('TabTheme', 'slanted&aqua') + settings.change('TabTheme', 'slanted&aqua') self.SetTabStyles("OpenRPGTabStylesSlantedAqua", FNB.FNB_VC8, graidentTo=wx.Color(0, 128, 255), graidentFrom=wx.WHITE, textColor=wx.BLACK) else: self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedAqua", True) @@ -384,14 +384,14 @@ @debugging def OnMB_OpenRPGTabStylesSlantedCustom(self): if self.mainmenu.GetMenuState("OpenRPGTabStylesSlantedCustom"): - settings.set_setting('TabTheme', 'customslant') - gfrom = settings.get_setting('TabGradientFrom') + settings.change('TabTheme', 'customslant') + gfrom = settings.get('TabGradientFrom') (fred, fgreen, fblue) = self.rgb.rgb_tuple(gfrom) - gto = settings.get_setting('TabGradientTo') + gto = settings.get('TabGradientTo') (tored, togreen, toblue) = self.rgb.rgb_tuple(gto) - tabtext = settings.get_setting('TabTextColor') + tabtext = settings.get('TabTextColor') (tred, tgreen, tblue) = self.rgb.rgb_tuple(tabtext) - tabbg = settings.get_setting('TabBackgroundGradient') + tabbg = settings.get('TabBackgroundGradient') (red, green, blue) = self.rgb.rgb_tuple(tabbg) self.SetTabStyles("OpenRPGTabStylesSlantedCustom", FNB.FNB_VC8, graidentTo=wx.Color(tored, togreen, toblue), graidentFrom=wx.Color(fred, fgreen, fblue), @@ -401,7 +401,7 @@ @debugging def OnMB_OpenRPGTabStylesFlatBlackandWhite(self): if self.mainmenu.GetMenuState("OpenRPGTabStylesFlatBlackandWhite"): - settings.set_setting('TabTheme', 'flat&bw') + settings.change('TabTheme', 'flat&bw') self.SetTabStyles("OpenRPGTabStylesFlatBlackandWhite", FNB.FNB_FANCY_TABS, graidentTo=wx.WHITE, graidentFrom=wx.WHITE, textColor=wx.BLACK) else: self.mainmenu.SetMenuState("OpenRPGTabStylesFlatBlackandWhite", True) @@ -409,7 +409,7 @@ @debugging def OnMB_OpenRPGTabStylesFlatAqua(self): if self.mainmenu.GetMenuState("OpenRPGTabStylesFlatAqua"): - settings.set_setting('TabTheme', 'flat&aqua') + settings.change('TabTheme', 'flat&aqua') self.SetTabStyles("OpenRPGTabStylesFlatAqua", FNB.FNB_FANCY_TABS, graidentTo=wx.Color(0, 128, 255), graidentFrom=wx.WHITE, textColor=wx.BLACK) else: self.mainmenu.SetMenuState("OpenRPGTabStylesFlatAqua", True) @@ -417,14 +417,14 @@ @debugging def OnMB_OpenRPGTabStylesFlatCustom(self): if self.mainmenu.GetMenuState("OpenRPGTabStylesFlatCustom"): - settings.set_setting('TabTheme', 'customflat') - gfrom = settings.get_setting('TabGradientFrom') + settings.change('TabTheme', 'customflat') + gfrom = settings.get('TabGradientFrom') (fred, fgreen, fblue) = self.rgb.rgb_tuple(gfrom) - gto = settings.get_setting('TabGradientTo') + gto = settings.get('TabGradientTo') (tored, togreen, toblue) = self.rgb.rgb_tuple(gto) - tabtext = settings.get_setting('TabTextColor') + tabtext = settings.get('TabTextColor') (tred, tgreen, tblue) = self.rgb.rgb_tuple(tabtext) - tabbg = settings.get_setting('TabBackgroundGradient') + tabbg = settings.get('TabBackgroundGradient') (red, green, blue) = self.rgb.rgb_tuple(tabbg) self.SetTabStyles("OpenRPGTabStylesFlatCustom", FNB.FNB_FANCY_TABS, graidentTo=wx.Color(tored, togreen, toblue), graidentFrom=wx.Color(fred, fgreen, fblue), @@ -463,8 +463,8 @@ @debugging def OnMB_GameServerServerHeartbeat(self): - if self.mainmenu.GetMenuState("GameServerServerHeartbeat"): settings.set_setting('Heartbeat', '1') - else: settings.set_setting('Heartbeat', '0') + if self.mainmenu.GetMenuState("GameServerServerHeartbeat"): settings.change('Heartbeat', '1') + else: settings.change('Heartbeat', '0') @debugging def OnMB_GameServerStartServer(self): @@ -807,9 +807,9 @@ elif name == "tree": temp_wnd = orpg.gametree.gametree.game_tree(parent_wnd, -1) self.tree = temp_wnd - if settings.get_setting('ColorTree') == '1': - self.tree.SetBackgroundColour(settings.get_setting('bgcolor')) - self.tree.SetForegroundColour(settings.get_setting('textcolor')) + if settings.get('ColorTree') == '1': + self.tree.SetBackgroundColour(settings.get('bgcolor')) + self.tree.SetForegroundColour(settings.get('textcolor')) else: self.tree.SetBackgroundColour('white') self.tree.SetForegroundColour('black') @@ -822,9 +822,9 @@ elif name == "player": temp_wnd = orpg.player_list.player_list(parent_wnd) self.players = temp_wnd - if settings.get_setting('ColorTree') == '1': - self.players.SetBackgroundColour(settings.get_setting('bgcolor')) - self.players.SetForegroundColour(settings.get_setting('textcolor')) + if settings.get('ColorTree') == '1': + self.players.SetBackgroundColour(settings.get('bgcolor')) + self.players.SetForegroundColour(settings.get('textcolor')) else: self.players.SetBackgroundColour('white') self.players.SetForegroundColour('black') @@ -914,7 +914,7 @@ def start_timer(self): self.poll_timer.Start(100) s = component.get('settings') - if s.get_setting("Heartbeat") == "1": + if s.get("Heartbeat") == "1": self.ping_timer.Start(1000*60) logger.debug("starting heartbeat...", True) @@ -1032,18 +1032,19 @@ ####Begin changes for Custom Exit Message by mDuo13###### elif id == orpg.networking.mplay_client.MPLAY_DISCONNECTING: settings = component.get('settings') - custom_msg = settings.get_setting("dcmsg") + custom_msg = settings.get("dcmsg") custom_msg=custom_msg[:80] if custom_msg[:3]=="/me": self.chat.send_chat_message(custom_msg[3:], 3) else: self.chat.system_message(custom_msg) #####End Changes for Custom Exit Message by mDuo13 - elif id== orpg.networking.mplay_client.MPLAY_GROUP_CHANGE: + elif id == orpg.networking.mplay_client.MPLAY_GROUP_CHANGE: group = evt.get_data() + print 'main ', group self.chat.InfoPost("Moving to room '"+group[1]+"'..") if self.gs : self.gs.set_cur_room_text(group[1]) self.players.reset() - elif id== orpg.networking.mplay_client.MPLAY_GROUP_CHANGE_F: + elif id == orpg.networking.mplay_client.MPLAY_GROUP_CHANGE_F: self.chat.SystemPost("Room access denied!") @debugging @@ -1076,9 +1077,9 @@ logger.general("[WARNING] Map error pre_exit_cleanup()", True) try: - save_tree = string.upper(settings.get_setting("SaveGameTreeOnExit")) + save_tree = string.upper(settings.get("SaveGameTreeOnExit")) if (save_tree != "0") and (save_tree != "False") and (save_tree != "NO"): - self.tree.save_tree(settings.get_setting("gametree")) + self.tree.save_tree(settings.get("gametree")) except Exception: logger.general("[WARNING] Error saving gametree", True) @@ -1200,7 +1201,7 @@ component.add('validate', validate) component.add("tabbedWindows", []) - logger._set_log_level = int(settings.get_setting('LoggingLevel')) + logger._set_log_level = int(settings.get('LoggingLevel')) logger._set_log_to_console(False) #Update Manager
--- a/orpg/mapper/miniatures.py Wed Oct 28 14:24:54 2009 -0500 +++ b/orpg/mapper/miniatures.py Thu Oct 29 20:35:28 2009 -0500 @@ -492,12 +492,6 @@ s = Element('miniatures') s.set('serial', str(self.serial_number)) s.append(mini_string) - #s = "<miniatures" - #s += " serial='" + str(self.serial_number) + "'" - #s += ">" - #s += mini_string - #s += "</miniatures>" - #return s return tostring(s) else: return ""
--- a/orpg/mapper/miniatures_handler.py Wed Oct 28 14:24:54 2009 -0500 +++ b/orpg/mapper/miniatures_handler.py Thu Oct 29 20:35:28 2009 -0500 @@ -358,9 +358,8 @@ elif id == MIN_REMOVE: self.canvas.layers['miniatures'].del_miniature(self.sel_rmin) elif id == MIN_TO_GAMETREE: ### Alpha ### implements ElementTree - min_xml = self.sel_rmin.toxml(action="new") + mini = self.sel_rmin.toxml(action="new") node = Element('nodehandler') - mini = fromstring(min_xml) node.set('module', 'map_miniature_nodehandler') node.set('class', 'map_miniature_handler') name = self.sel_rmin.label if self.sel_rmin.label else 'Unnamed Miniature' @@ -498,6 +497,7 @@ def on_miniature(self, evt): session = self.canvas.frame.session if (session.my_role() != session.ROLE_GM) and (session.my_role() != session.ROLE_PLAYER) and (session.use_roles()): + print session.my_role() self.infoPost("You must be either a player or GM to use the miniature Layer") return min_url = self.min_url.GetValue() @@ -771,14 +771,16 @@ def role_is_gm_or_player(self): session = self.canvas.frame.session - if (session.my_role() <> session.ROLE_GM) and (session.my_role() <> session.ROLE_PLAYER) and (session.use_roles()): + print session.my_role(), session.ROLE_GM + if (session.my_role() != session.ROLE_GM) and (session.my_role() != session.ROLE_PLAYER) and (session.use_roles()): + print 'role is gm or player' self.infoPost("You must be either a player or GM to use the miniature Layer") return False return True def role_is_gm(self): session = self.canvas.frame.session - if (session.my_role() <> session.ROLE_GM) and (session.use_roles()): return False + if (session.my_role() != session.ROLE_GM) and (session.use_roles()): return False return True def alreadyDealingWithMenu(self):
--- a/orpg/networking/gsclient.py Wed Oct 28 14:24:54 2009 -0500 +++ b/orpg/networking/gsclient.py Thu Oct 29 20:35:28 2009 -0500 @@ -38,6 +38,7 @@ from orpg.orpgCore import component import traceback from orpg.tools.validate import validate + from xml.etree.ElementTree import ElementTree, Element from xml.etree.ElementTree import fromstring, tostring @@ -67,24 +68,17 @@ if x.name.startswith(DEV_SERVER): if y.name.startswith(DEV_SERVER): - if not who_name: - return who_user - else: - return who_name - else: - return -1 + if not who_name: return who_user + else: return who_name + else: return -1 elif y.name.startswith(DEV_SERVER): return 1 - elif not who_user: - return who_name - else: - return who_user + elif not who_user: return who_name + else: return who_user def roomCmp(room1, room2): - if int(room1) > int(room2): - return 1 - elif int(room1) < int(room2): - return -1 + if int(room1) > int(room2): return 1 + elif int(room1) < int(room2): return -1 return 0 class game_server_panel(wx.Panel): @@ -292,7 +286,6 @@ open_rpg.get_component('frame').Bind(wx.EVT_MENU, self.on_bookmarks_menu, item) self.bookmarks_menu.AppendItem(item) - self.save_bookmarks() def save_bookmarks(self): @@ -301,10 +294,8 @@ def on_server_dbclick(self, evt=None): #make sure address is updated just in case list select wasn't done - try: - self.on_select(evt) - except: - pass + try: self.on_select(evt) + except: pass address = self.texts["address"].GetValue() if self.session.is_connected(): if self.session.host_server == address : @@ -317,10 +308,8 @@ def on_room_dbclick(self, evt=None): #make sure address is updated just in case list select wasn't done - try: - self.on_select(evt) - except: - pass + try: self.on_select(evt) + except: pass group_id = str(self.room_list.GetItemData(self.cur_room_index)) if self.NoGroups: @@ -330,16 +319,13 @@ return if self.cur_room_index >= 0: - if self.cur_room_index != 0: - self.set_lobbybutton(1); - else: - self.set_lobbybutton(0); + if self.cur_room_index != 0: self.set_lobbybutton(1); + else: self.set_lobbybutton(0); group = self.session.get_group_info(group_id) pwd = "" if (group[2] == "True") or (group[2] == "1"): pwd = self.password_manager.GetPassword("room", group_id) - else: - pwd = "" + else: pwd = "" self.session.send_join_group(group_id, pwd) def on_room_select(self,evt): @@ -417,10 +403,8 @@ def gs_connect(self, evt): address = self.texts['address'].GetValue() - try: - dummy = self.name - except: - self.name = `address` + try: dummy = self.name + except: self.name = `address` self.do_connect(address) def gs_disconnect(self, evt): @@ -430,7 +414,6 @@ self.do_create_group() def gs_join(self, evt): - print 'here' self.do_join_group() def gs_join_lobby(self, evt): @@ -456,10 +439,8 @@ def refresh_room_list(self): self.room_list.DeleteAllItems() address = self.texts["address"].GetValue() - try: - cadder = self.session.host_server - except: - cadder = '' + try: cadder = self.session.host_server + except: cadder = '' if self.rmList.has_key(address) and len(self.rmList[address]) > 0 and cadder != address: groups = self.rmList[address] self.NoGroups = True @@ -489,33 +470,30 @@ try: self.svrList = [] self.server_list.DeleteAllItems() - xml_dom = meta_server_lib.get_server_list(["2"]); - node_list = xml_dom.getElementsByTagName('server') + etreeEl = meta_server_lib.get_server_list(["2"]); + node_list = etreeEl.findall('server') hex = orpg.tools.rgbhex.RGBHex() - color1 = settings.get_setting("RoomColor_Active") - color2 = settings.get_setting("RoomColor_Locked") - color3 = settings.get_setting("RoomColor_Empty") - color4 = settings.get_setting("RoomColor_Lobby") + color1 = settings.get("RoomColor_Active") + color2 = settings.get("RoomColor_Locked") + color3 = settings.get("RoomColor_Empty") + color4 = settings.get("RoomColor_Lobby") if len(node_list): length = len(node_list) part = 0 partLength = 1.0/length for n in node_list: - if n.hasAttribute('id') and n.hasAttribute('name') and n.hasAttribute('num_users') and n.hasAttribute('address') and n.hasAttribute('port'): - self.svrList.append(server_instance(n.getAttribute('id'), n.getAttribute('name'), - n.getAttribute('num_users'), n.getAttribute('address'), - n.getAttribute('port'))) - address = n.getAttribute('address') + ':' + n.getAttribute('port') - self.rmList[address] = [] - rooms = n.getElementsByTagName('room') + #if n.hasAttribute('id') and n.hasAttribute('name') and n.hasAttribute('num_users') and n.hasAttribute('address') and n.hasAttribute('port'): + self.svrList.append(server_instance(n.get('id'), n.get('name'), + n.get('num_users'), n.get('address'), + n.get('port'))) + address = n.get('address') + ':' + n.get('port') + self.rmList[address] = [] + rooms = n.findall('room') - for room in rooms: - pwd = room.getAttribute("pwd") - id = room.getAttribute("id") - name = room.getAttribute("name") - nump = room.getAttribute("num_users") - self.rmList[address].append((id, name, pwd, nump)) + for room in rooms: + self.rmList[address].append((room.get("id"), room.get("name"), + room.get("pwd"), room.get("num_users"))) self.svrList.sort(server_instance_compare) for n in self.svrList: @@ -554,14 +532,8 @@ if self.serverNameSet == 0: self.texts["address"].SetValue("127.0.0.1:6774") self.serverNameSet = 1 - else: - pass - + else: pass # Allow xml_dom to be collected - try: - xml_dom.unlink() - except: - pass except Exception, e: print "Server List not available." traceback.print_exc() @@ -569,35 +541,31 @@ def failed_connection(self): if(self.cur_server_index >= 0): - id = self.servers[self.cur_server_index].getAttribute('id') - meta = self.servers[self.cur_server_index].getAttribute('meta') - address = self.servers[self.cur_server_index].getAttribute('address') - port = self.servers[self.cur_server_index].getAttribute('port') + server_index = self.servers[self.cur_server_index] # post_failed_connection will return a non-zero if the server # was removed. If it was, refresh the display - if(meta_server_lib.post_failed_connection(id,meta=meta,address=address,port=port)): + if(meta_server_lib.post_failed_connection(server_index.get('id'), + meta=server_index.get('meta'), address=server_index.get('address'), + port=server_index.get('port'))): self.refresh_server_list() def do_connect(self, address): chat = component.get('chat') chat.InfoPost("Locating server at " + address + "...") - if self.session.connect(address): - self.frame.start_timer() + if self.session.connect(address): self.frame.start_timer() else: chat.SystemPost("Failed to connect to game server...") self.failed_connection() def do_join_lobby(self): self.cur_room_index = 0 - self.session.send_join_group("0","") + self.session.send_join_group("0", "") self.set_lobbybutton(0); def do_join_group(self): if self.cur_room_index >= 0: - if self.cur_room_index != 0: - self.set_lobbybutton(1); - else: - self.set_lobbybutton(0); + if self.cur_room_index != 0: self.set_lobbybutton(1); + else: self.set_lobbybutton(0); group_id = str(self.room_list.GetItemData(self.cur_room_index)) group = self.session.get_group_info(group_id) pwd = "" @@ -607,10 +575,9 @@ #if dlg.ShowModal() == wx.ID_OK: # pwd = dlg.GetValue() #dlg.Destroy() - else: - pwd = "" - if pwd != None: #pwd==None means the user clicked "Cancel" - self.session.send_join_group(group_id,pwd) + else: pwd = "" + if pwd != None: #pwd == None means the user clicked "Cancel" + self.session.send_join_group(group_id, pwd) def do_create_group(self): name = self.texts["room_name"].GetValue() @@ -646,63 +613,42 @@ e = name[loc+1:] name = b + "'" + e oldloc = loc+1 - if self.buttons['gs_pwd'].GetValue(): - pwd = self.texts["room_pwd"].GetValue() - else: - pwd = "" - if name == "": - wx.MessageBox("Invalid Name","Error"); + if self.buttons['gs_pwd'].GetValue(): pwd = self.texts["room_pwd"].GetValue() + else: pwd = "" + if name == "": wx.MessageBox("Invalid Name","Error"); else: msg = "%s is creating room \'%s.\'" % (self.session.name, name) - self.session.send( msg ) - self.session.send_create_group(name,pwd,boot_pwd,minversion) + self.session.send(msg) + self.session.send_create_group(name, pwd, boot_pwd, minversion) self.set_lobbybutton(1); #enable the Lobby quickbutton - #--------------------------------------------------------- # [START] Snowdog: Updated Game Server Window 12/02 #--------------------------------------------------------- def on_size(self,evt): # set column widths for room list - - # set column widths for server list pass - - #--------------------------------------------------------- # [END] Snowdog: Updated Game Server Window 12/02 #--------------------------------------------------------- - def colorize_group_list(self, groups): try: hex = orpg.tools.rgbhex.RGBHex() - for gr in groups: item_list_location = self.room_list.FindItemData(-1,int(gr[0])) if item_list_location != -1: item = self.room_list.GetItem(item_list_location) - if gr[0] == "0": - - r,g,b = hex.rgb_tuple(settings.get_setting("RoomColor_Lobby")) + if gr[0] == "0": r,g,b = hex.rgb_tuple(settings.get("RoomColor_Lobby")) elif gr[3] <> "0": - if gr[2] == "True" or gr[2] == "1": - - r,g,b = hex.rgb_tuple(settings.get_setting("RoomColor_Locked")) - else: - - r,g,b = hex.rgb_tuple(settings.get_setting("RoomColor_Active")) - else: - - r,g,b = hex.rgb_tuple(settings.get_setting("RoomColor_Empty")) - - + r,g,b = hex.rgb_tuple(settings.get("RoomColor_Locked")) + else: r,g,b = hex.rgb_tuple(settings.get("RoomColor_Active")) + else: r,g,b = hex.rgb_tuple(settings.get("RoomColor_Empty")) color = wx.Colour(red=r,green=g,blue=b) item.SetTextColour(color) self.room_list.SetItem(item) - except: - traceback.print_exc() + except: traceback.print_exc()
--- a/orpg/networking/meta_server_lib.py Wed Oct 28 14:24:54 2009 -0500 +++ b/orpg/networking/meta_server_lib.py Thu Oct 29 20:35:28 2009 -0500 @@ -46,6 +46,9 @@ import traceback import re +from xml.etree.ElementTree import ElementTree, Element, iselement +from xml.etree.ElementTree import fromstring, tostring + metacache_lock = RLock() def get_server_dom(data=None,path=None): @@ -78,29 +81,21 @@ print data print # build dom - xml = component.get('xml') - xml_dom = xml.parseXml(data) - xml_dom = xml_dom._get_documentElement() - return xml_dom + etreeEl = data + return etreeEl -def post_server_data( name, realHostName=None): - if realHostName: - data = urllib.urlencode( {"server_data[name]":name, +def post_server_data(name, realHostName=None): + if realHostName: data = urllib.urlencode({"server_data[name]":name, "server_data[version]":PROTOCOL_VERSION, "act":"new", - "REMOTE_ADDR": realHostName } ) - - else: - #print "Letting meta server decide the hostname to list..." - data = urllib.urlencode( {"server_data[name]":name, + "REMOTE_ADDR": realHostName }) + # print "Letting meta server decide the hostname to list..." + else: data = urllib.urlencode({"server_data[name]":name, "server_data[version]":PROTOCOL_VERSION, - "act":"new"} ) - - #xml_dom = get_server_dom( data , "http://openrpg.sf.net/openrpg_servers.php")#Sourceforge still? - path = component.get('settings').get_setting('MetaServerBaseURL') #getMetaServerBaseURL() - xml_dom = get_server_dom(data, path) - ret_val = int( xml_dom.getAttribute( "id" ) ) - return ret_val + "act":"new"}) + path = component.get('settings').get('MetaServerBaseURL') #getMetaServerBaseURL() + etreeEl = get_server_dom(data, path) + return int(etreeEl.get('id')) def post_failed_connection(id,meta=None,address=None,port=None): # For now, turning this off. This needs to be re-vamped for @@ -113,87 +108,64 @@ def remove_server(id): data = urllib.urlencode({"id":id,"act":"del"}); - xml_dom = get_server_dom(data) - ret_val = int(xml_dom.getAttribute("return")) - return ret_val - + etreeEl = get_server_dom(data) + return int(etreeEl.get("return")) -def byStartAttribute(first,second): - # This function is used to easily sort a list of nodes - # by their start time +def byStartAttribute(first, second): + # This function is used to easily sort a list of nodes by their start time + # Ensure there is something to sort with for each - if first.hasAttribute("start"): first_start = int(first.getAttribute("start")) - else: first_start = 0 - - if second.hasAttribute("start"): second_start = int(second.getAttribute("start")) - else: second_start = 0 + first_start = int(first.get('start')) or 0 + second_start = int(second.get('start')) or 0 # Return the result of the cmp function on the two strings - return cmp(first_start,second_start) + return cmp(first_start, second_start) -def byNameAttribute(first,second): - # This function is used to easily sort a list of nodes - # by their name attribute - +def byNameAttribute(first, second): + # This function is used to easily sort a list of nodes by their name attribute # Ensure there is something to sort with for each - if first.hasAttribute("name"): first_name = str(first.getAttribute("name")).lower() - else: first_name = "" - - if second.hasAttribute("name"): second_name = str(second.getAttribute("name")).lower() - else: second_name = "" - + first_name = first.get('name') or '' + second_name = second.get('name') or '' + # Return the result of the cmp function on the two strings return cmp(first_name,second_name) -def get_server_list(versions = None,sort_by="start"): +def get_server_list(versions = None, sort_by="start"): data = urllib.urlencode({"version":PROTOCOL_VERSION,"ports":"%"}) - all_metas = getMetaServers(versions,1) # get the list of metas + all_metas = getMetaServers(versions, 1) # get the list of metas base_meta = getMetaServerBaseURL() #all_metas.reverse() # The last one checked will take precedence, so reverse the order - # so that the top one on the actual list is checked last + # so that the top one on the actual list is checked last + return_hash = {} # this will end up with an amalgamated list of servers - return_hash = {} # this will end up with an amalgamated list of servers - - for meta in all_metas: # check all of the metas - + for meta in all_metas: # check all of the metas #get the server's xml from the current meta bad_meta = 0 #print "Getting server list from " + meta + "..." - try: xml_dom = get_server_dom(data=data,path=meta) - except: - #print "Trouble getting servers from " + meta + "..." - bad_meta = 1 - - if bad_meta: - continue - - if base_meta == meta: - #print "This is our base meta: " + meta - updateMetaCache(xml_dom) - - node_list = xml_dom.getElementsByTagName('server') - - if len(node_list): # if there are entries in the node list - # otherwise, just loop to next meta + try: xml_dom = get_server_dom(data=data, path=meta) + except: bad_meta = 1 #print "Trouble getting servers from " + meta + "..." + if bad_meta: continue + if base_meta == meta: updateMetaCache(xml_dom) #print "This is our base meta: " + meta + node_list = fromstring(xml_dom).findall('server') + if len(node_list): # if there are entries in the node list + # otherwise, just loop to next meta # for each node found, we're going to check the nodes from prior # metas in the list. If a match is found, then use the new values. for n in node_list: - # set them from current node - - if not n.hasAttribute('name'): n.setAttribute('name','NO_NAME_GIVEN') - name = n.getAttribute('name') - if not n.hasAttribute('num_users'): n.setAttribute('num_users','N/A') - num_users = n.getAttribute('num_users') - if not n.hasAttribute('address'): n.setAttribute('address','NO_ADDRESS_GIVEN') - address = n.getAttribute('address') - if not n.hasAttribute('port'): n.setAttribute('port','6774') - port = n.getAttribute('port') - n.setAttribute('meta',meta) + if n.find('name') == None: n.set('name','NO_NAME_GIVEN') + name = n.get('name') + if n.find('num_users') == None: n.set('num_users','N/A') + num_users = n.get('num_users') + if n.find('address') == None: n.set('address','NO_ADDRESS_GIVEN') + address = n.get('address') + if n.find('port') == None: n.set('port','6774') + port = n.get('port') + n.set('meta',meta) end_point = str(address) + ":" + str(port) if return_hash.has_key(end_point): if META_DEBUG: print "Replacing duplicate server entry at " + end_point @@ -203,20 +175,19 @@ # Now, we have to construct a new DOM to pass back. # Create a servers element - return_dom = orpg.minidom.Element("servers") + server_list = Element('servers') # get the nodes stored in return_hash - return_list = return_hash.values() + sort_list = return_hash.values() # sort them by their name attribute. Uses byNameAttribute() # defined above as a comparison function - - if sort_by == "start": return_list.sort(byStartAttribute) - elif sort_by == "name": return_list.sort(byNameAttribute) + if sort_by == "start": sort_list.sort(byStartAttribute) + elif sort_by == "name": sort_list.sort(byNameAttribute) # Add each node to the DOM - for n in return_list: return_dom.appendChild(n) - return return_dom + for n in sort_list: server_list.append(n) + return server_list ## List Format: ## <servers> @@ -226,21 +197,21 @@ def updateMetaCache(xml_dom): try: if META_DEBUG: print "Updating Meta Server Cache" - metaservers = xml_dom.getElementsByTagName( 'metaservers' ) # pull out the metaservers bit + metaservers = xml_dom.findall('metaservers') # pull out the metaservers bit if len(metaservers) == 0: cmetalist = getRawMetaList() xml_dom = get_server_dom(cmetalist[0]) - metaservers = xml_dom.getElementsByTagName( 'metaservers' ) - authoritative = metaservers[0].getAttribute('auth') + metaservers = xml_dom.findall('metaservers') + authoritative = metaservers[0].get('auth') if META_DEBUG: print " Authoritive Meta: "+str(authoritative) - metas = metaservers[0].getElementsByTagName("meta") # get the list of metas + metas = metaservers[0].findall("meta") # get the list of metas if META_DEBUG: print " Meta List ("+str(len(metas))+" servers)" try: metacache_lock.acquire() ini = open(dir_struct["user"]+"metaservers.cache","w") for meta in metas: - if META_DEBUG: print " Writing: "+str(meta.getAttribute('path')) - ini.write(str(meta.getAttribute('path')) + " " + str(meta.getAttribute('versions')) + "\n") + if META_DEBUG: print " Writing: "+str(meta.get('path')) + ini.write(str(meta.get('path')) + " " + str(meta.get('versions')) + "\n") ini.close() finally: metacache_lock.release() @@ -248,7 +219,18 @@ if META_DEBUG: traceback.print_exc() print "Meta Server Lib: UpdateMetaCache(): " + str(e) -def getRawMetaList(): +def getRawMetaList(path=None): + ### Alpha ### + """This code will allow for a list of metas to be created. Future developement will more integrate the list of metas""" + if path != None: + metas = [] + data = urllib.urlencode({"version":PROTOCOL_VERSION,"ports":"%"}) + xml_dom = get_server_dom(data, path) + node_list = fromstring(xml_dom).findall('meta_server') + if len(node_list): + for n in node_list: + metas.append(n.get('path')) + return metas try: try: metacache_lock.acquire() @@ -268,16 +250,15 @@ def getMetaServers(versions = None, pick_random=0): """ get meta server URLs as a list - versions is a list of acceptable version numbers. A False truth value will use getMetaServerBaseURL() - set a default if we have weird reading problems default_url = "http://www.openrpg.com/openrpg_servers.php" """ + ### Pre Alpha Design ### + """ Here is how to handle Multiple Meta servers, and probably the best way to do it. Create an XML file that contains nodes with the various servers. Users will grab that meta data and have the option to connect to multiple meta servers which will allow them to find all the rooms. A check box should be used so if one server faile the users can continue without much lag. When creating a server hosts will need to select a meta to go too. This should be in the final of Ornery Orc.""" meta_names = [] - if(versions): # If versions are supplied, then look in metaservers.conf try: """ @@ -287,15 +268,13 @@ handle. Generally, this will be either a 1 for the original Meta format, or 2 for the new one. """ - # Read in the metas + #Adding a path object will attempt to look for a meta_network. metas = getRawMetaList() - #print str(metas) # go through each one to check if it should be returned, based on the # version numbers allowed. for meta in metas: - # split the line on whitespace # obviously, your meta servers urls shouldn't contain whitespace. duh. words = meta.split() @@ -347,7 +326,6 @@ node_list = tree.getElementsByTagName("MetaServerBaseURL") if node_list: url = node_list[0].getAttribute("value") - # allow tree to be collected try: tree.unlink() except: pass @@ -391,21 +369,19 @@ just written, i.e. TestDeleteStatus() and Delete() """ - def __init__(self,name=None,realHostName=None,num_users = "Hmmm",MetaPath=None,port=6774,register_callback=None): - - Thread.__init__(self,name="registerThread") - self.rlock = RLock() # Re-entrant lock used to make this class thread safe - self.die_event = Event() # The main loop in run() will wait with timeout on this - if name: - self.name = name # Name that the server want's displayed on the Meta - else: - self.name = "Unnamed server" # But use this if for some crazy reason no name is - # passed to the constructor - self.num_users = num_users # the number of users currently on this server + def __init__(self, name=None, realHostName=None, num_users="0", + MetaPath=None, port=6774, register_callback=None): + Thread.__init__(self, name="registerThread") + self.rlock = RLock() # Re-entrant lock used to make this class thread safe + self.die_event = Event() # The main loop in run() will wait with timeout on this + self.name = name or 'Unnamed Server' # Name that the server want's displayed on the Meta + # But use Unnamed Server if for some crazy reason + # no name is passed to the constructor + self.num_users = num_users # the number of users currently on this server self.realHostName = realHostName # Name to advertise for connection self.id = "0" # id returned from Meta. Defaults to "0", which # indicates a new registration. - self.cookie = "0" # cookie returned from Meta. Defaults to "0",which + self.cookie = "0" # cookie returned from Meta. Defaults to "0", which # indicates a new registration. self.interval = 0 # interval returned from Meta. Is how often to # re-register, in minutes. @@ -422,11 +398,8 @@ it easier to have multiple registerThreads going to keep the server registered on multiple (compatible) Metas. """ - - if MetaPath == None: - self.path = getMetaServerBaseURL() # Do this if no Meta specified - else: - self.path = MetaPath + if MetaPath == None: self.path = getMetaServerBaseURL() # Do this if no Meta specified + else: self.path = MetaPath def getIdAndCookie(self): return self.id, self.cookie @@ -435,15 +408,13 @@ try: self.rlock.acquire() return self.die_event.isSet() - finally: - self.rlock.release() + finally: self.rlock.release() def Delete(self): try: self.rlock.acquire() self.die_event.set() - finally: - self.rlock.release() + finally: self.rlock.release() def run(self): """ @@ -455,24 +426,23 @@ re-registers this server and sleeps Interval minutes until the thread is ordered to die in place """ - while(not self.TestDeleteStatus()): # Loop while until told to die + while(not self.TestDeleteStatus()): # Loop while until told to die # Otherwise, call thread safe register(). self.register(self.name, self.realHostName, self.num_users) if META_DEBUG: print "Sent Registration Data" # register() will end up setting the state variables # for us, including self.interval. try: - self.rlock.acquire() # Serialize access to this state information + self.rlock.acquire() # Serialize access to this state information - if self.interval >= 3: # If the number of minutes is one or greater - self.interval -= 1 # wake up with 30 seconds left to re-register + if self.interval >= 3: # If the number of minutes is one or greater + self.interval -= 1 # wake up with 30 seconds left to re-register else: - self.interval = .5 # Otherwise, we probably experienced some kind - # of error from the Meta in register(). Sleep - # for 6 seconds and start from scratch. + self.interval = .5 # Otherwise, we probably experienced some kind + # of error from the Meta in register(). Sleep + # for 6 seconds and start from scratch. - finally: # no matter what, release the lock - self.rlock.release() + finally: self.rlock.release() # no matter what, release the lock # Wait interval minutes for a command to die die_signal = self.die_event.wait(self.interval*60) @@ -505,10 +475,10 @@ "server_data[cookie]":self.cookie, "server_data[version]":PROTOCOL_VERSION, "act":"unregister"} ) - try: - xml_dom = get_server_dom(data=data, path=self.path) # this POSTS the request and returns the result + try: # this POSTS the request and returns the result + xml_dom = get_server_dom(data=data, path=self.path) if xml_dom.hasAttribute("errmsg"): - print "Error durring unregistration: " + xml_dom.getAttribute("errmsg") + print "Error durring unregistration: " + xml_dom.get("errmsg") except: if META_DEBUG: print "Problem talking to Meta. Will go ahead and die, letting Meta remove us." # If there's an error, echo it to the console @@ -562,8 +532,8 @@ "server_data[version]":PROTOCOL_VERSION, "server_data[num_users]":self.num_users, "act":"register"} ) - try: - xml_dom = get_server_dom(data=data,path=self.path) # this POSTS the request and returns the result + try: # this POSTS the request and returns the result + etreeEl = get_server_dom(data=data, path=self.path) except: if META_DEBUG: print "Problem talking to server. Setting interval for retry ..." if META_DEBUG: print data @@ -584,10 +554,10 @@ return 0 # indicates that it was okay to call, not that no errors occurred # If there is a DOM returned .... - if xml_dom: + if etreeEl: # If there's an error, echo it to the console - if xml_dom.hasAttribute("errmsg"): - print "Error durring registration: " + xml_dom.getAttribute("errmsg") + if etreeEl.hasAttribute("errmsg"): + print "Error durring registration: " + etreeEl.get("errmsg") if META_DEBUG: print data if META_DEBUG: print """ @@ -609,24 +579,20 @@ Is it wrong to have a method where there's more comments than code? :) """ try: - self.interval = int(xml_dom.getAttribute("interval")) - self.id = xml_dom.getAttribute("id") - self.cookie = xml_dom.getAttribute("cookie") - if not xml_dom.hasAttribute("errmsg"): - updateMetaCache(xml_dom) + self.interval = int(etreeEl.get("interval")) + self.id = etreeEl.get("id") + self.cookie = etreeEl.get("cookie") + if not etreeEl.hasAttribute("errmsg"): updateMetaCache(xml_dom) except: if META_DEBUG: print if META_DEBUG: print "OOPS! Is the Meta okay? It should be returning an id, cookie, and interval." if META_DEBUG: print "Check to see what it really returned.\n" # Let xml_dom get garbage collected - try: - xml_dom.unlink() - except: - pass + try: xml_dom.unlink() + except: pass else: # else if no DOM is returned from get_server_dom() print "Error - no DOM constructed from Meta message!" return 0 # Let caller know it was okay to call us - finally: - self.rlock.release() + finally: self.rlock.release() # End of class registerThread ################################################################################
--- a/orpg/networking/mplay_client.py Wed Oct 28 14:24:54 2009 -0500 +++ b/orpg/networking/mplay_client.py Thu Oct 29 20:35:28 2009 -0500 @@ -46,8 +46,10 @@ from orpg.orpgCore import component from orpg.orpg_xml import xml -from xml.etree.ElementTree import ElementTree, Element +from xml.etree.ElementTree import ElementTree, Element, iselement from xml.etree.ElementTree import fromstring, tostring +from xml.parsers.expat import ExpatError + try: import bz2 @@ -150,7 +152,7 @@ # Loop as long as we have a connection while( self.get_status() == MPLAY_CONNECTED ): - try: readMsg = self.outbox.get( block=1 ) + try: readMsg = self.outbox.get(block=1) except Exception, text: self.log_msg( ("outbox.get() got an exception: ", text) ) @@ -192,7 +194,7 @@ if bytes == 0: self.log_msg( "Remote has disconnected!" ) self.set_status( MPLAY_DISCONNECTING ) - self.outbox.put( "" ) # Make sure the other thread is woken up! + self.outbox.put("") # Make sure the other thread is woken up! self.sendThreadExitEvent.set() self.log_msg( "recvThread has terminated..." ) @@ -211,16 +213,10 @@ offset += sent sentm = offset else: - # Calculate our message length - length = len(msg) - - # Encode the message length into network byte order - lp = pack('!i', length) - + length = len(msg) # Calculate our message length + lp = pack('!i', length) # Encode the message length into network byte order try: - # Send the encoded length - sentl = sock.send( lp ) - + sentl = sock.send( lp ) # Send the encoded length # Now, send the message the the length was describing sentm = sock.send( msg ) if self.isServer(): self.log_msg(("data_sent", sentl+sentm)) @@ -251,27 +247,18 @@ data = "" return data - def recvMsg( self, sock ): - """This method now expects to receive a message having a 4-byte prefix length. It will ONLY read - completed messages. In the event that the remote's connection is terminated, it will throw an - exception which should allow for the caller to more gracefully handle this exception event. + def recvMsg(self, sock): + """This method now expects to receive a message having a 4-byte prefix length. It will ONLY read completed messages. In the event that the remote's connection is terminated, it will throw an exception which should allow for the caller to more gracefully handle this exception event. - Because we use strictly reading ONLY based on the length that is told to use, we no longer have to - worry about partially adjusting for fragmented buffers starting somewhere within a buffer that we've - read. Rather, it will get ONLY a whole message and nothing more. Everything else will remain buffered - with the OS until we attempt to read the next complete message.""" - + Because we use strictly reading ONLY based on the length that is told to use, we no longer have to worry about partially adjusting for fragmented buffers starting somewhere within a buffer that we've read. Rather, it will get ONLY a whole message and nothing more. Everything else will remain buffered with the OS until we attempt to read the next complete message.""" msgData = "" try: lenData = self.recvData( sock, MPLAY_LENSIZE ) - # Now, convert to a usable form - (length,) = unpack('!i', lenData) - # Read exactly the remaining amount of data - msgData = self.recvData( sock, length ) + (length,) = unpack('!i', lenData) # Now, convert to a usable form + msgData = self.recvData( sock, length ) # Read exactly the remaining amount of data if self.isServer(): self.log_msg(("data_recv", length+4)) - # Make the peer IP address available for reference later - if self.remote_ip is None: + if self.remote_ip is None: # Make the peer IP address available for reference later self.remote_ip = self.sock.getpeername() except IOError, e: self.log_msg( e ) except Exception, e: self.log_msg( e ) @@ -282,15 +269,15 @@ self.status = MPLAY_CONNECTED self.sock.setblocking(1) # Confirm that our threads have started - thread.start_new_thread( self.sendThread,(0,) ) - thread.start_new_thread( self.recvThread,(0,) ) + thread.start_new_thread( self.sendThread,(0,)) + thread.start_new_thread( self.recvThread,(0,)) self.startedEvent.set() def disconnect(self): self.set_status(MPLAY_DISCONNECTING) self.log_msg("client stub " + self.ip +" disconnecting...") self.log_msg("closing sockets...") - try: self.sock.shutdown( 2 ) + try: self.sock.shutdown(2) except Exception, e: print "Caught exception: " + str(e) print @@ -321,8 +308,7 @@ The IP field should really be deprecated as too many systems are NAT'd and/or behind firewalls for a client provided IP address to have much value. As such, we now label it as deprecated. """ - def toxml(self,action): - """ + def toxml(self, action): el = Element('player') el.set('name', myescape(self.name)) el.set('action', action) @@ -334,32 +320,13 @@ el.set('protocol_version', self.protocol_version) el.set('client_string', self.client_string) el.set('useCompression', str(self.useCompression)) - cmpType = 'None' if cmpBZ2 and (self.compressionType == 'Undefined' or self.compressionType == bz2): cmpType = 'bz2' elif cmpZLIB and (self.compressionType == 'Undefined' or self.compressionType == zlib): cmpType = 'zlib' - el.set('cmpType', cmpType) - return el - """ - - xml_data = '<player name="' + myescape(self.name) + '"' - xml_data += ' action="' + action + '" id="' + self.id + '"' - xml_data += ' group_id="' + self.group_id + '" ip="' + self.ip + '"' - xml_data += ' status="' + self.text_status + '"' - xml_data += ' version="' + self.version + '"' - xml_data += ' protocol_version="' + self.protocol_version + '"' - xml_data += ' client_string="' + self.client_string + '"' - xml_data += ' useCompression="' + str(self.useCompression) + '"' - if cmpBZ2 and (self.compressionType == 'Undefined' or self.compressionType == bz2): - xml_data += ' cmpType="bz2"' - elif cmpZLIB and (self.compressionType == 'Undefined' or self.compressionType == zlib): - xml_data += ' cmpType="zlib"' - else: xml_data += ' cmpType="None"' - xml_data += ' />' - return xml_data + return tostring(el) def log_msg(self,msg): if self.log_console: @@ -374,15 +341,6 @@ def my_role(self): #Leaving this for testing. return self.role - """ - if self.role == "GM": - return self.ROLE_GM - elif self.role == "Player": - return self.ROLE_PLAYER - elif self.role == "Lurker": - return self.ROLE_LURKER - return -1 - """ def set_status(self,status): self.statLock.acquire() @@ -568,25 +526,28 @@ return (0,id,name) self.ignore_name.append(self.players[id][0]) self.ignore_id.append(self.players[id][2]) - return (1,self.players[id][2],self.players[id][0]) + return (1, self.players[id][2], self.players[id][0]) def boot_player(self,id,boot_pwd = ""): - #self.send(BOOT_MSG,id) - msg = '<boot boot_pwd="' + boot_pwd + '"/>' - self.send(msg,id) + el = Element('boot') + el.set('boot_pwd', boot_pwd) + self.send(tostring(el), id) #--------------------------------------------------------- # [START] Snowdog Password/Room Name altering code 12/02 #--------------------------------------------------------- - def set_room_pass(self,npwd,pwd=""): - recycle_bin = "<alter key=\"pwd\" " - recycle_bin += "val=\"" +npwd+ "\" bpw=\"" + pwd + "\" " - recycle_bin += "plr=\"" + self.id +"\" gid=\"" + self.group_id + "\" />" - self.outbox.put(recycle_bin); del recycle_bin #makes line easier to read. --TaS + def set_room_pass(self, npwd, pwd=""): + el = Element('alter') + el.set('key', 'pwd') + el.set('val', npwd) + el.set('bpw', pwd) + el.set('plr', self.id) + el.set('gid', self.group_id) + self.outbox.put(tostring(el)) self.update() - def set_room_name(self,name,pwd=""): + def set_room_name(self, name, pwd=""): loc = name.find("&") oldloc=0 while loc > -1: @@ -614,10 +575,13 @@ e = name[loc+1:] name = b + "'" + e oldloc = loc+1 - recycle_bin = "<alter key=\"name\" " - recycle_bin += "val=\"" + name + "\" bpw=\"" + pwd + "\" " - recycle_bin += "plr=\"" + self.id +"\" gid=\"" + self.group_id + "\" />" - self.outbox.put(recycle_bin); del recycle_bin #makes line easier to read. --TaS + el = Element('alter') + el.set('key', 'pwd') + el.set('val', npwd) + el.set('bpw', pwd) + el.set('plr', self.id) + el.set('gid', self.group_id) + self.outbox.put(tostring(el)) self.update() #--------------------------------------------------------- @@ -625,19 +589,39 @@ #--------------------------------------------------------- def display_roles(self): - self.outbox.put("<role action=\"display\" player=\"" + self.id +"\" group_id=\""+self.group_id + "\" />") + el = Element('role') + el.set('action', 'display') + el.set('player', self.id) + el.set('group_id', self.group_id) + self.outbox.put(tostring(el)) def get_role(self): - self.outbox.put("<role action=\"get\" player=\"" + self.id +"\" group_id=\""+self.group_id + "\" />") + el = Element('role') + el.set('action', 'get') + el.set('player', self.id) + el.set('group_id', self.group_id) + self.outbox.put(tostring(el)) - def set_role(self,player,role,pwd=""): - recycle_bin = "<role action=\"set\" player=\"" + player + "\" " - recycle_bin += "role=\"" +role+ "\" boot_pwd=\"" + pwd + "\" group_id=\"" + self.group_id + "\" />" - self.outbox.put(recycle_bin); del recycle_bin #makes line easer to read. --TaS + def set_role(self, player, role, pwd=""): + el = Element('role') + el.set('action', 'set') + el.set('player', player) + el.set('role', role) + el.set('boot_pwd', pwd) + el.set('group_id', self.group_id) + self.outbox.put(tostring(el)) self.update() - def send(self,msg,player="all"): + def send(self, msg, player="all"): if self.status == MPLAY_CONNECTED and player != self.id: + ### Pre Alpha ### + #el = Element('msg') + #el.set('to', player) + #el.set('from', self.id) + #el.set('group_id', self.group_id) + #el.append(fromstring(msg)) + #self.outbox.put(tostring(el)) + ### Current chat is not ready for Element Tree ### self.outbox.put("<msg to='"+player+"' from='"+self.id+"' group_id='"+self.group_id+"' />"+msg) self.check_my_status() @@ -646,19 +630,26 @@ self.outbox.put(snd_xml) self.check_my_status() - def send_create_group(self,name,pwd,boot_pwd,minversion): - recycle_bin = "<create_group from=\""+self.id+"\" " - recycle_bin += "pwd=\""+pwd+"\" name=\""+ name+"\" boot_pwd=\""+boot_pwd+"\" " - recycle_bin += "min_version=\"" + minversion +"\" />" - self.outbox.put(recycle_bin); del recycle_bin #makes line easier to read. --TaS + def send_create_group(self, name, pwd, boot_pwd, min_version): + el = Element('create_group') + el.set('from', self.id) + el.set('pwd', pwd) + el.set('name', name) + el.set('boot_pwd', boot_pwd) + el.set('min_version', min_version) + self.outbox.put(tostring(el)) - def send_join_group(self,group_id,pwd): + def send_join_group(self, group_id, pwd): if (group_id != 0): self.update_role("Lurker") - self.outbox.put("<join_group from=\""+self.id+"\" pwd=\""+pwd+"\" group_id=\""+str(group_id)+"\" />") + el = Element('join_group') + el.set('from', self.id) + el.set('pwd', pwd) + el.set('group_id', str(group_id)) + print 'send join group ', str(group_id) + self.outbox.put(tostring(el)) def poll(self, evt=None): - try: - msg = self.inbox.get_nowait() + try: msg = self.inbox.get_nowait() except: if self.get_status() != MPLAY_CONNECTED: self.check_my_status() @@ -689,29 +680,26 @@ self.add_msg_handler('password', self.on_password, True) self.add_msg_handler('sound', self.on_sound, True) - def pretranslate(self,data): + def pretranslate(self, data): # Pre-qualify our data. If we don't have atleast 5-bytes, then there is # no way we even have a valid message! if len(data) < 5: return - end = data.find(">") - head = data[:end+1] - msg = data[end+1:] - xml_dom = self.xml.parseXml(head) - xml_dom = xml_dom._get_documentElement() - tag_name = xml_dom._get_tagName() - id = xml_dom.getAttribute("from") - if id == '': id = xml_dom.getAttribute("id") - if self.msg_handlers.has_key(tag_name): self.msg_handlers[tag_name](id, data, xml_dom) - else: - #Unknown messages recived ignoring - #using pass insted or printing an error message - #because plugins should now be able to send and proccess messages - #if someone is using a plugin to send messages and this user does not - #have the plugin they would be getting errors - pass - if xml_dom: xml_dom.unlink() + try: el = fromstring(data) + except ExpatError: + end = data.find(">") + head = data[:end+1] + msg = data[end+1:] + el = fromstring(head) + try: + el1 = fromstring(msg) + el.append(el1) + except ExpatError: + el.text = msg + #logger.general("Bad Message: \n" + data) + id = el.get('from') or el.get('id') + if el.tag in self.msg_handlers: self.msg_handlers[el.tag](id, data, el) - def on_sound(self, id, data, xml_dom): + def on_sound(self, id, data, etreeEl): (ignore_id,ignore_name) = self.get_ignore_list() for m in ignore_id: if m == id: @@ -719,96 +707,79 @@ print "ignoring sound from player:" return chat = self.get_chat() - snd = xml_dom.getAttribute("url") - loop_sound = xml_dom.getAttribute("loop") - chat.sound_player.play(snd, "remote", loop_sound) + chat.sound_player.play(etreeEl.get('url'), 'remote', etreeEl.get('loop')) - def on_msg(self, id, data, xml_dom): + def on_msg(self, id, data, etreeEl): end = data.find(">") head = data[:end+1] msg = data[end+1:] - if id == "0": - self.on_receive(msg,None) # None get's interpreted in on_receive as the sys admin. - # Doing it this way makes it harder to impersonate the admin - else: - if self.is_valid_id(id): self.on_receive(msg,self.players[id]) - if xml_dom: xml_dom.unlink() + if msg[-6:] == '</msg>': msg = msg[:-6] + if id == "0": self.on_receive(msg, None) + # None get's interpreted in on_receive as the sys admin. + # Doing it this way makes it harder to impersonate the admin + elif self.is_valid_id(id): self.on_receive(msg, self.players[id]) - def on_ping(self, id, msg, xml_dom): + def on_ping(self, id, msg, etreeEl): #a REAL ping time implementation by Snowdog 8/03 # recieves special server <ping time="###" /> command # where ### is a returning time from the clients ping command #get current time, pull old time from object and compare them # the difference is the latency between server and client * 2 ct = time.clock() - ot = xml_dom.getAttribute("time") + ot = etreeEl.get("time") latency = float(float(ct) - float(ot)) - latency = int( latency * 10000.0 ) - latency = float( latency) / 10.0 + latency = int(latency * 10000.0) + latency = float(latency) / 10.0 ping_msg = "Ping Results: " + str(latency) + " ms (parsed message, round trip)" - self.on_receive(ping_msg,None) - if xml_dom: xml_dom.unlink() + self.on_receive(ping_msg, None) - def on_group(self, id, msg, xml_dom): - name = xml_dom.getAttribute("name") - players = xml_dom.getAttribute("players") - act = xml_dom.getAttribute("action") - pwd = xml_dom.getAttribute("pwd") - group_data = (id, name, pwd, players) - - if act == 'new': + def on_group(self, id, msg, etreeEl): + act = etreeEl.get("action") + group_data = (id, etreeEl.get("name"), etreeEl.get("pwd"), etreeEl.get("players")) + if act == 'new' or 'update': self.groups[id] = group_data - self.on_group_event(mplay_event(GROUP_NEW, group_data)) + if act == 'update': self.on_group_event(mplay_event(GROUP_UPDATE, group_data)) + elif act == 'new': self.on_group_event(mplay_event(GROUP_NEW, group_data)) elif act == 'del': del self.groups[id] self.on_group_event(mplay_event(GROUP_DEL, group_data)) - elif act == 'update': - self.groups[id] = group_data - self.on_group_event(mplay_event(GROUP_UPDATE, group_data)) - if xml_dom: xml_dom.unlink() - def on_role(self, id, msg, xml_dom): - act = xml_dom.getAttribute("action") - role = xml_dom.getAttribute("role") + def on_role(self, id, msg, etreeEl): + act = etreeEl.get("action") if (act == "set") or (act == "update"): try: (a,b,c,d,e,f,g,h) = self.players[id] if id == self.id: - self.players[id] = (a,b,c,d,e,f,g,role) - self.update_role(role) - else: self.players[id] = (a,b,c,d,e,f,g,role) - self.on_player_event(mplay_event(PLAYER_UPDATE,self.players[id])) + self.players[id] = (a,b,c,d,e,f,g,etreeEl.get("role")) + self.update_role(etreeEl.get("role")) + else: self.players[id] = (a,b,c,d,e,f,g,etreeEl.get("role")) + self.on_player_event(mplay_event(PLAYER_UPDATE, self.players[id])) except: pass - if xml_dom: xml_dom.unlink() - def on_player(self, id, msg, xml_dom): - act = xml_dom.getAttribute("action") - ip = xml_dom.getAttribute("ip") - name = xml_dom.getAttribute("name") - status = xml_dom.getAttribute("status") - version = xml_dom.getAttribute("version") - protocol_version = xml_dom.getAttribute("protocol_version") - client_string = xml_dom.getAttribute("client_string") - try: player = (name, ip, id, status, - version, protocol_version, - client_string, self.players[id][7]) + def on_player(self, id, msg, etreeEl): + act = etreeEl.get("action") + try: player = (etreeEl.get("name"), etreeEl.get("ip"), id, etreeEl.get("status"), + etreeEl.get("version"), etreeEl.get("protocol_version"), + etreeEl.get("client_string"), self.players[id][7]) except Exception, e: - player = (name, ip, id, status, - version, protocol_version, - client_string, "Player") + player = (etreeEl.get("name"), etreeEl.get("ip"), id, etreeEl.get("status"), + etreeEl.get("version"), etreeEl.get("protocol_version"), + etreeEl.get("client_string"), "Player") + print e if act == "new": self.players[id] = player self.on_player_event(mplay_event(PLAYER_NEW, self.players[id])) elif act == "group": - self.group_id = xml_dom.getAttribute("group_id") + self.group_id = etreeEl.get('group_id') self.clear_players() self.on_mplay_event(mplay_event(MPLAY_GROUP_CHANGE, self.groups[self.group_id])) - self.players[self.id] = self.get_my_info() #(self.name,self.ip,self.id,self.text_status) + self.players[self.id] = self.get_my_info() + #(self.name,self.ip,self.id,self.text_status) self.on_player_event(mplay_event(PLAYER_NEW, self.players[self.id])) elif act == "failed": self.on_mplay_event(mplay_event(MPLAY_GROUP_CHANGE_F)) elif act == "del": - self.on_player_event(mplay_event(PLAYER_DEL,self.players[id])) + self.on_player_event(mplay_event(PLAYER_DEL, self.players[id])) if self.players.has_key(id): del self.players[id] if id == self.id: self.do_disconnect() # the next two cases handle the events that are used to let you know when others are typing @@ -818,20 +789,13 @@ self.update_self_from_player(player) else: self.players[id] = player dont_send = 0 - for m in self.ignore_id: + for m in self.ignore_id: if m == id: dont_send=1 - if dont_send != 1: self.on_player_event(mplay_event(PLAYER_UPDATE,self.players[id])) - if xml_dom: xml_dom.unlink() + if dont_send != 1: self.on_player_event(mplay_event(PLAYER_UPDATE, self.players[id])) - def on_password(self, id, msg, xml_dom): - signal = type = id = data = None - id = xml_dom.getAttribute("id") - type = xml_dom.getAttribute("type") - signal = xml_dom.getAttribute("signal") - data = xml_dom.getAttribute("data") - self.on_password_signal( signal,type,id,data ) - if xml_dom: - xml_dom.unlink() + def on_password(self, id, msg, etreeEl): + self.on_password_signal(etreeEl.get("signal"), etreeEl.get("type"), + etreeEl.get("id"), etreeEl.get("data")) def check_my_status(self): status = self.get_status() @@ -843,7 +807,6 @@ if self.is_connected(): self.log_msg( "Client is already connected to a server?!? Need to disconnect first." ) return 0 - xml_dom = None self.inbox = Queue.Queue(0) self.outbox = Queue.Queue(0) addressport_ar = addressport.split(":") @@ -858,29 +821,29 @@ try: self.sock.connect((address,port)) # send client into with id=0 - self.sendMsg( self.sock, self.toxml("new") ) - data = self.recvMsg( self.sock ) + outgoing = self.toxml('new') + if iselement(outgoing): outgoing = tostring(outgoing) + self.sendMsg(self.sock, outgoing) + data = self.recvMsg(self.sock) # get new id and group_id - xml_dom = self.xml.parseXml(data) - xml_dom = xml_dom._get_documentElement() - self.id = xml_dom.getAttribute("id") - self.group_id = xml_dom.getAttribute("group_id") - if xml_dom.hasAttribute('useCompression') and xml_dom.getAttribute('useCompression') == 'True': + el = fromstring(data) + self.id = el.get('id') + self.group_id = el.get('group_id') + if el.get('useCompression') == 'True': self.useCompression = True - if xml_dom.hasAttribute('cmpType'): - if cmpBZ2 and xml_dom.getAttribute('cmpType') == 'bz2': - self.compressionType = bz2 - elif cmpZLIB and xml_dom.getAttribute('cmpType') == 'zlib': - self.compressionType = zlib - else: self.compressionType = None - else: self.compressionType = bz2 + if cmpBZ2 and el.get('cmpType') == 'bz2': + self.compressionType = bz2 + elif cmpZLIB and el.get('cmpType') == 'zlib': + self.compressionType = zlib + else: self.compressionType = None #send confirmation - self.sendMsg( self.sock, self.toxml("new") ) + outgoing = self.toxml('new') + if iselement(outgoing): outgoing = tostring(outgoing) + self.sendMsg(self.sock, outgoing) except Exception, e: + print e self.log_msg(e) - if xml_dom: xml_dom.unlink() return 0 - # Start things rollings along self.initialize_threads() self.on_mplay_event(mplay_event(MPLAY_CONNECTED)) @@ -888,12 +851,13 @@ self.text_status, self.version, self.protocol_version, self.client_string, self.role) self.on_player_event(mplay_event(PLAYER_NEW,self.players[self.id])) - if xml_dom: xml_dom.unlink() return 1 def start_disconnect(self): self.on_mplay_event(mplay_event(MPLAY_DISCONNECTING)) - self.outbox.put( self.toxml("del") ) + outgoing = self.toxml('del') + if iselement(outgoing): outgoing = tostring(outgoing) + self.outbox.put(outgoing) ## Client Side Disconect Forced -- Snowdog 10-09-2003 #pause to allow GUI events time to sync. time.sleep(1)
--- a/orpg/networking/mplay_groups.py Wed Oct 28 14:24:54 2009 -0500 +++ b/orpg/networking/mplay_groups.py Thu Oct 29 20:35:28 2009 -0500 @@ -22,15 +22,12 @@ f = open( mapFile ) tree = f.read() f.close() - else: f = open(orpg.dirpath.dir_struct["template"] + "default_map.xml") tree = f.read() f.close() - self.game_map.init_from_xml(tree) - def add_player(self,id): self.players.append(id)
--- a/orpg/networking/mplay_messaging.py Wed Oct 28 14:24:54 2009 -0500 +++ b/orpg/networking/mplay_messaging.py Thu Oct 29 20:35:28 2009 -0500 @@ -67,7 +67,8 @@ self.port = int(component.get("settings").get_setting("port")) ##used even? self.ip = socket.gethostbyname(socket.gethostname()) self.lensize = calcsize('i') - self.mplay_type = ('disconnected', 'connected', 'disconnecting', 'group change', 'group change failed') + self.mplay_type = ('disconnected', 'connected', + 'disconnecting', 'group change', 'group change failed') self.status = self.mplay_type[0] self.alive = False self.sock = None @@ -93,26 +94,31 @@ self.groups = {} #Setup Stuff from the Server - if kwargs.has_key('inbox'): - self.inbox = kwargs['inbox'] - if kwargs.has_key('sock'): - self.sock = kwargs['sock'] - if kwargs.has_key('ip'): - self.ip = kwargs['ip'] - if kwargs.has_key('role'): - self.role = kwargs['role'] - if kwargs.has_key('id'): - self.id = kwargs['id'] - if kwargs.has_key('group_id'): - self.group_id = kwargs['group_id'] - if kwargs.has_key('name'): - self.name = kwargs['name'] - if kwargs.has_key('version'): - self.version = kwargs['version'] - if kwargs.has_key('protocol_version'): - self.protocol_version = kwargs['protocol_version'] - if kwargs.has_key('client_string'): - self.client_string = kwargs['client_string'] + """ + if kwargs.has_key('inbox'): self.inbox = kwargs['inbox'] + if kwargs.has_key('sock'): self.sock = kwargs['sock'] + if kwargs.has_key('ip'): self.ip = kwargs['ip'] + if kwargs.has_key('role'): self.role = kwargs['role'] + if kwargs.has_key('id'): self.id = kwargs['id'] + if kwargs.has_key('group_id'): self.group_id = kwargs['group_id'] + if kwargs.has_key('name'): self.name = kwargs['name'] + if kwargs.has_key('version'): self.version = kwargs['version'] + if kwargs.has_key('protocol_version'): self.protocol_version = kwargs['protocol_version'] + if kwargs.has_key('client_string'): self.client_string = kwargs['client_string'] + """ + + ### Alpha ### + self.inbox = kwargs['inbox'] or pass + self.sock = kwargs['sock'] or pass + self.ip = kwargs['ip'] or pass + self.role = kwargs['role'] or pass + self.id = kwargs['id'] or pass + self.group_id = kwargs['group_id'] or pass + self.name = kwargs['name'] or pass + self.version = kwargs['version'] or pass + self.protocol_version = kwargs['protocol_version'] or pass + self.client_string = kwargs['client_string'] or pass + def build_message(self, *args, **kwargs): #print args @@ -159,7 +165,8 @@ def update_self_from_player(self, player): try: - (self.name, self.ip, self.id, self.text_status, self.version, self.protocol_version, self.client_string,role) = player + (self.name, self.ip, self.id, self.text_status, + self.version, self.protocol_version, self.client_string,role) = player except: logger.general("Exception: messenger->update_self_from_player():\n" + traceback.format_exc()) @@ -218,12 +225,9 @@ idletime = self.idle_time() idlemins = idletime / 60 status = "Unknown" - if idlemins < 3: - status = "Active" - elif idlemins < 10: - status = "Idle ("+str(int(idlemins))+" mins)" - else: - status = "Inactive ("+str(int(idlemins))+" mins)" + if idlemins < 3: status = "Active" + elif idlemins < 10: status = "Idle ("+str(int(idlemins))+" mins)" + else: status = "Inactive ("+str(int(idlemins))+" mins)" return status def connected_time(self): @@ -245,18 +249,14 @@ self.timeout_time = None def check_time_out(self): - if self.timeout_time==None: - self.timeout_time = time.time() + if self.timeout_time == None: self.timeout_time = time.time() curtime = time.time() diff = curtime - self.timeout_time - if diff > 1800: - return 1 - else: - return 0 + if diff > 1800: return 1 + else: return 0 def send(self, msg): - if self.get_status() == 'connected': - self.outbox.put(msg) + if self.get_status() == 'connected': self.outbox.put(msg) def change_group(self, group_id, groups): old_group_id = str(self.group_id) @@ -275,17 +275,13 @@ def add_msg_handler(self, tag, function, core=False): if not self.msg_handlers.has_key(tag): self.msg_handlers[tag] = function - if core: - self.core_msg_handlers.append(tag) - else: - print 'XML Messages ' + tag + ' already has a handler' + if core: self.core_msg_handlers.append(tag) + else: print 'XML Messages ' + tag + ' already has a handler' def remove_msg_handler(self, tag): if self.msg_handlers.has_key(tag) and not tag in self.core_msg_handlers: del self.msg_handlers[tag] - else: - print 'XML Messages ' + tag + ' already deleted' - + else: print 'XML Messages ' + tag + ' already deleted' #Message Handaling def message_handler(self, arg):
--- a/orpg/networking/mplay_server.py Wed Oct 28 14:24:54 2009 -0500 +++ b/orpg/networking/mplay_server.py Thu Oct 29 20:35:28 2009 -0500 @@ -77,7 +77,8 @@ class game_group(object): - def __init__( self, id, name, pwd, desc="", boot_pwd="", minVersion="", mapFile=None, messageFile=None, persist =0 ): + def __init__(self, id, name, pwd, desc="", boot_pwd="", + minVersion="", mapFile=None, messageFile=None, persist=0): self.id = id self.name = name self.desc = desc @@ -94,16 +95,23 @@ self.mapFile = None if mapFile != None: + """ + try: + f = open(filename, "rb") + tree = parse(f) + self.xml_root = tree.getroot() + except: + f.close() + self.xml_root = None + """ self.mapFile = mapFile f = open( mapFile ) tree = f.read() f.close() - else: f = open(dir_struct["template"] + "default_map.xml") tree = f.read() f.close() - self.game_map.init_from_xml(tree) def save_map(self): @@ -116,8 +124,7 @@ self.players.append(id) def remove_player(self,id): - if self.voice.has_key(id): - del self.voice[id] + if self.voice.has_key(id): del self.voice[id] self.players.remove(id) def get_num_players(self): @@ -149,14 +156,21 @@ return 1 #depreciated - see send_group_list() - def toxml(self,act="new"): + def toxml(self, act="new"): # Please don't add the boot_pwd to the xml, as this will give it away to players watching their console - xml_data = "<group id=\"" + self.id - xml_data += "\" name=\"" + self.name - xml_data += "\" pwd=\"" + str(self.pwd!="") - xml_data += "\" players=\"" + str(self.get_num_players()) - xml_data += "\" action=\"" + act + "\" />" - return xml_data + el = Element('group') + el.set('id', self.id) + el.set('name', self.name) + el.set('pwd', str(self.pwd!="")) + el.set('players', str(self.get_num_players())) + el.set('action', act) + return tostring(el) + #xml_data = "<group id=\"" + self.id + #xml_data += "\" name=\"" + self.name + #xml_data += "\" pwd=\"" + str(self.pwd!="") + #xml_data += "\" players=\"" + str(self.get_num_players()) + #xml_data += "\" action=\"" + act + "\" />" + #return xml_data class client_stub(client_base): @@ -190,8 +204,13 @@ if diff > 1800: return 1 else: return 0 - def send(self,msg,player,group): + def send(self, msg, player, group): if self.get_status() == MPLAY_CONNECTED: + #el = Element('msg') + #el.set('to', player) + #el.set('from', '0') + #el.set('group_id', group) + #el.text(msg) self.outbox.put("<msg to='" + player + "' from='0' group_id='" + group + "' />" + msg) def change_group(self,group_id,groups): @@ -238,9 +257,9 @@ self.next_group_id = 100 self.metas = {} # This holds the registerThread objects for each meta self.be_registered = 0 # Status flag for whether we want to be registered. - self.serverName = name # Name of this server in the metas + self.serverName = name # Name of this server in the metas self.boot_pwd = "" - self.server_address = None # IP or Name of server to post to the meta. None means the meta will auto-detect it. + self.server_address = None # IP or Name of server to post to the meta. None means the meta will auto-detect it. self.defaultMessageFile = None self.userPath = dir_struct["user"] self.lobbyMapFile = "Lobby_map.xml"
--- a/orpg/networking/mplay_server_gui.py Wed Oct 28 14:24:54 2009 -0500 +++ b/orpg/networking/mplay_server_gui.py Thu Oct 29 20:35:28 2009 -0500 @@ -200,19 +200,19 @@ def add(self, player): i = self.InsertImageStringItem( 0, player["id"], 0 ) - self.SetStringItem( i, 1, self.stripHtml( player["name"] ) ) - self.SetStringItem( i, 2, "NEW" ) - self.SetStringItem( i, 3, self.roomList[0] ) - self.SetStringItem( i, 4, self.stripHtml( player["version"] ) ) - self.SetStringItem( i, 5, 'Lurker' if self.stripHtml( player["role"] ) == '' else self.stripHtml( player["role"] )) - self.SetStringItem( i, 6, self.stripHtml( player["ip"] ) ) - self.SetStringItem (i, 7, "PING" ) - self.SetItemData( i, int(player["id"]) ) + self.SetStringItem(i, 1, self.stripHtml(player["name"])) + self.SetStringItem(i, 2, "NEW") + self.SetStringItem(i, 3, self.roomList[0]) + self.SetStringItem(i, 4, self.stripHtml(player["version"])) + self.SetStringItem(i, 5, 'Lurker' if self.stripHtml(player["role"]) == '' else self.stripHtml(player["role"])) + self.SetStringItem(i, 6, self.stripHtml(player["ip"])) + self.SetStringItem(i, 7, "PING") + self.SetItemData(i, int(player["id"])) self.AutoAjust() def remove(self, id): - i = self.FindItemData( -1, int(id) ) - self.DeleteItem( i ) + i = self.FindItemData( -1, int(id)) + self.DeleteItem(i) self.AutoAjust() def AutoAjust(self): @@ -491,12 +491,12 @@ (room, room_id, player) = data self.conns.updateRoom(data) - def OnDeleteGroup( self, data ): + def OnDeleteGroup(self, data): (room_id, player) = data del self.conns.roomList[room_id] - def OnJoinGroup( self, data ): - self.conns.updateRoom( data ) + def OnJoinGroup(self, data): + self.conns.updateRoom(data ) def OnSetRole( self, data ): (id, role) = data @@ -516,7 +516,7 @@ except: pass if self.serverName == '': self.serverName = 'Server Name' - serverNameEntry = wx.TextEntryDialog( self, "Please Enter The Server Name You Wish To Use:", + serverNameEntry = wx.TextEntryDialog(self, "Please Enter The Server Name You Wish To Use:", "Server's Name", self.serverName, wx.OK|wx.CANCEL|wx.CENTRE ) if serverNameEntry.ShowModal() == wx.ID_OK: self.serverName = serverNameEntry.GetValue() # see if we already have password specified
--- a/orpg/orpg_version.py Wed Oct 28 14:24:54 2009 -0500 +++ b/orpg/orpg_version.py Thu Oct 29 20:35:28 2009 -0500 @@ -4,7 +4,7 @@ #BUILD NUMBER FORMAT: "YYMMDD-##" where ## is the incremental daily build index (if needed) DISTRO = "Traipse Alpha" DIS_VER = "Ornery Orc" -BUILD = "091028-00" +BUILD = "091029-00" # This version is for network capability. PROTOCOL_VERSION = "1.2"
--- a/orpg/tools/predTextCtrl.py Wed Oct 28 14:24:54 2009 -0500 +++ b/orpg/tools/predTextCtrl.py Thu Oct 29 20:35:28 2009 -0500 @@ -350,7 +350,33 @@ # It may be vestigal self.keyHook = keyHook # Save the keyHook passed in + ExpandoTextCtrl._wrapLine = self._wrapLine + + def _wrapLine(self, line, dc, width): + # Estimate where the control will wrap the lines and + # return the count of extra lines needed. + # Re writes ExpandoTextCtrl _wrapLine function + print 'New _wrapLine Function' + pte = dc.GetPartialTextExtents(line) + width -= wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X) + idx = 0 + start = 0 + count = 0 + spc = -1 + while idx < len(pte): + if line[idx] == ' ': spc = idx + if pte[idx] - start > width: + # we've reached the max width, add a new line + count += 1 + # did we see a space? if so restart the count at that pos + if spc != -1: + idx = spc + 1 + spc = -1 + start = pte[idx] + else: + idx += 1 + return count # findWord subroutine. #