def get_new_message_for_user(user, **kwargs):
    """
    get_new_message_for_user(user, **kwargs) -> HTTPResponse(json(new_data))
    Return HTTP response to new data
    :type user: basestring
    """
    def __update_data(_data):
        conferences = get_memcached(get_key("conferences"))
        for key in conferences.keys():
            if user in conferences[key]["users"].keys():
                try:
                    msg = conferences[key]["users"][user]["messages"]
                except:
                    msg = []
                if msg:
                    _data["new_data"].append({key: {"messages": msg}})
                    conferences[key]["users"][user]["messages"] = []
                    set_memcached(get_key("conferences"), conferences)
        notifications = get_notifications(kwargs["user_obj"])
        if notifications:
            _data["notifications"] = _data["notifications"] + notifications
        return _data

    def __get_new_data():
        listeners = get_memcached(get_key("listeners"))
        _new_data = {
            "users": [dict(name=key,
                           location=listeners[key]["locations"],
                           profile=listeners[key]["profile"]) for key in listeners.keys() if not key == str(user)],
            "new_data": [],
            "conferences": get_active_conferences(user),
            "notifications": get_notifications(kwargs["user_obj"])
        }
        return _new_data.copy()

    if "flag" not in kwargs.keys():
        kwargs["flag"] = None
    if "long_polling" not in kwargs.keys():
        kwargs["long_polling"] = False
    if "user_obj" in kwargs.keys() and "location" in kwargs.keys():
        _location = kwargs['location']
    else:
        kwargs["user_obj"] = None

    data = __get_new_data()

    if settings.CHAT_LONG_POLLING and kwargs["long_polling"]:

        out_time = 0
        while not data["new_data"] and out_time < settings.CHAT_TIMEOUT:

            if kwargs["user_obj"]:
                if _location:
                    update_user(kwargs["user_obj"], _location)

            out_time += 1

            _temp_data = __get_new_data()
            _temp_data = __update_data(_temp_data)

            if not _temp_data == data:
                data = _temp_data.copy()
                break

            if kwargs["flag"] == "connect":
                break

            if not _temp_data["new_data"]:
                sleep(settings.CHAT_TIME_SLEEP_NEWDATA)
            else:
                data = _temp_data.copy()

    data = json.dumps(data)
    return HttpResponse(data, content_type='application/json', status=200)
dataset/ETHPy150Open treeio/treeio/treeio/core/middleware/chat.py/get_new_message_for_user/original