def _refresh_common_key(sid):
	s_obj = WebServerModel.objects(sid=sid)

	if s_obj.get().children:
		logger.info("common key timeout")
		new_prk = api.generate_private_key()
		message = {
					"action":api._ACTION_KEYS[3],
					"data":
					{
			    		"common_key_private":new_prk.exportKey().decode('utf-8')
			    	}
				}

		try:
			if _broadcast_to_nodes(api.EXCHANGE_FOR_ALL, 
				api.encrypt_msg(s_obj.scalar('common_key_public').get(), 
				message)) == False:
				logger.error("Message broadcast failed")
				

			#else:
			res = s_obj.update_one(
				common_key_public=api.generate_public_key(new_prk).exportKey().decode('utf-8'),
				common_key_private=message['data']['common_key_private'])
			s_obj.get().save()

			## make log of updated common key
			_make_log(api._ACTION_KEYS[3], sid, "common key updated")

		except:
			logger.error("try again")
		
	
	threading.Timer(api.COMMON_KEY_TIMEOUT, _refresh_common_key, [sid]).start()
from web_server.general_api import general_api as api
from web_server.general_api.connection_timeout import ConnTimeout
from client_model import AppModel
from app_core import Node
from server_listener import BroadcastListener, MessageListener
from mongoengine import *


MSG_FROM_NODES = "msg_from_nodes"
## if this file is directly ran by python
if __name__ == "__main__":

    connect('chatchat')

    private_key = api.generate_private_key()
    m_AppModel = AppModel(
        public_key=api.generate_public_key(private_key).exportKey().decode('utf-8'), 
        nid=str(api.__uuid_generator_1()), 
        private_key=private_key.exportKey().decode('utf-8'))

    ## this will execute document.insert()
    m_AppModel.save()

    # node instance
    mNode = Node(pickle.dumps(m_AppModel))
    mNode.start()

    # listener for receiving broadcasted msg from the master server
    mBroadcastListener = BroadcastListener(m_AppModel.nid)
    mBroadcastListener.start()