def __init__(self, file_paths, platform): """ ActionHandler constructor. Create the main window, setup the message handler, import the preferences, and connect all of the action handlers. Finally, enter the gtk main loop and block. @param file_paths a list of flow graph file passed from command line @param platform platform module """ self.clipboard = None for action in Actions.get_all_actions(): action.connect('activate', self._handle_action) #setup the main window self.main_window = MainWindow(platform) self.main_window.connect('delete-event', self._quit) self.main_window.connect('key-press-event', self._handle_key_press) self.get_page = self.main_window.get_page self.get_flow_graph = self.main_window.get_flow_graph self.get_focus_flag = self.main_window.get_focus_flag #setup the messages Messages.register_messenger(self.main_window.add_report_line) Messages.send_init(platform) #initialize self.init_file_paths = file_paths Actions.APPLICATION_INITIALIZE() #enter the mainloop gtk.main()
def handle_user_gui(app, action, args): # FOR GUI. Handles basic user input # calling for other functions to complete the input # and make commands. msg.display_user_instructions() if action == "search sport": return hdlr.handle_search_sport_gui(app, args) elif action == "search sports in location": return hdlr.handle_search_sports_in_location_gui(app, args) elif action == "search sports in region": return hdlr.handle_search_sports_in_region_gui(app, args) elif action == "search sports in country": return hdlr.handle_search_sports_in_country_gui(app, args) elif action == "search sports in zone": return hdlr.handle_search_sports_in_zone_gui(app, args) elif action == "display locations": return hdlr.handle_display_locations_gui(app, args) elif action == "display regions": return hdlr.handle_display_regions_gui(app, args) elif action == "display countries": return hdlr.handle_display_countries_gui(app, args) elif action == "display zones": return hdlr.handle_display_zones_gui(app, args) elif action == "instructions": return hdlr.handle_display_user_instructions() elif action == "quit": return
def run(self): while True: _cpu, _mem, _disk = monitoring_resource() _cpu = 50.0 _mem = 45.1 #_disk = 66.3 if Config.DELTA_SHARED != 0: self.delta = Config.DELTA_SHARED Config.DELTA_SHARED = 0 elif Config.E_SHARED != 0: self.e = Config.E_SHARED Config.E_SHARED = 0 self.delta = [0, 0, 0] self.calculate_u([_cpu, _mem, _disk]) Config.U_SHARED = self.u Config.V_SHARED = self.v print("Node with reporting u: " + str(self.u)) functionValue = Config.monitoringFunction(self.coeff, self.u) if functionValue > self.threshold: self.last_mode = "scale_up" print( "Found a local violation on the monitored resources - SCALE UP" ) try: #move arduino to another position client = MQTTClient(Config.MQTT_IP, Config.MQTT_CLIENT_NAME) client.connect() client.publish(Config.MQTT_TOPIC, Config.MQTT_MESSAGE) client.disconnect() except: print("Error to connect to MQTT broker") response = Messages.send( "scale_up", v=self.v, u=self.u, coeff=self.coeff) #communication to cloud try: self.e = response["e"] self.delta = [0, 0, 0] print("New estimation from coordinator - e:" + str(self.e)) except KeyError: self.delta = response['delta'] print("New estimation from coordinator - delta:" + str(self.delta)) except TypeError: print("No node available") self.vLast = self.v elif functionValue < (-self.threshold): if self.last_mode == "scale_down": print( "Under the threshold but cannot scale down because not in cluster" ) else: self.last_mode = "scale_down" print( "Found a local violation on the monitored resources - SCALE DOWN" ) Messages.send_noresp("scale_down", v=self.v, u=self.u) self.vLast = self.v self.last_mode = "scale_down" time.sleep(Config.MONITORING_TIMEFRAME)
def _gotShortHandshake(self, connId, connSet): success = False data = ''.join(connSet['inBuffer']) connSet['inBuffer'] = [data] #decode handshake length, proto, reserved, infohash = Messages.decodeShortHandshake(data) if not proto.lower()=='bittorrent protocol': #invalid handshake, close conn self._closeConn(connId, 'received invalid handshake') elif not infohash in self.torrents: #invalid handshake, close conn self._closeConn(connId, 'received handshake with unknown infohash') else: #valid handshake connSet['torrentIdent'] = self.torrents[infohash] if self.peerPool.establishedConnection(connSet['torrentIdent'], connSet['sock'].getpeername()): #no connection to this address exists up to now success = True connSet['added'] = True self.log.info("Conn %d: Got valid handshake, sending response", connId) connSet['sock'].send(Messages.generateHandshake(infohash, self.peerId)) else: #we already have a connection to this address self._closeConn(connId, 'we already have a connection to this address') return success
def build(self, building): '''pokial sa jedna o pole da upgradovat najnizsi lvl jeho typu, pokial je uz budova postavena, da ju upgradovat, ked nie da ju stavat. ''' if any(building == x for x in self.resources().keys()): id = self.get_id_of_lowest_res_lvl(building) self.upgrade(id) elif self.is_building_built(building) != -1: id = self.get_building_id(building) self.upgrade(id) else: id = self.get_free_building_place_id() soup = self.get_soup(self.build_url + id + '&category=' + self.get_building_category(id, building)) divs = soup.findAll('div', {'class': 'buildingWrapper'}) for i in range(len(divs)): if divs[i].find('h2').string == building: index = i break button_link = divs[index].find( 'button', {'class': 'green new'})['onclick'].split("'")[1] self.session.post(self.url[:-9] + button_link) id = self.get_building_id(building) if self.debug: Messages.building(building, id, self.get_building_lvl(building, id=id))
def warn_user(event, session_api, chat_id, msg_command, dict_of_users): if Connector.isAdmin(chat_id, event.object.message['from_id']): getConversationMembers(session_api, event, dict_of_users) # check forward messages if len(event.object.message['fwd_messages']) != 0: for temp in event.object.message['fwd_messages']: Messages.send_message( session_api, chat_id, 'User with id: \'' + str(int(temp['from_id'])) + '\' warned successful!') Connector.db_warn(chat_id, int(temp['from_id'])) # check id in msg_command try: msg_ids = msg_command.split()[1:] for user_idd in msg_ids: user_id = (str(user_idd[3:]).split('|'))[0] if int(user_id) in dict_of_users.keys(): Messages.send_message( session_api, chat_id, 'User with id: \'' + str(user_id) + '\' warned successful!') Connector.db_warn(chat_id, int(user_id)) else: Messages.send_message( session_api, chat_id, 'User with id: \'' + str(user_id) + '\' is not in chat!') except ValueError: Messages.send_message(session_api, chat_id, 'Id is incorrect!') else: Messages.send_message(session_api, chat_id, 'Permission denied! You is not admin!')
def OnModify(self, event): if self.selected == None: Messages.messageError('No se ha seleccionado ningun servidor', 'Modificar configuracion') else: NewConfigurationWindow.showModifWindow(self) event.Skip()
def generate_next_request(self): while True: #Ask the Requests Manager for new Blocks to request piece_index, block_index = self.torrent.requester.getNextBlock( self) if block_index < 0 or len( self.set_of_blocks_requested) >= MAX_REQUEST_TO_PEER: if self.torrent.fileManager.StreamCompleted == True: # Launch Finishing Sequences reactor.stop() else: break block_byte_offset = block_index * BLOCK_SIZE #Add this to the set of blocks requested. self.set_of_blocks_requested.add((piece_index, block_index)) self.transport.write( str( Messages.Request( index=Messages.number_to_bytes(piece_index), begin=Messages.number_to_bytes(block_byte_offset), length=Messages.number_to_bytes(BLOCK_SIZE)))) self.torrent.requester.requestSuccessful(self, piece_index, block_index) #Add timeout for requests. Logger.info("Sending Request For Piece :" + str(piece_index) + ", " + str(block_index) + " to " + str(self.ip)) reactor.callLater(TIMEOUT, self.checkTimeout, piece_index, block_index)
def answer_request(self, piece_index, begin, length): data = "" remaining_length = length while (remaining_length > 0): block_index = int(begin / BLOCK_SIZE) if (self.torrent.fileManager.blockExists( piece_index, block_index)): #block_exists indicates if block is present if (remaining_length >= BLOCK_SIZE): data = self.torrent.fileManager.readBlock( piece_index, block_index)[ begin % BLOCK_SIZE:] #readBlock returns the data block begin = math.ceil(begin / BLOCK_SIZE) * ConstantsBLOCK_SIZE remaining_length -= BLOCK_SIZE - begin % BLOCK_SIZE else: data = self.torrent.fileManager.readBlock( piece_index, block_index)[begin % BLOCK_SIZE:remaining_length] remaining_length = 0 self.transport.write( str( Messages.Piece( index=Messages.number_to_bytes(piece_index), begin=Messages.number_to_bytes(begin), block=data))) #send corresponding data block if (begin == self.torrent.fileManager.get_piece_length( piece_index) ): #get piece length for corresponding piece index piece_index += 1 begin = 0
def handle_add_region(app, db_file): msg.display_add_region_instructions() region = input("region: ") country = input("country: ") zone = input("zone: ") app.add_region(clss.Region(region), country, zone) db_file.write("\nadd region " + region + " " + country + " " + zone)
def requestChatMessages(self, chat_id): chat = self.getChat(chat_id) c.log( 'info', 'Requesting chat messages for chat %s "%s"' % (chat_id, chat['data']['title'])) Messages.requestMessages({'chat_id': chat_id}, self.data[chat_id])
def handle_add_location(app, db_file): msg.display_add_location_instructions() location = input("location: ") region = input("region: ") country = input("country: ") zone = input("zone: ") app.add_location(clss.Location(location), region, country, zone) db_file.write("\nadd location " + location + " " + region + " " + country + " " + zone)
def get_addr(self): message = Messages.get_addr() self.socket.send(message) print("Wiadomość getaddr wysłana\nOczekuje na odpowiedź...\n") addr_list: List[Tuple[str, int]] = Messages.receive_addr(self.socket) for addr in addr_list: print("Adres: " + str(addr[0]) + " port:" + str(addr[1]))
def OnExecute(self, event): ix = self.choice.GetCurrentSelection() if ix < 0: Messages.messageError('Select a SAP Server', 'Execute ABAP Code') else: result = sap.executeCode(self.servers[ix], self.parent.code) self.parent.outtext.SetValue(result)
def OnTestConfig(self, event): message = Utils.setParams(self) if message != None: Messages.messageError(message, 'Probar') else: if sap.testServerConfig(*self.params): Messages.messageInformation('La configuracion es correcta, ahora puede guardar', 'Probar configuracion') event.Skip()
def OnExecute(self, event): ix = self.choice.GetCurrentSelection() if ix < 0: Messages.messageError('Select a SAP Server', 'Execute ABAP Code') else: result = sap.executeCode(self.servers[ix], self.parent.code ) self.parent.outtext.SetValue(result)
def random_band(session_api, chat_id, msg_command): try: min = int(str(msg_command).split(' ')[1]) max = int(str(msg_command).split(' ')[2]) result = random.randint(min, max) Messages.send_message(session_api, chat_id, 'Your random generated number is ' + str(result)) except ValueError: Messages.send_message(session_api, chat_id, 'Input incorrect!')
def cancelRequestFor(self,piece_index,block_index): if((piece_index,block_index) in self.set_of_blocks_requested): self.set_of_blocks_requested.remove((piece_index,block_index)) begin = block_index*BLOCK_SIZE piece_index = Messages.number_to_bytes(piece_index) begin = Messages.number_to_bytes(block_index) length = Messages.number_to_bytes(BLOCK_SIZE) self.transport.write(str(Messages.Cancel(index = piece_index, begin = begin, length = length)))
def kick(self, bot, game): try: Messages.send_message(bot, self.real_id, Messages.YOU_LOSE) Messages.send_message(bot, game.group_id, "بازیکن " + self.first_name + " از بازی حذف شد") bot.restrict_chat_member(chat_id=game.group_id, user_id=self.real_id, permissions=telegram.ChatPermissions(can_send_messages=False)) # bot.kick_chat_member(game.group_id, self.real_id) except Exception as e: print(e)
def OnDelete(self, event): if self.selected == None: Messages.messageError('No se ha seleccionado ningun servidor', 'Eliminar configuracion') else: ret = Messages.messageChoice('Realmente desea eliminar la configuracion?', 'Eliminar configuracion') if ret == wx.ID_YES: if db.deleteConfig(self.sel_text): self.list.DeleteItem(self.selected) event.Skip()
def kickfrom_user(event, session_api, chat_id, msg_command): if Connector.isAdmin(chat_id, event.object.message['from_id']): try: time = msg_command.split(' ')[1] Connector.db_kickfrom(chat_id, time) except ValueError: Messages.send_message(session_api, chat_id, 'Date is incorrect!') else: Messages.send_message(session_api, chat_id, 'Permission denied! You is not admin!')
def OnTestConfig(self, event): message = Utils.setParams(self) if message != None: Messages.messageError(message, 'Probar') else: if sap.testServerConfig(*self.params): Messages.messageInformation( 'La configuracion es correcta, ahora puede guardar', 'Probar configuracion') event.Skip()
def cancelRequestFor(self, piece_index, block_index): if ((piece_index, block_index) in self.set_of_blocks_requested): self.set_of_blocks_requested.remove((piece_index, block_index)) begin = block_index * BLOCK_SIZE piece_index = Messages.number_to_bytes(piece_index) begin = Messages.number_to_bytes(block_index) length = Messages.number_to_bytes(BLOCK_SIZE) self.transport.write( str(Messages.Cancel(index=piece_index, begin=begin, length=length)))
def _setLocalChoke(self, value): if value == True and self.localChoke == False: # choking self._delAllOutRequests() self._queueSend(Messages.generateChoke()) self.localChoke = value elif value == False and self.localChoke == True: self._queueSend(Messages.generateUnChoke()) self.localChoke = value
def _setLocalInterest(self, value): if value == False and self.localInterest == True: # changing to negative, we were interested before assert self._amountOfInRequests() == 0, "Local Requests are running and we are not interested?" # self._cancelAllInRequests() self._queueSend(Messages.generateNotInterested()) self.localInterest = value elif value == True and self.localInterest == False: self._queueSend(Messages.generateInterested()) self.localInterest = value
def broadcast(session_api, chat_id, msg_command, event, dict_of_users): message = '' members = User.getConversationMembers(session_api, event, dict_of_users) for member in dict_of_users.keys(): message += '@id' + str(member) + " " message += msg_command.split()[1] Messages.send_message(session_api, chat_id, message)
def all_commands(session_api, peer_id): message = 'List of commands: \n ' \ ' Date & Time:\n' \ ' 1. !date (return current date)\n' \ ' 2. !time (return current Moscow time)\n' \ ' 3. !datetime (return !date + !time)\n' \ ' Chat members:\n' \ ' 1. !members (return list of this chat members)\n' \ ' 2. !kick {id} (kick user from id. Example to kick (id=567123): !kick 567123\n' Messages.send_message(session_api, peer_id, message)
def OnSave(self, event): message = Utils.setParams(self) if message != None: Messages.messageError(message, 'Guardar') else: r = db.saveServerConfig(*self.params) if r: for field, label in self.fields: field.SetValue('') event.Skip()
def _clearJVMOutputFiles(self): """ Clears JVM output files. """ try: open(self._globJVMOutPath, 'w').close() open(self._globJVMErrPath, 'w').close() except: Messages.warning(__name__, "Cannot remove JVM output files!", verbose=2)
def _deleteJVMOutputFiles(self): """ Deletes JVM output files. """ try: IO.removeFile(self._globJVMOutPath) IO.removeFile(self._globJVMErrPath) except: Messages.warning(__name__, "Cannot remove JVM output files!", verbose=2)
def dict_iterator_and_send(dict_of_users, session_api, chat_id, event): User.getConversationMembers(session_api, event, dict_of_users) message = '' temp = 1 for user in dict_of_users.keys(): message += str(temp) + '. vk.com/id' + str(user) + ' ' + dict_of_users.get(user)['first_name'] \ + ' ' + dict_of_users.get(user)['last_name'] + '\n' temp += 1 Messages.send_message(session_api, chat_id, message)
def requestMessages(self, user_id): user = Users.getUser(user_id) c.log('info', 'Requesting messages for user %s %s %s' % (user_id, user['data']['first_name'], user['data']['last_name'])) if user_id not in self.data: self.data[user_id] = { 'id' : user_id, 'log' : [] } Messages.requestMessages({'user_id': user_id}, self.data[user_id])
def _handle_page_change(self, notebook, page, page_num): """ Handle a page change. When the user clicks on a new tab, reload the flow graph to update the vars window and call handle states (select nothing) to update the buttons. @param notebook the notebook @param page new page @param page_num new page number """ self.current_page = self.notebook.get_nth_page(page_num) Messages.send_page_switch(self.current_page.get_file_path()) Actions.PAGE_CHANGE()
def _handle_page_change(self, notebook, page, page_num): """ Handle a page change. When the user clicks on a new tab, reload the flow graph to update the vars window and call handle states (select nothing) to update the buttons. @param notebook the notebook @param page new page @param page_num new page number """ self.current_page = self.notebook.get_nth_page(page_num) Messages.send_page_switch(self.current_page.get_file_path()) self.handle_states()
def online_list(event, session_api, chat_id, msg_command, dict_of_users): members = getConversationMembers(session_api, event, dict_of_users) print('\n\n\n', members) temp = 1 message = 'Online list:\n' for k, v in members.items(): for k2 in v.keys(): if k2 == 'online' and v[k2] == 1: message += str(temp) + '. vk.com/id' + str(k) + '\n' temp += 1 Messages.send_message(session_api, chat_id, message)
def try_give_admin(event, session_api): try: chat_id = event.object.message['peer_id'] Messages.send_message( session_api, chat_id, "Hello! \n Give me admin role to work with chat. " "\n1) Bot will start work after 20 seconds if you gave him an admin role" "\n2) Bot will not work if you give not an admin role" "\n\nP.s. If 2) was, try kick and invite again") time.sleep(20) except KeyError: pass
def update_selected_elements(self): """ Update the selected elements. The update behavior depends on the state of the mouse button. When the mouse button pressed the selection will change when the control mask is set or the new selection is not in the current group. When the mouse button is released the selection will change when the mouse has moved and the control mask is set or the current group is empty. Attempt to make a new connection if the old and ports are filled. If the control mask is set, merge with the current elements. """ selected_elements = None if self.mouse_pressed: new_selections = self.what_is_selected(self.get_coordinate()) #update the selections if the new selection is not in the current selections #allows us to move entire selected groups of elements if self.get_ctrl_mask() or not (new_selections and new_selections[0] in self.get_selected_elements()): selected_elements = new_selections if self._old_selected_port: self._old_selected_port.force_label_unhidden(False) self.create_shapes() self.queue_draw() elif self._new_selected_port: self._new_selected_port.force_label_unhidden() else: # called from a mouse release if not self.element_moved and (not self.get_selected_elements() or self.get_ctrl_mask()): selected_elements = self.what_is_selected( self.get_coordinate(), self.press_coor) #this selection and the last were ports, try to connect them if self._old_selected_port and self._new_selected_port: try: self.connect(self._old_selected_port, self._new_selected_port) Actions.ELEMENT_CREATE() except: Messages.send_fail_connection() self._old_selected_port = None self._new_selected_port = None return #update selected elements if selected_elements is None: return old_elements = set(self.get_selected_elements()) self._selected_elements = list(set(selected_elements)) new_elements = set(self.get_selected_elements()) #if ctrl, set the selected elements to the union - intersection of old and new if self.get_ctrl_mask(): self._selected_elements = list( set.union(old_elements, new_elements) - set.intersection(old_elements, new_elements)) Actions.ELEMENT_SELECT()
def write(self): #do throttle warning throttled = any(map(lambda b: b.throttle(), self._flow_graph.get_enabled_blocks())) if not throttled and self._generate_options != 'hb': Messages.send_warning('''\ This flow graph may not have flow control: no audio or usrp blocks found. \ Add a Misc->Throttle block to your flow graph to avoid CPU congestion.''') #generate open(self.get_file_path(), 'w').write(str(self)) if self._generate_options == 'hb': #convert hier block to xml wrapper convert_hier.convert_hier(self._flow_graph, self.get_file_path()) os.chmod(self.get_file_path(), self._mode)
def __shutdownJVM(self): """ Shuts down the Java Virtual Machine """ if self._globJVMOn: jpype.shutdownJVM() self._globJVMOn = False self._globJVMSymm = None Messages.log(__name__, "JVM shut down!", verbose=1) self._deleteJVMOutputFiles()
def _handle_page_change(self, notebook, page, page_num): """ Handle a page change. When the user clicks on a new tab, reload the flow graph to update the vars window and call handle states (select nothing) to update the buttons. Args: notebook: the notebook page: new page page_num: new page number """ self.current_page = self.notebook.get_nth_page(page_num) Messages.send_page_switch(self.current_page.get_file_path()) Actions.PAGE_CHANGE()
def OnDownload(self, event): message = Utils.setParams(self) if message != None: Messages.messageError(message, 'Error downloading code') else: ix = self.choice.GetCurrentSelection() if ix < 0: Messages.messageError('Select a server', 'Download ABAP Source code') else: abap = sap.getCode(self.servers[ix], self.params[0]) if abap != "": self.parent.code = abap self.parent.codetext.SetValue(abap) self.parent.ReloadHighlight() Messages.messageInformation( 'Source Code downloaded successfully!', 'Download') self.parent.local = False self.parent.ChangeRootName(self.params[0].upper(), True) self.parent.sap_program = self.params[0].upper() self.parent.sap_server = self.servers[ix] self.parent.tree.SetBackgroundColour('blue violet') self.parent.SetTitle('Zorse - SAP:\\' + self.params[0].upper()) self.Destroy() else: Messages.messageError('Error downloading program', 'Error downloading code')
def OnDownload(self, event): message = Utils.setParams(self) if message != None: Messages.messageError(message, 'Error downloading code') else: ix = self.choice.GetCurrentSelection() if ix < 0: Messages.messageError('Select a server', 'Download ABAP Source code') else: abap = sap.getCode(self.servers[ix], self.params[0]) if abap != "": self.parent.code = abap self.parent.codetext.SetValue(abap) self.parent.ReloadHighlight() Messages.messageInformation('Source Code downloaded successfully!', 'Download') self.parent.local = False self.parent.ChangeRootName(self.params[0].upper(), True) self.parent.sap_program = self.params[0].upper() self.parent.sap_server = self.servers[ix] self.parent.tree.SetBackgroundColour('blue violet') self.parent.SetTitle('Zorse - SAP:\\' + self.params[0].upper()) self.Destroy() else: Messages.messageError('Error downloading program', 'Error downloading code')
def _handle_server(self, prefix, cmd, suffix, params, caller): if cmd == "cmd": self.serv.executor.execute(suffix, params.split(' '), PluginUser(caller)) return True if cmd == "table": # https://github.com/stasivs/Messenger/issues/4 self.serv.resend( Bcast(""" <table> <tbody> <tr> <td>1</td> <td>2</td> </td> <tr> <td>3</td> <td>4</td> </td> </tbody> </table> """)) return True if cmd == "stop": sys.exit() return True if cmd == "say": if not prefix: self.serv.resend(Messages.Bcast(params)) else: self.serv.resend(UserMessage(params, prefix)) return True if cmd == "tell": if not suffix: return False user = self.serv.get_user_by_nick(suffix) if not prefix: user.send(Messages.Info(params)) else: user.send(UserMessage(params, prefix)) return True if cmd == "eval": res = eval(params) self.serv.resend(Messages.Info(res)) return True if cmd == "exec": exec(params) return True return False
def update_selected_elements(self): """ Update the selected elements. The update behavior depends on the state of the mouse button. When the mouse button pressed the selection will change when the control mask is set or the new selection is not in the current group. When the mouse button is released the selection will change when the mouse has moved and the control mask is set or the current group is empty. Attempt to make a new connection if the old and ports are filled. If the control mask is set, merge with the current elements. """ selected_elements = None if self.mouse_pressed: new_selections = self.what_is_selected(self.get_coordinate()) #update the selections if the new selection is not in the current selections #allows us to move entire selected groups of elements if self.get_ctrl_mask() or not ( new_selections and new_selections[0] in self.get_selected_elements() ): selected_elements = new_selections if self._old_selected_port: self._old_selected_port.force_label_unhidden(False) self.create_shapes() self.queue_draw() elif self._new_selected_port: self._new_selected_port.force_label_unhidden() else: # called from a mouse release if not self.element_moved and (not self.get_selected_elements() or self.get_ctrl_mask()): selected_elements = self.what_is_selected(self.get_coordinate(), self.press_coor) #this selection and the last were ports, try to connect them if self._old_selected_port and self._new_selected_port: try: self.connect(self._old_selected_port, self._new_selected_port) Actions.ELEMENT_CREATE() except: Messages.send_fail_connection() self._old_selected_port = None self._new_selected_port = None return #update selected elements if selected_elements is None: return old_elements = set(self.get_selected_elements()) self._selected_elements = list(set(selected_elements)) new_elements = set(self.get_selected_elements()) #if ctrl, set the selected elements to the union - intersection of old and new if self.get_ctrl_mask(): self._selected_elements = list( set.union(old_elements, new_elements) - set.intersection(old_elements, new_elements) ) Actions.ELEMENT_SELECT()
def run(self): try: self.lock.acquire() while not self.shouldStop: self.lock.release() recvable, sendable, errored = self.samSockManager.select( self.connsWithRecvInterest, self.connsWithSendInterest, self.allConns, timeout=1 ) self.lock.acquire() for connId in errored: # conn failed, close it self._failedConn(connId, "connection failed") for connId in sendable: if connId in self.conns: # connected connSet = self.conns[connId] torrentInfo = self.torrents[connSet["torrentIdent"]] connSet["sock"].send(Messages.generateHandshake(torrentInfo["infohash"], self.peerId)) self.connsWithSendInterest.remove(connId) self.connsWithRecvInterest.add(connId) for connId in recvable: if connId in self.conns: # received data self._recvFromConn(connId) self.thread = None self.log.info("Stopping") self.lock.release() except: self.log.error("Error in main loop:\n%s", logTraceback())
def _gotFullHandshake(self, connId, connSet): data = "".join(connSet["inBuffer"]) # decode handshake length, proto, reserved, infohash, remotePeerId = Messages.decodeHandshake(data) if not proto.lower() == "bittorrent protocol": # invalid handshake, close conn self._failedConn(connId, "received invalid handshake") elif not infohash == self.torrents[connSet["torrentIdent"]]["infohash"]: # invalid infohash self._failedConn(connId, "received handshake with wrong infohash") else: # valid handshake if not self.peerPool.establishedConnection(connSet["torrentIdent"], connSet["sock"].getpeername()): # we already have a connection to this address self._failedConn(connId, "we already have a connection to this address") else: # no connection to this address exists up to now self.log.info("Conn %i: Got valid handshake, established connections", connId) # add to handler self.connHandler.addConnection(connSet["torrentIdent"], connSet["sock"], "out", remotePeerId) # remove from local structures self._removeConn(connId)
def _addConnection(self, torrentIdent, connSock, direction, remotePeerId): assert torrentIdent in self.torrents,'connection for not running torrent or something?!' torrent = self.torrents[torrentIdent] remoteAddr = connSock.getpeername() assert not remoteAddr in torrent['connRemoteAddrs'],'Already have a connection to that address?!' if remotePeerId in torrent['connPeerIds']: #already connected to this peer self.log.info('Conn %i: Closing because we are already connected to that peer', connSock.fileno()) connSock.close() self.peerPool.lostConnection(torrentIdent, remoteAddr) else: #really add this conn conn = BtConnection(torrentIdent, torrent['pieceStatus'], self.connStatsCache, self.connStatus,\ remotePeerId, self.scheduler, connSock, direction, remoteAddr,\ torrent['inMeasure'], torrent['outMeasure'], self.outLimiter, self.inLimiter) connId = conn.fileno() self.conns[connId] = conn torrent['connIds'].add(connId) torrent['connPeerIds'].add(remotePeerId) torrent['connRemoteAddrs'].add(remoteAddr) if torrent['superSeedingEnabled']: #add to handler torrent['superSeedingHandler'].addConn(connId, conn) else: #send bitfield conn.send(Messages.generateBitfield(torrent['ownStatus'].getBitfield()))
def menu(): print('1. Messages 2. Contacts') print('3. Phone 4. Media') print('b. Back 0. Exit') choice = '' while(choice!=0): choice = input('Enter Choice : ') if( choice == '1' ): Messages.menu() elif( choice == '2'): Contacts.menu() elif( choice == '3'): Phone.menu() elif( choice == '4'): Media.menu()
def connGotBitfield(self, connId): #got a bitfield from the peer, need to check if the peer already has some of the offered pieces self.lock.acquire() connSet = self.connInfo[connId] connStatus = connSet['conn'].getStatus() #check for offered pieces which the peer already has for pieceIndex in connStatus.getMatchingGotPieces(connSet['upPieces']): connSet['upPieces'].remove(pieceIndex) self.pieceStatus.decreaseAssignedUploads(pieceIndex) #offer new pieces if needed if len(connSet['upPieces']) < 2: wantedPieces = connStatus.getMatchingMissingPieces(self.ownStatus.getGotPieces()) wantedPieces.difference_update(connSet['upPieces']) pieces = self.pieceStatus.getUpPieces(wantedPieces, 2 - len(connSet['upPieces'])) if len(pieces) == 0: #no piece to offer self.log.debug('Conn %-6i - Nothing to offer (adding to waiting list)', connId) self.waitingConns.add(connId) else: #offer pieces self.log.debug('Conn %-6i - Offering pieces %s', connId, ', '.join(str(x) for x in pieces)) for pieceIndex in pieces: connSet['upPieces'].add(pieceIndex) connSet['conn'].send(Messages.generateHave(pieceIndex)) self.lock.release()
def get_msgs(self): self.m1 = Msg.get_m1() self.m2 = Msg.get_m2() self.m3 = Msg.get_m3() self.m4 = Msg.get_m4() self.m5 = Msg.get_m5() self.m6 = Msg.get_m6() self.m7 = Msg.get_m7() self.m8 = Msg.get_m8()
def _cancelInRequest(self, pieceIndex, offset, length): # try to find the request, send cancel and then delete it inRequest = (pieceIndex, offset, length) self.inRequestQueue.remove(inRequest) requestInfo = self.inRequestInfo.pop(inRequest) if not self._abortSend(requestInfo["messageId"]): # the request was already send self._queueSend(Messages.generateCancel(pieceIndex, offset, length))
def answer_request(self, piece_index, begin, length): data = "" remaining_length = length while(remaining_length>0): block_index = int(begin/BLOCK_SIZE) if(self.torrent.fileManager.blockExists(piece_index,block_index)): #block_exists indicates if block is present if(remaining_length >= BLOCK_SIZE): data = self.torrent.fileManager.readBlock(piece_index,block_index)[begin%BLOCK_SIZE:] #readBlock returns the data block begin = math.ceil(begin/BLOCK_SIZE)*ConstantsBLOCK_SIZE remaining_length -= BLOCK_SIZE-begin%BLOCK_SIZE else: data = self.torrent.fileManager.readBlock(piece_index,block_index)[begin%BLOCK_SIZE:remaining_length] remaining_length = 0 self.transport.write(str(Messages.Piece( index = Messages.number_to_bytes(piece_index), begin = Messages.number_to_bytes(begin), block = data))) #send corresponding data block if(begin == self.torrent.fileManager.get_piece_length(piece_index)): #get piece length for corresponding piece index piece_index += 1 begin = 0
def welcome_screen(): global LAST_NAME global DAY raw_input(Messages.WELCOME) name = raw_input(Messages.ASK_LAST_NAME) # TODO: but aren't we already creating a Player in CharacterDB? GAME_STATE.player = Character.Player(name=name) bully = CharacterDB.random_character(cclass='Camper', gender='m') print 'Your name is Pickett %s' % GAME_STATE.player.name Messages.print_messages([ Messages.EXPLANATION, Messages.BUS_LOADING, Messages.CRACK, Messages.GAME_KID_LOST]) return week_one(bully)
def week_one(bully): if GAME_STATE.day == 1: Messages.print_messages(Messages.WEEK_ONE[GAME_STATE.day]) campers = CharacterDB.random_character_sample(cclass='Camper', count=5) troid = CharacterDB.find('Troid') people_outside_theater = campers + [troid] while GAME_STATE.characters_talked_to < 3: GAME_STATE.characters_talked_to += 1 person = CharacterDB.choose_person( people_outside_theater, Messages.LEAVING_THEATER) GameState.GAME_STATE.already_talked_to.append('Troid') character_talking = person.name if person == troid: Messages.print_messages([ Messages.TROID_DESCRIPTION, Messages.PERSON_TALKING % character_talking + Messages.TROID_HEY_BRO, Messages.PERSON_TALKING % character_talking + Messages.TROID_CONVO_ONE]) answer = raw_input(Messages.TROID_CONVO_ONE_ANSWERS) if answer == '1': troid.dispo += 1 Messages.print_messages([ Messages.PERSON_TALKING % character_talking + Messages.TROID_LOVES_X]) elif answer == '2': troid.dispo -= 1 Messages.print_messages([ Messages.PERSON_TALKING % character_talking + Messages.TROID_WHATEVER_SMELL]) elif answer == '3': troid.dispo -= 1 Messages.print_messages([ Messages.PERSON_TALKING % character_talking + Messages.TROID_WOW]) else: answer = raw_input(Messages.TROID_CONVO_ONE_ANSWERS)
def generate_next_request(self): while True: #Ask the Requests Manager for new Blocks to request piece_index,block_index = self.torrent.requester.get_next_block(self) if block_index < 0 or len(self.set_of_blocks_requested) >= MAX_REQUEST_TO_PEER: if self.torrent.file_manager.StreamCompleted == True: reactor.stop() else: break block_byte_offset = block_index*BLOCK_SIZE #Add this to the set of blocks requested. self.set_of_blocks_requested.add((piece_index,block_index)) self.transport.write(str(Messages.Request( index = Messages.number_to_bytes(piece_index), begin = Messages.number_to_bytes(block_byte_offset), length = Messages.number_to_bytes(BLOCK_SIZE)))) self.torrent.requester.requestSuccessful(self, piece_index,block_index) #Add timeout for requests. Logger.info("Sending Request For Piece :" + str(Messages.number_to_bytes(piece_index)) + " to " + str(self.ip)) reactor.callLater(TIMEOUT,self.checkTimeout,piece_index,block_index)