Advertisement
Guest User

Untitled

a guest
Feb 8th, 2014
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 26.09 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. #-------------------------------------------------------------------------------
  4. # Copyright (c) 2013 Gael Honorez.
  5. # All rights reserved. This program and the accompanying materials
  6. # are made available under the terms of the GNU Public License v3.0
  7. # which accompanies this distribution, and is available at
  8. # http://www.gnu.org/licenses/gpl.html
  9. #
  10. # This program is free software: you can redistribute it and/or modify
  11. # it under the terms of the GNU General Public License as published by
  12. # the Free Software Foundation, either version 3 of the License, or
  13. # (at your option) any later version.
  14. #
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  18. # GNU General Public License for more details.
  19. #-------------------------------------------------------------------------------
  20.  
  21.  
  22. from PySide import QtCore, QtNetwork
  23. import _winreg
  24. import struct
  25. import os
  26. import miniserverlogger
  27. import shutil
  28. import re
  29. import subprocess
  30. import random
  31.  
  32. loggerInstance = miniserverlogger.instance
  33. import logging
  34.  
  35. UNIT16 = 8
  36.  
  37. class Packet():
  38.     def __init__(self, header=None , data=None, *values, **kwvalues):
  39.        
  40.         self._data = data  
  41.         self._values = kwvalues
  42.         self._header = header
  43.    
  44.     def Pack(self):
  45.  
  46.         data = ""
  47.        
  48.         headerSize = len(str(self._header))
  49.         headerField = str(self._header).replace("\t","/t").replace("\n","/n")
  50.         chunkSize = len(self._data)
  51.         headerPackStr = "<i" + str(headerSize) + "si"
  52.         data += struct.pack(headerPackStr, headerSize, headerField, chunkSize)
  53.  
  54.         for field in self._data :      
  55.             fieldType = 0 if type(field) is int else 1
  56.  
  57.             chunkPackStr = ""
  58.             fields = []
  59.             if fieldType is 1:
  60.                 fieldSize = len(field)
  61.                 chunkPackStr += "<bi" + str(fieldSize) + "s"
  62.                 fieldStr = str(field).replace("\t","/t").replace("\n","/n")
  63.                 fields.extend([fieldType, fieldSize, fieldStr])
  64.             elif fieldType is 0:
  65.                 chunkPackStr += "<bi"
  66.                 fields.extend([fieldType, field])
  67.             data += struct.pack(chunkPackStr, *fields)
  68.  
  69.         return data
  70.  
  71. class Connection(QtCore.QObject):
  72.     def __init__(self, socket, parent=None):
  73.         super(Connection, self).__init__(parent)
  74.         self.parent = parent
  75.        
  76.         self.log = logging.getLogger('miniserver')
  77.         self.log.setLevel( logging.DEBUG )
  78.         self.log.addHandler(loggerInstance.getHandler())
  79.                
  80.         self.log.debug("Incoming FA socket")
  81.         self.socket = QtNetwork.QTcpSocket(self)
  82.        
  83.         if self.socket.setSocketDescriptor(socket) == False :
  84.             self.log.debug("awful error : Socket descriptor not set")
  85.             self.socket.abort()
  86.             return
  87.  
  88.         self.props = {}
  89.  
  90.         self.socket.readyRead.connect(self.readData)
  91.         self.socket.disconnected.connect(self.disconnection)
  92.         self.socket.error.connect(self.displayError)    
  93.         self.socket.stateChanged.connect(self.stateChange)
  94.        
  95.         #self.initSupcom()
  96.         self.action = None
  97.         self.chunks = []
  98.         self.headerSizeRead = False
  99.         self.headerRead = False
  100.         self.chunkSizeRead = False
  101.         self.fieldTypeRead = False
  102.         self.fieldSizeRead = False        
  103.  
  104.  
  105.     def process(self, action, chunks):
  106.         self.log.info(action + " : " + str(chunks))
  107.         if action == 'GameState':
  108.             if chunks[0] == 'Idle':
  109.                 self.initSupcom()
  110.             elif chunks[0] == 'Lobby':
  111.                 self.hostGame()
  112.                 self.SendFaPath()
  113.                
  114.         elif action == "addProp":
  115.             self.addProp()
  116.        
  117.         elif action.lower() == "savetofile":
  118.             self.saveToFile(chunks[0], chunks[1])
  119.  
  120.         elif action.lower() == "appendtofile":
  121.             self.saveToFile(chunks[0], chunks[1], chunks[2])
  122.            
  123.         elif action.lower() == "preparetemplatefiles":
  124.             self.prepareTemplateFiles(chunks[0], chunks[1], chunks[2], chunks[3], builder=True, pattern ="'builder'")
  125.  
  126.         elif action.lower() == "savetemplatefiles":
  127.             self.saveTemplateFiles(chunks[0], chunks[1], chunks[2], builder=True, pattern ="'builder'")
  128.  
  129.         elif action.lower() == "removetemplatefiles":
  130.             self.removeTemplateFiles(chunks[0])
  131.  
  132.         elif action.lower() == "backuptemplatefiles":
  133.             self.backupTemplateFiles(chunks[0])
  134.  
  135.         elif action.lower() == "savemapfiles":
  136.             self.saveMapFiles(chunks[0], chunks[1], chunks[2], builder=True, pattern="'episodeofwar'")
  137.  
  138.         elif action.lower() == "removemapfiles":
  139.             self.removeMapFiles(chunks[0])
  140.  
  141.         elif action.lower() == "writescenariodata":
  142.             self.writeScenarioData(chunks[0], chunks[1])
  143.  
  144.         elif action.lower() == "backupscenariodata":
  145.             self.backupScenarioData(chunks[0])
  146.  
  147.         elif action.lower() == "commitscenariodata":
  148.             self.commitScenarioData(chunks[0], chunks[1])
  149.  
  150.         elif action.lower() == "writesavedata":
  151.             self.writeSaveData(chunks[0], chunks[1])
  152.  
  153.         elif action.lower() == "backupsavedata":
  154.             self.backupSaveData(chunks[0])
  155.  
  156.         elif action.lower() == "commitsavedata":
  157.             self.commitSaveData(chunks[0], chunks[1])
  158.            
  159.     def SendFaPath(self):
  160.         reply = Packet("JoinGame", [self.GetFaPath(), "FaEditor", int(100000)])
  161.         self.send(reply)
  162.                        
  163.     def prepareTemplateFiles(self, templateId, mapName, save, scenario, builder = False, pattern = None):
  164.  
  165.         faPath = self.GetFaPath()
  166.         templatePath = os.path.join(faPath, "_templates", templateId )
  167.                
  168.         if not os.path.exists(templatePath):
  169.             os.makedirs(templatePath)
  170.  
  171.         scenarioFile = os.path.join(templatePath, templateId + "_template_scenario.lua")
  172.         saveFile = os.path.join(templatePath, templateId + "_template_save.lua")
  173.         scriptFile = os.path.join(templatePath, templateId + "_template_script.lua")
  174.         origMapFile = os.path.join(faPath, "maps", mapName, mapName + ".scmap")
  175.         newMapFile = os.path.join(templatePath, templateId + ".scmap")
  176.        
  177.         file = QtCore.QFile(scenarioFile)
  178.         file.open(QtCore.QIODevice.WriteOnly)
  179.         file.write("version = 3")
  180.         file.write("\n")
  181.        
  182.         if builder and pattern != None:
  183.             rep = re.compile("type.*=.*('.+')")
  184.             match = re.search(rep, scenario)
  185.             if match:
  186.                 scenario.replace(match.group(1), pattern)
  187.        
  188.         file.write("ScenarioInfo" + " = " + scenario)
  189.         file.close()        
  190.        
  191.         file = QtCore.QFile(saveFile)
  192.         file.open(QtCore.QIODevice.WriteOnly)
  193.         file.write("Scenario" + " =" + save)
  194.         file.close()
  195.  
  196.         if not os.path.exists(scriptFile):
  197.             shutil.copy2('script.lua', scriptFile)
  198.  
  199.         if not os.path.exists(newMapFile):
  200.             shutil.copy2(origMapFile, newMapFile)
  201.  
  202.     def saveTemplateFiles(self, scenarioid, save, scenario, builder = False, pattern = None):
  203.  
  204.         faPath = self.GetFaPath()
  205.         templatePath = os.path.join(faPath, "_templates", scenarioid )
  206.         self.backupTemplateFiles(scenarioid)
  207.                
  208.         if not os.path.exists(templatePath):
  209.             os.makedirs(templatePath)
  210.  
  211.         scenarioFile = os.path.join(templatePath, scenarioid + "_template_scenario.lua")
  212.         saveFile = os.path.join(templatePath, scenarioid + "_template_save.lua")
  213.         scriptFile = os.path.join(templatePath, scenarioid + "_template_script.lua")
  214.        
  215.         file = QtCore.QFile(scenarioFile)
  216.         file.open(QtCore.QIODevice.WriteOnly)
  217.         file.write("version = 3")
  218.         file.write("\n")
  219.        
  220.         if builder and pattern != None:
  221.             rep = re.compile("type.*=.*('.+')")
  222.             match = re.search(rep, scenario)
  223.             if match:
  224.                 scenario.replace(match.group(1), pattern)
  225.        
  226.         file.write("ScenarioInfo" + " = " + scenario)
  227.         file.close()        
  228.        
  229.         file = QtCore.QFile(saveFile)
  230.         file.open(QtCore.QIODevice.WriteOnly)
  231.         file.write("Scenario" + " =" + save)
  232.         file.close()
  233.  
  234.         if not os.path.exists(scriptFile):
  235.             shutil.copy2('script.lua', scriptFile)
  236.  
  237.     def backupTemplateFiles(self, scenarioid):
  238.         faPath = self.GetFaPath()
  239.         templatePath = os.path.join(faPath, "_templates", scenarioid )
  240.         backupPath = os.path.join(faPath, "_templates", scenarioid, "backup" )
  241.                
  242.         if os.path.exists(templatePath):
  243.             if not os.path.exists(backupPath):
  244.                 os.makedirs(backupPath)
  245.  
  246.             scenarioFile = os.path.join(templatePath, scenarioid + "_template_scenario.lua")
  247.             saveFile = os.path.join(templatePath, scenarioid + "_template_save.lua")
  248.             scriptFile = os.path.join(templatePath, scenarioid + "_template_script.lua")
  249.  
  250.             backupScenarioFile = os.path.join(backupPath, scenarioid + "_backup_scenario.lua")
  251.             backupSaveFile = os.path.join(backupPath, scenarioid + "_backup_save.lua")
  252.             backupScriptFile = os.path.join(backupPath, scenarioid + "_backup_script.lua")
  253.  
  254.             shutil.copy2(scenarioFile, backupScenarioFile)
  255.             shutil.copy2(saveFile, backupSaveFile)
  256.             shutil.copy2(scriptFile, backupScriptFile)
  257.  
  258.     def removeTemplateFiles(self, scenarioid):
  259.  
  260.         faPath = self.GetFaPath()
  261.         templatePath = os.path.join(faPath, "_templates", scenarioid )
  262.        
  263.         if os.path.exists(templatePath):
  264.             shutil.rmtree(templatePath)
  265.                                                        
  266.     def saveMapFiles(self, scenarioid, save, scenario, builder = False, pattern = None):
  267.         faPath = self.GetFaPath()
  268.         templatePath = os.path.join(faPath, "_templates", scenarioid )
  269.         mapPath = os.path.join(faPath, "maps", scenarioid )
  270.                
  271.         if not os.path.exists(mapPath):
  272.             os.makedirs(mapPath)
  273.  
  274.         scenarioFile = os.path.join(mapPath, scenarioid + "_scenario.lua")
  275.         saveFile = os.path.join(mapPath, scenarioid + "_save.lua")
  276.         scriptFile = os.path.join(templatePath, scenarioid + "_template_script.lua")
  277.         newscriptFile = os.path.join(mapPath, scenarioid + "_script.lua")
  278.  
  279.         origMapFile = os.path.join(templatePath, scenarioid + ".scmap")
  280.         newMapFile = os.path.join(mapPath, scenarioid + ".scmap")
  281.        
  282.         file = QtCore.QFile(scenarioFile)
  283.         file.open(QtCore.QIODevice.WriteOnly)
  284.         file.write("version = 3")
  285.         file.write("\n")
  286.        
  287.         if builder and pattern != None:
  288.             rep = re.compile("type.*=.*('.+')")
  289.             match = re.search(rep, scenario)
  290.             if match:
  291.                 scenario.replace(match.group(1), pattern)
  292.        
  293.         file.write("ScenarioInfo" + " = " + scenario)
  294.         file.close()        
  295.        
  296.         file = QtCore.QFile(saveFile)
  297.         file.open(QtCore.QIODevice.WriteOnly)
  298.         file.write("Scenario" + " = " + save)
  299.         file.close()
  300.  
  301.         shutil.copy2(scriptFile, newscriptFile)
  302.  
  303.         if not os.path.exists(newMapFile):
  304.             shutil.copy2(origMapFile, newMapFile)
  305.  
  306.     def removeMapFiles(self, scenarioid):
  307.  
  308.         faPath = self.GetFaPath()
  309.         mapPath = os.path.join(faPath, "maps", scenarioid )
  310.        
  311.         if os.path.exists(mapPath):
  312.             shutil.rmtree(mapPath)
  313.  
  314.     def writeScenarioData(self, scenarioid, text):
  315.  
  316.         faPath = self.GetFaPath()
  317.         templatePath = os.path.join(faPath, "_templates", scenarioid )
  318.         scenarioFile = os.path.join(templatePath, scenarioid + "_template_scenario.lua")
  319.         self.backupScenarioData(scenarioid)
  320.                
  321.         if not os.path.exists(templatePath):
  322.             os.makedirs(templatePath)
  323.            
  324.         file = QtCore.QFile(scenarioFile)
  325.         file.open(QtCore.QIODevice.WriteOnly)
  326.         file.write("ScenarioInfo" + " = " + text)
  327.         file.write("\n")
  328.         file.write("version = 3")
  329.         file.close()
  330.  
  331.     def backupScenarioData(self, scenarioid):
  332.  
  333.         faPath = self.GetFaPath()
  334.         templatePath = os.path.join(faPath, "_templates", scenarioid )
  335.         backupPath = os.path.join(faPath, "_templates", scenarioid, "backup" )
  336.                
  337.         if os.path.exists(templatePath):
  338.             if not os.path.exists(backupPath):
  339.                 os.makedirs(backupPath)
  340.  
  341.             scenarioFile = os.path.join(templatePath, scenarioid + "_template_scenario.lua")
  342.             backupScenarioFile = os.path.join(backupPath, scenarioid + "_backup_scenario.lua")
  343.             shutil.copy2(scenarioFile, backupScenarioFile)
  344.  
  345.     def commitScenarioData(self, scenarioid, text):
  346.  
  347.         faPath = self.GetFaPath()
  348.         mapPath = os.path.join(faPath, "maps", scenarioid )
  349.         scenarioFile = os.path.join(mapPath, scenarioid + "_scenario.lua")
  350.                
  351.         if os.path.exists(mapPath):    
  352.             file = QtCore.QFile(scenarioFile)
  353.             file.open(QtCore.QIODevice.WriteOnly)
  354.             file.write("ScenarioInfo" + " = " + text)
  355.             file.write("\n")
  356.             file.write("version = 3")
  357.             file.close()
  358.  
  359.     def writeSaveData(self, scenarioid, text):
  360.  
  361.         faPath = self.GetFaPath()
  362.         templatePath = os.path.join(faPath, "_templates", scenarioid )
  363.         saveFile = os.path.join(templatePath, scenarioid + "_template_save.lua")
  364.         self.backupSaveData(scenarioid)
  365.                
  366.         if not os.path.exists(templatePath):
  367.             os.makedirs(templatePath)
  368.            
  369.         file = QtCore.QFile(saveFile)
  370.         file.open(QtCore.QIODevice.WriteOnly)
  371.         file.write("Scenario" + " = " + text)
  372.         file.close()
  373.  
  374.     def backupSaveData(self, scenarioid):
  375.  
  376.         faPath = self.GetFaPath()
  377.         templatePath = os.path.join(faPath, "_templates", scenarioid )
  378.         backupPath = os.path.join(faPath, "_templates", scenarioid, "backup" )
  379.                
  380.         if os.path.exists(templatePath):
  381.             if not os.path.exists(backupPath):
  382.                 os.makedirs(backupPath)
  383.  
  384.             saveFile = os.path.join(templatePath, scenarioid + "_template_save.lua")
  385.             backupSaveFile = os.path.join(backupPath, scenarioid + "_backup_save.lua")
  386.             shutil.copy2(saveFile, backupSaveFile)
  387.  
  388.     def commitSaveData(self, scenarioid, text):
  389.  
  390.         faPath = self.GetFaPath()
  391.         mapPath = os.path.join(faPath, "maps", scenarioid )
  392.         saveFile = os.path.join(mapPath, scenarioid + "_save.lua")
  393.                
  394.         if os.path.exists(mapPath):            
  395.             file = QtCore.QFile(saveFile)
  396.             file.open(QtCore.QIODevice.WriteOnly)
  397.             file.write("Scenario" + " = " + text)
  398.             file.close()
  399.            
  400.     def saveToFile(self, f, text):
  401.         if not os.path.exists(os.path.dirname(f)):
  402.             os.makedirs(os.path.dirname(f))
  403.            
  404.         file = QtCore.QFile(f)
  405.         file.open(QtCore.QIODevice.WriteOnly)
  406.         file.write(text)
  407.         file.close()
  408.  
  409.     def appendToFile(self, f, tableName, text):
  410.         if not os.path.exists(os.path.dirname(f)):
  411.             os.makedirs(os.path.dirname(f))    
  412.                
  413.         file = QtCore.QFile(f)
  414.         file.open(QtCore.QIODevice.Append)
  415.         file.write(tableName + " =" + text)
  416.         file.close()
  417.    
  418.     def addProp(self, chuncks):
  419.         what = chuncks[0]
  420.         x = int(chuncks[1])
  421.         y = int(chuncks[2])
  422.        
  423.         self.props[what] = [x,y]
  424.    
  425.     def initSupcom(self):
  426.         reply = Packet("CreateLobby", [0, 0, "Campaign Editor", 0, 1])
  427.         self.send(reply)
  428.    
  429.     def hostGame(self):
  430.         reply = Packet("HostGame", ["SCMP_007"])
  431.         self.send(reply)
  432.  
  433.     def stateChange(self, socketState):
  434.         if socketState != QtNetwork.QAbstractSocket.ClosingState :
  435.             self.log.debug("socket about to close")
  436.         elif socketState != QtNetwork.QAbstractSocket.UnconnectedState :
  437.             self.log.debug("socket not connected")
  438.        
  439.         if socketState != QtNetwork.QAbstractSocket.ConnectedState :
  440.             self.log.debug("not connected")
  441.             self.socket.abort()
  442.  
  443.     def displayError(self, socketError):
  444.         if socketError == QtNetwork.QAbstractSocket.RemoteHostClosedError:
  445.             self.log.warning("RemoteHostClosedError")
  446.      
  447.  
  448.         elif socketError == QtNetwork.QAbstractSocket.HostNotFoundError:
  449.             self.log.warning("HostNotFoundError")
  450.         elif socketError == QtNetwork.QAbstractSocket.ConnectionRefusedError:
  451.             self.log.warning("ConnectionRefusedError")
  452.         else:
  453.             self.log.warning("The following Error occurred: %s." % self.socket.errorString())
  454.  
  455.     def readData(self):
  456.         self.log.info("reading socket from FA")
  457.         if self.socket.bytesAvailable() == 0 :
  458.             self.log.info("data reception read done - too or not enough data")
  459.             return
  460.        
  461.         ins = QtCore.QDataStream(self.socket)
  462.         ins.setByteOrder(QtCore.QDataStream.LittleEndian)  
  463.  
  464.         while ins.atEnd() == False :
  465.             if self.socket.isValid() :
  466.                 if self.headerSizeRead == False :
  467.                     if self.socket.bytesAvailable() < 4:
  468.                         return
  469.                
  470.                     self.blockSize = ins.readUInt32()
  471.                     self.headerSizeRead = True
  472.                    
  473.                 if self.headerRead == False :
  474.                
  475.                     if self.socket.bytesAvailable() < self.blockSize :
  476.                         return
  477.                
  478.                     self.action = ins.readRawData(self.blockSize)
  479.                     self.headerRead = True
  480.                    
  481.                 if self.chunkSizeRead == False :
  482.                     if self.socket.bytesAvailable() < 4:
  483.                         return
  484.                
  485.                     self.chunkSize = ins.readInt32()
  486.                     self.chunks = []
  487.                     self.chunkSizeRead = True
  488.                
  489.                 if self.chunkSize > 100 :
  490.                     self.__logger.info("Big error reading FA datas !")
  491.                     self.socket.readAll()
  492.                     self.fieldSize = 0
  493.                     self.blockSize = 0
  494.                     self.chunkSize = 0  
  495.                     self.noSocket = True                        
  496.                     return
  497.                
  498.                 for _ in range(len(self.chunks), self.chunkSize):
  499.                     if self.fieldTypeRead == False :
  500.                         if self.socket.bytesAvailable() < 1 :
  501.                             return
  502.                                
  503.                         self.fieldType = ins.readBool()
  504.                         self.fieldTypeRead = True
  505.                    
  506.                     if not self.fieldType :
  507.                      
  508.                         if self.socket.bytesAvailable() < 4 :
  509.                             return
  510.                         number = ins.readInt32()
  511.                         self.chunks.append(number)
  512.                         self.fieldTypeRead = False        
  513.  
  514.                     else :
  515.                         if self.fieldSizeRead == False :      
  516.                             if self.socket.bytesAvailable() < 4 :
  517.                                 return  
  518.                              
  519.                             self.fieldSize =  ins.readInt32()
  520.                             self.fieldSizeRead = True
  521.                
  522.                         if self.socket.bytesAvailable() < self.fieldSize :
  523.                             return
  524.  
  525.                         datastring = ins.readRawData(self.fieldSize)
  526.                         fixedStr = datastring.replace("/t","\t").replace("/n","\n")
  527.                         self.chunks.append(fixedStr)              
  528.                         self.fieldTypeRead = False
  529.                         self.fieldSizeRead = False  
  530.      
  531.                 self.process(self.action, self.chunks)
  532.                 self.action = None
  533.                 self.chunks = []
  534.                 self.headerSizeRead = False
  535.                 self.headerRead = False
  536.                 self.chunkSizeRead = False
  537.                 self.fieldTypeRead = False
  538.                 self.fieldSizeRead = False
  539.  
  540.  
  541.     def send(self, reply):
  542.         self.socket.write(reply.Pack())
  543.    
  544.     def disconnection(self):
  545.         self.parent.removeConnection(self)
  546.  
  547.     def GetFaPath(self):    
  548.         '''
  549.        Retrieves the Path as configured in the settings
  550.        '''
  551.         settings = QtCore.QSettings("ForgedAllianceForever", "FA Lobby")
  552.         settings.beginGroup("ForgedAlliance")
  553.         path = unicode(settings.value("app/path"))
  554.         settings.endGroup()
  555.         return path
  556.        
  557. class start(QtNetwork.QTcpServer):
  558.  
  559.     def __init__(self, parent=None):
  560.  
  561.         super(start, self).__init__(parent)
  562.  
  563.         self.log = logging.getLogger('miniserver.main')
  564.         self.log.setLevel( logging.DEBUG )
  565.         self.log.addHandler(loggerInstance.getHandler())
  566.         self.connections = []
  567.  
  568.         FaPath = self.SetFaPath()
  569.  
  570.         if not FaPath:
  571.             self.log.info("Forged Alliance path could not be found")
  572.             raise Exception("Forged Alliance path could not be found")
  573.  
  574.         self.log.info("Forged Alliance Path Found.")
  575.         print "Forged Alliance Path Found."
  576.  
  577.         if not self.listen(QtNetwork.QHostAddress.LocalHost, 1234):
  578.             self.log.error ("Unable to start the server on port 1234")
  579.             raise Exception("Unable to start the mini server on port 1234")
  580.  
  581.         print "Server started on port " + str(self.serverPort())
  582.         self.log.info("starting the server on port " + str(self.serverPort()))
  583.  
  584.         FaExePath = os.path.join(FaPath, "bin" , "forgedalliance.exe")
  585.        # if os.path.isfile(FaExePath):
  586.           #  subprocess.call([FaExePath, " -debug /enablediskwatch /purgecache /window 1024 768 /campaignbuilder /showlog /gpgnet 127.0.0.1:1234"])
  587.            
  588.     def incomingConnection(self, socketId):
  589.         print "Forged Allaince Connection Established"
  590.         self.log.debug("Forged Allaince Connection Established")
  591.         self.connections.append(Connection(socketId, self))    
  592.        
  593.     def removeConnection(self, connection):
  594.         if connection in self.connections:
  595.             self.connections.remove(connection)
  596.             connection.deleteLater()
  597.  
  598.     def SetFaPath(self):
  599.         for path in self.mostProbablePaths():
  600.             if self.validatePath(path):
  601.                 self.setPathInSettings(path)
  602.                 return path
  603.        
  604.         return None
  605.  
  606.     def mostProbablePaths(self):
  607.         '''
  608.        Returns a list of the most probable paths where Supreme Commander: Forged Alliance might be installed
  609.        '''
  610.         pathlist = []
  611.        
  612.         #Retail path
  613.         pathlist.append(os.path.expandvars("%ProgramFiles%\\THQ\\Gas Powered Games\\Supreme Commander - Forged Alliance"))
  614.  
  615.         #Direct2Drive Paths
  616.         #... allegedly identical to impulse paths - need to confirm this
  617.  
  618.         #Impulse/GameStop Paths - might need confirmation yet
  619.         pathlist.append(os.path.expandvars("%ProgramFiles%\\Supreme Commander - Forged Alliance"))
  620.        
  621.         #Steam path  
  622.         pathlist.append(os.path.expandvars("%ProgramFiles%\\Steam\\steamapps\\common\\supreme commander forged alliance"))
  623.  
  624.         #Construe path from registry traces - this is not a very safe method, but it seems to work for plain installs
  625.         try :
  626.             regkey = "SOFTWARE\\Classes\\SCFAReplayType\\Shell\\Open\\Command"
  627.             key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, regkey)
  628.             path = _winreg.QueryValue(key, "")
  629.             if "ForgedAlliance.exe" in path:            
  630.                 path = path[:path.rfind("bin")]
  631.                 path = path.rstrip('"/\\')
  632.                 pathlist.append(os.path.expandvars(path))    
  633.         except :
  634.             pass
  635.        
  636.         return pathlist
  637.    
  638.     def validatePath(self, path):
  639.         try:
  640.             # Supcom only supports Ascii Paths
  641.             if not path.decode("ascii"): return False
  642.            
  643.             #We check whether the base path and a gamedata/lua.scd file exists. This is a mildly naive check, but should suffice
  644.             if not os.path.isdir(path): return False  
  645.             if not os.path.isfile(os.path.join(path, r'gamedata', r'lua.scd')): return False
  646.            
  647.             #Reject or fix paths that end with a slash.
  648.             #LATER: this can have all sorts of intelligent logic added
  649.             #Suggested: Check if the files are actually the right ones, if not, tell the user what's wrong with them.
  650.             if path.endswith("/"): return False
  651.             if path.endswith("\\"): return False
  652.        
  653.             return True
  654.         except:
  655.             _, value, _ = sys.exc_info()
  656.             logger.error(u"Path validation failed: " + unicode(value))
  657.             return False
  658.        
  659.     def setPathInSettings(self, path):
  660.         '''
  661.        Stores the new path for Forged Alliance in the app settings
  662.        '''
  663.         settings = QtCore.QSettings("ForgedAllianceEditor", "FA Editor")
  664.         settings.beginGroup("ForgedAllianceEditor")
  665.         settings.setValue("app/path", path)
  666.         settings.endGroup()
  667.         settings.sync()
  668.  
  669.  
  670.     def getPathFromSettings(self):    
  671.         '''
  672.        Retrieves the Path as configured in the settings
  673.        '''
  674.         settings = QtCore.QSettings("ForgedAllianceEditor", "FA Editor")
  675.         settings.beginGroup("ForgedAllianceEditor")
  676.         path = unicode(settings.value("app/path"))
  677.         settings.endGroup()
  678.         return path
  679.            
  680. if __name__ == '__main__':
  681.     import sys
  682.    
  683.     app = QtCore.QCoreApplication(sys.argv)
  684.     server = start()
  685.     app.exec_()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement