Example #1
0
 def __init__(self, logging):
     self.logger = newLogger("Core Messages")
     self._lock = loggingMutex("messages", logging=logging)
     self._db, plugin_type = get_db_connection(self.logger)
     
     if self._db is None:
         self._length = 0
         self._latest = None
         return
     
     if plugin_type != "SQLite Connection":
         self.logger.warning("Your standard connection is not of type SQLite." + \
             "Loading messages from another type is experimental.")
     
     if not self._db.existsTable("CORE_MESSAGE_VERSION"):
         self._db.execute("CREATE TABLE CORE_MESSAGE_VERSION(VERSION INTEGER)")
         self._db.execute("INSERT INTO CORE_MESSAGE_VERSION(VERSION) VALUES(?)", self._DB_VERSION_CURRENT)
                     
     if not self._db.existsTable("CORE_MESSAGES"):
         self._db.execute("CREATE TABLE CORE_MESSAGES(SENDER TEXT, TIME REAL, MESSAGE TEXT)")
         self._db.execute("CREATE INDEX CORE_MESSAGE_TIME_INDEX on CORE_MESSAGES(TIME ASC)")
         self._length = 0
         self._latest = None
         self.importOld(get_settings().get_legacy_messages_file())
     else:
         self._latest = self._getLatest()
         self._length = self._getNumMessages()    
Example #2
0
 def create_widget(self, parent):
     from private_messages.chat_history_view import ChatHistoryWidget
     
     self._lock = loggingMutex("Private Messages", logging=get_settings().get_verbose())
     
     from PyQt4.QtCore import QThread
     from private_messages.chat_messages_handler import ChatMessagesHandler
     if canUseBackgroundQThreads():
         self._messagesThread = QThread()
     else:
         self._messagesThread = None
         
     self._messagesHandler = ChatMessagesHandler(self.logger, self, self.hidden_options[u"ack_timeout"], self.hidden_options[u"next_msgid"])
     if self._messagesThread is not None:
         self._messagesHandler.moveToThread(self._messagesThread)
         self._messagesThread.start()
     
     self._messagesHandler.delayedDelivery.connect(self._delayedDelivery)
     self._messagesHandler.messageIDChanged.connect(self._messageIDChanged)
     self._messagesHandler.displayOwnMessage.connect(self._displayOwnMessage)
     self._messagesHandler.newMessage.connect(self._displayMessage)
     
     self._openChats = {} # mapping peer ID -> ChatDockWidget
     self._history = ChatHistoryWidget(self, parent, self.logger)
     return self._history
    def __init__(self, logger, thumbnailSize, storeLocally, gui):
        super(RemotePicturesHandler, self).__init__()

        self.logger = logger
        self._thumbnailSize = thumbnailSize
        self._storeLocally = storeLocally 
        self._gui = gui
        self._storage = RemotePicturesStorage(self, self.logger)
        self._currentlyDownloading = set() # set of currently downloading pictures
        self._lock = loggingMutex(u"Remote Pictures Handler", qMutex=True, logging=get_settings().get_verbose())
        
        self._createThumbnailAndAddCategory = AsyncCall(self,
                                                        self.logger,
                                                        self._createThumbnail,
                                                        self._addCategoryAndCloseFile)
        
        self._createAndChangeThumbnail = AsyncCall(self,
                                                   self.logger,
                                                   self._createThumbnail,
                                                   self._changeThumbnail)
        
        self._loadPictures.connect(self._loadPicturesSlot)
        self._processRemotePicture.connect(self._processRemotePictureSlot)
        self._checkCategory.connect(self._checkCategorySlot)
        self._thumbnailSizeChanged.connect(self._thumbnailSizeChangedSlot)
        self._storeLocallyChanged.connect(self._storeLocallyChangedSlot)
Example #4
0
 def __init__(self):
     super(lunch_server, self).__init__()
     self.controller = None
     self.initialized = False
     self._disable_broadcast = False
     self.running = False
     self._peer_nr = 0
     self._peers = None
     self.plugin_manager = None
     self._message_queues = {} # queues for messages from new peers
     self._last_messages = {} # last messages by peer ID, to avoid duplicates
     self._send_logger = newLogger("Core Send")
     self._recv_logger = newLogger("Core Recv")
     
     self.message_queues_lock = loggingMutex("message_queues", logging=get_settings().get_verbose())
     self.cached_messages_lock = loggingMutex("cached_messages", logging=get_settings().get_verbose())
     
     self.exitCode = 0  
Example #5
0
 def __init__(self):
     super(tdtnotify, self).__init__()
     self.options = {"blog_name":"tittendestages",
                     "polling_time":30}
     
     self.url = "http://api.tumblr.com/v2/blog/" + self.options['blog_name'] + \
                 ".tumblr.com/posts/photo?api_key=SyMOX3RGVS4OnK2bGWBcXNUfX34lnzQJY5FRB6uxpFqjEHz2SY"
     
     self.timer = None
     self.lock = loggingMutex("TDTNotify", logging=get_settings().get_verbose())
 def __init__(self, jsonString):
     # {plugin name : {action name : {settings}}}
     self.logger = newLogger("Privacy")
     try:
         self._settings = json.loads(jsonString)
     except ValueError:
         self.logger.exception("Error reading privacy settings from JSON.")
         self._settings = {}
     
     self._modifications = {}
     self._lock = loggingMutex("Privacy Settings", logging=get_settings().get_verbose())
Example #7
0
 def __init__(self, peers):
     self._s = None
     try:
         self._s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
     except:
         self._s = None
         raise
     
     self._peers = peers
     self._port = get_settings().get_udp_port()
     self._max_msg_length = get_settings().get_max_fragment_length()
     self._incomplete_messages = {}
     
     self._incMsgLock = loggingMutex("dropIncompleteMsg", logging=get_settings().get_verbose())
Example #8
0
 def __init__(self):
     super(db_connections, self).__init__()
     self.plugin_manager = get_plugin_manager()
     
     self.conn_properties_lock = loggingMutex("db_conn_properties", logging=get_settings().get_verbose())
     self.open_connections = {}
     self.conn_properties = {}
     self.conn_plugins = {} #will be filled later (init plugin obejcts)        
         
     self.options = [(("default_connection","Default Connection",
                       self.conn_properties.keys(),
                       get_settings().set_default_db_connection),
                      get_settings().get_default_db_connection())]
     self.force_activation = True
Example #9
0
    def __init__(self):
        """after initializing all variables, the peer information form the lust run is read from a file"""
        self.logger = newLogger("Peers")
        self._potentialPeers = set()  # set containing data from lunch_peers.cfg
        self._memberIDs = set()  # of PeerIDs members: peers that sent their info, are active and belong to my group
        self._IP_seen = {}  # last seen timestamps by IP
        self._peer_info = {}  # information of every peer by IP
        self._idToIp = {}  # mapping from ID to a set of IPs

        self._groups = set()  # seen group names

        self._lock = loggingMutex("peers", logging=get_settings().get_verbose())

        if get_settings().get_plugins_enabled():
            self._peerNames = PeerNames()
        else:
            self._peerNames = None
Example #10
0
 def __init__(self, logger, get_db_conn_func, options):
     super(TwitterDownloadThread, self).__init__()
     self.logger = logger
     self._get_db_conn = get_db_conn_func
     self._options = options
     
     self._safe_conn = None        
     self._twitter_api = None
     self._stop_event = Event()
     self._wait_event = Event()
     self._lock = loggingMutex("twitter download thread", logging=get_settings().get_verbose())
     
     self._own_screen_name = ""
     self._old_pic_urls = {}
     self._since_ids = {}
     self._mentions_since_id = 0
     self._remote_callers = []
     self._friends = []
 def __init__(self, logger, delegate, ackTimeout, nextMsgID):
     super(ChatMessagesHandler, self).__init__()
     
     self.logger = logger
     self._delegate = delegate
     self._ackTimeout = ackTimeout
     self._waitingForAck = {} # message ID : (otherID, time, message, isResend)
     self._hasUndelivered = True # just assume until proven otherwise
     self._currentlyDisplaying = {} # otherID : [msgID]
     self._displayMessageLock = loggingMutex(u"Chat messages delivery lock", qMutex=True, logging=get_settings().get_verbose())
     
     nextIDFromDB = self._getStorage().getLastSentMessageID() + 1
     self._nextMessageID = max(nextMsgID, nextIDFromDB)
     
     self._cleanupTimer = QTimer(self)
     self._cleanupTimer.timeout.connect(self._cleanup)
     self._cleanupTimer.start(2000)
     
     self._processAck.connect(self._processAckSlot)
     self._processMessage.connect(self._processMessageSlot)
     self._receivedSuccessfully.connect(self._receivedSuccessfullySlot)
     self._errorReceivingMessage.connect(self._errorReceivingMessageSlot)
     
     get_notification_center().connectPeerAppended(self._peerAppended)
