def doLogin(self): try: if self.serverData.currentTime.hour == 3 and self.serverData.currentTime.minute == 0: # don't connect immediately after 3am server reset mySleep(30) except TypeError: pass # the first time is normal not to have the server time url = '.'.join(self.config.webpage.split('.')[1:]) page = self._fetchValidResponse("http://" + url) form = ParseFile(page.stringio, page.url, backwards_compat=False)[0] form["uni_url"] = [self.config.webpage] form["login"] = self.config.username form["pass"] = self.config.password form.action = "http://"+self.config.webpage+"/game/reg/login2.php" page = self._fetchValidResponse(form.click()) try: self.session = re.findall("[0-9A-Fa-f]{12}", page.text)[0] self.saveState () except IndexError: raise BotFatalError(page) self._eventMgr.loggedIn(self.config.username, self.session) self._fetchPhp('index.php', lgn=1) mySleep(5) page = self._fetchPhp('index.php', page='overview', lgn=1)
def get_forms(self, predicate=None): """Returns all the forms satisfying predicate.""" try: forms = ParseFile(StringIO(self.page), self.url, backwards_compat=False) except ParseError: forms = ParseFile(StringIO(self.page), self.url, backwards_compat=False, \ form_parser_class=XHTMLCompatibleFormParser) return (f for f in forms if predicate is None or predicate(f))
def get_forms(self): return ParseFile(io.StringIO( str(BeautifulSoup(self.body, 'lxml')).replace('<br/>', '').replace('<hr/>', '')), self.current_url, backwards_compat=False)
def decode_stream(self, file_data): try: form = ParseFile(StringIO.StringIO(gsa_form_str % (self.ip, self.port)), base_uri='http://%s:%s' % (self.ip, self.port))[0] form.add_file(StringIO.StringIO(file_data), name='file') self.lr.load(form.click(), is_xpath=False) result = '' gsa_result = self.lr.body if gsa_result.find('<span id="captcha_result">') > -1: result = gsa_result.split( '<span id="captcha_result">')[1].split('</span>')[0] return result except: raise
def get_forms_by_url(self, url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, isdecode=False, repeat=3, is_xpath=False): try: if timeout is socket._GLOBAL_DEFAULT_TIMEOUT: timeout = self._timeout response = None response = self.open(url, data, timeout, isdecode, repeat, is_xpath) return ParseFile(io.StringIO(str(BeautifulSoup(self.body, 'lxml')).replace('<br/>', '').replace('<hr/>', '')), response.geturl(), backwards_compat=False) except: raise finally: if response: del response
def submit(self, page, data={}, headers={}, name=None, action=None, kwargs={}): forms = ParseFile(StringIO(page), self.resp.geturl(), backwards_compat=False) form = self.get_form(forms, name) if form == None: return None for k, v in data.items(): try: item = form.find_control(k) except ControlNotFoundError: form.new_control('text', k, {'value': v}) continue if isinstance(item, ListControl) and not isinstance(v, (list, tuple)): v = [v] try: item.value = v except AttributeError: if item.readonly: item.readonly = False if item.disabled: item.disabled = False item.value = v if action: if callable(action): form.action = action(form.action) else: form.action = action req = form.click(**kwargs) self.get_headers(headers, req) return self.get_page(req)
def launchMission(self, mission, abortIfNotEnough = True, fleetSlotsToReserve = 0): while True: # assure cuantities are integers for shipType, quantity in mission.fleet.items(): mission.fleet[shipType] = int(quantity) # 1st step: select fleet page = self._fetchPhp('index.php', page='fleet1') # TODO: management of various planets cp=mission.sourcePlanet.code) freeFleetSlots = self.getFreeFleetSlots(page) availableFleet = self.getAvailableFleet(page) form = ParseFile(page.stringio, page.url, backwards_compat=False)[-1] for shipType, requested in mission.fleet.iteritems(): available = availableFleet.get(shipType, 0) if available == 0 or (abortIfNotEnough and available < requested): raise NotEnoughShipsError(mission.sourcePlanet.fleet, {shipType:requested}, available) shipCode = INGAME_TYPES_BY_NAME[shipType].code form["am" + str(shipCode)] = str(requested) if freeFleetSlots <= int(fleetSlotsToReserve): raise NoFreeSlotsError() mySleep(3) # 2nd step: select destination and speed page = self._fetchValidResponse(form.click()) forms = ParseFile(page.stringio, page.url, backwards_compat=False) if not forms or 'fleet3' not in forms[0].action: continue # unkown error, retry form = forms[0] destCoords = mission.targetPlanet.coords form['galaxy'] = str(destCoords.galaxy) form['system'] = str(destCoords.solarSystem) form['position'] = str(destCoords.planet) form.find_control('type').readonly = False form['type'] = str(destCoords.coordsType) form['speed'] = [str(mission.speedPercentage / 10)] mySleep(3) # 3rd step: select mission and resources to carry page = self._fetchValidResponse(form.click()) form = ParseFile(page.stringio, page.url, backwards_compat=False)[0] if not forms or 'fleet3' not in forms[0].action: continue # unkown error, retry try: form.find_control('mission').readonly = False form['mission'] = str(mission.missionType) except ControlNotFoundError: continue resources = mission.resources form['resource1'] = str(resources.metal) form['resource2'] = str(resources.crystal) form['resource3'] = str(resources.deuterium) hours, mins, secs = re.findall("(\d+):(\d+):(\d+)", page.etree.xpath("string(//*[@id='duration'])"))[0] flightTime = timedelta(0, int(secs), 0, 0, int(mins), int(hours)) mySleep(3) # 4th and final step: check result page = self._fetchValidResponse(form.click()) if self.translations['fleetCouldNotBeSent'] in page.text: continue # unexpected error, retry errors = self.REGEXPS['fleetSendError'].findall(page.text) if len(errors) > 0 or 'class="success"' not in page.text: errors = str(errors) if self.translations['fleetLimitReached'] in errors: raise NoFreeSlotsError() elif self.translations['noShipSelected'] in errors: raise NotEnoughShipsError(availableFleet, mission.fleet) else: raise FleetSendError(errors) mission.launched(self.serverData.currentTime, flightTime) # check the requested fleet was sent intact: # sentFleet = {} # for fullName, value in resultPage.items(): # name = self.translationsByLocalText.get(fullName) # if name is None: # continue # if name in INGAME_TYPES_BY_NAME.keys(): # sentFleet[name] = int(value.replace('.', '')) # if mission.fleet != sentFleet: # warnings.warn("Not all requested fleet was sent. Requested: %s. Sent: %s" % (mission.fleet, sentFleet)) # mission.fleet = sentFleet break