Example #12
0
    def start_server(self):
        '''listening method - should be started in its own thread''' 
        
        getCoreLogger().info("%s - Starting the lunch notifier service", strftime("%a, %d %b %Y %H:%M:%S", localtime()).decode("utf-8"))
        
        self.my_master = -1  # the peer i use as master
        
        is_in_broadcast_mode = False
        
        self._recv_socket = lunchSocket(self._peers)
        try: 
            self._recv_socket.bind()
            self.running = True
            self._cleanupLock = loggingMutex("cleanup", logging=get_settings().get_verbose())
            self._startCleanupTimer()
            self.controller.initDone()
            
            #first thing to do: ask stored peers for their info:
            if len(self._peers) == 0:
                requests = self._peers.initPeersFromFile()
                self.call_request_info(requests)
            
            while self.running:
                try:
                    xmsg, ip = self._recv_socket.recv()
                    try:
                        plainMsg = xmsg.getPlainMessage()                        
                        self._recv_logger.info("From %s: %s",ip,plainMsg)
                    except:
                        getCoreLogger().exception("There was an error when trying to parse a message from %s", ip)
                        continue
                     
                    # check for local address: only stop command allowed, else ignore
                    if ip.startswith("127."):
                        if xmsg.getCommand() == "STOP":
                            getCoreLogger().info("Got Stop Command from localhost: %s", plainMsg)
                            self.running = False
                            self.exitCode = EXIT_CODE_STOP
                        elif xmsg.getCommand() == "OPEN_WINDOW" and lunchinator_has_gui():
                            self.controller._openWindow.emit()
                        elif xmsg.getCommand() == "LOCAL_PIPE":
                            getCoreLogger().debug("Relaying LOCAL_PIPE call")
                            self.call_all_members("HELO_PIPE "+xmsg.getCommandPayload())
                        continue
                    
                    # first we save the timestamp of this contact, no matter what
                    self._peers.seenIP(ip)

                    # check if we know this peer          
                    isNewPeer = self._peers.getPeerInfo(pIP=ip) == None          
                    if isNewPeer and self._should_call_info_on_event(plainMsg):
                        #this is a new member - we ask for info right away
                        self.call_request_info([ip])
                    
                    self._handle_event(xmsg, ip, time(), isNewPeer, False)
                except splitCall as e:
                    getCoreLogger().debug(e.value)
                except socket.timeout:                    
                    if len(self._peers) > 1:                     
                        if is_in_broadcast_mode:
                            is_in_broadcast_mode = False
                            getCoreLogger().info("ending broadcast")       
                    else:
                        if not self._disable_broadcast:
                            if not is_in_broadcast_mode:
                                is_in_broadcast_mode = True
                                getCoreLogger().info("seems like you are alone - broadcasting for others")
                            s_broad = lunchSocket(self._peers)
                            msg = 'HELO_REQUEST_INFO ' + self._build_info_string()
                            self._send_logger.info(msg)
                            s_broad.broadcast(msg)
                            s_broad.close()
                            #forgotten peers may be on file
                            requests = self._peers.initPeersFromFile()
                            self.call_request_info(requests)
                            
        except socket.error as e:
            # socket error messages may contain special characters, which leads to crashes on old python versions
            getCoreLogger().error(u"stopping lunchinator because of socket error: %s", convert_string(str(e)))
        except KeyboardInterrupt:
            getCoreLogger().info("Received keyboard interrupt, stopping.")
        except:
            getCoreLogger().exception("stopping - Critical error: %s", str(sys.exc_info())) 
        finally: 
            self.running = False
            try:
                #make sure to close the cleanup thread first
                with self._cleanupLock:
                    self._cleanupTimer.cancel()
                
                self.call("HELO_LEAVE bye")
                self._recv_socket.close()
                self._recv_socket = None 
            except:
                getCoreLogger().warning("Wasn't able to send the leave call and close the socket...")
            self._finish()
Example #13
0
 def _inactiveSocketsMutex(cls):
     if cls._mutex is None:
         cls._mutex = loggingMutex("inactive sockets mutex", True, logging=get_settings().get_verbose())
     return cls._mutex
 def __init__(self):
     self._lock = loggingMutex("Peer Actions", logging=get_settings().get_verbose())
     self._peerActions = {} # mapping plugin name -> list of peer actions
     self._msgPrefixes = {} # mapping message prefix -> peer action
     get_notification_center().connectPluginActivated(self._pluginActivated)
     get_notification_center().connectPluginDeactivated(self._pluginDeactivated)
Example #15
0
 def __init__(self, internalDir, externalRepos, logging=False):
     self._internalDir = internalDir
     self._externalRepos = externalRepos
     self._outdated = set()
     self._upToDate = set()
     self._lock = loggingMutex("repositories", logging=logging)