Exemple #1
0
    def get_update(self):
        update_id = self.request.get("update_id", None)
        if update_id is not None:
            update_id = int(update_id)

        chat_update_id = self.request.get("chat_update_id", None)
        if chat_update_id is not None:
            chat_update_id = int(chat_update_id)

        userchat_key = db.Key(self.request.get("userchat_key", None))

        chat_id = userchat_key.id_or_name()
        if chat_id:
            peer_id_holder = self.memcache_fetcher.get(
                config.MEMCACHE_PEER_ID(userchat_key.parent().id_or_name(), chat_id)
            )
        self.login(prev_update_id=update_id, chat_id=chat_id, prev_chat_update_id=chat_update_id)

        message = None
        if chat_id:
            if userchat_key.parent() != self.user_key:
                self.response.set_status(404)
                return
            chat_key = db.Key.from_path("Chat", chat_id)
            chat_timestamp = common.str2datetime(self.request.get("chat_timestamp"))

            message = self.request.get("message", None)

            peer_id = peer_id_holder.get_result()
            if peer_id is None:
                userchat = self.datastore_fetcher.get(userchat_key)
                peer_userchat_key = common.get_ref_key(userchat.get_result(), "peer_userchat")
                peer_id = peer_userchat_key.parent().id_or_name()
                memcache.set(peer_id_holder.get_key(), peer_id, time=600)

            peer_status = self.memcache_fetcher.get(config.MEMCACHE_LAST_BEEN_ONLINE(peer_id))
            message_entity = None
            if message:
                message = common.htmlize_string(common.sanitize_string(message))
                message_entity = models.Message(parent=chat_key, message_string=message, sender=userchat_key)

                peer_chat_open = self.memcache_fetcher.get(config.MEMCACHE_USER_OPEN_CHAT(peer_id, chat_id))
                if peer_chat_open.get_result() is None:
                    peer_unreadchat_key = db.Key.from_path("User", peer_id, "UnreadChat", chat_id)
                    peer_unreadchat = models.UnreadChat(key=peer_unreadchat_key)

                    userchat_holder = self.datastore_fetcher.get(userchat_key)
                    peer_userchat_holder = self.datastore_fetcher.get(
                        db.Key.from_path("User", peer_id, "UserChat", chat_id)
                    )
                    userchat = userchat_holder.get_result()
                    peer_userchat = peer_userchat_holder.get_result()
                    userchat.last_updated = self.now
                    peer_userchat.last_updated = self.now
                    db.put([message_entity, peer_unreadchat, peer_userchat, userchat])

                    peer_update_id = memcache.incr(config.MEMCACHE_USER_UPDATE_ID(peer_id), initial_value=0)
                    memcache.set(
                        config.MEMCACHE_USER_NOTIFICATION(peer_id, peer_update_id),
                        {
                            "username": models.User.get_username(self.user_key),
                            "chat_id": chat_id,
                            "message": message,
                            "link": "/chat/%s" % models.User.get_username(self.user_key),
                            "timestamp": message_entity.date_time,
                        },
                        time=config.NOTIFICATION_DURATION,
                    )
                else:
                    db.put(message_entity)

            if self.chat_update_id:
                new_messages = (
                    db.Query(models.Message)
                    .ancestor(chat_key)
                    .filter("date_time >", chat_timestamp)
                    .order("-date_time")
                    .fetch(10)
                )
                try:
                    self.client_update["chat_timestamp"] = str(new_messages[0].date_time)
                except:
                    pass
                new_messages.reverse()

                template_values = {
                    "username": models.User.get_username(self.user_key),
                    "messages": [
                        {
                            "message_string": msg.message_string,
                            "username": models.User.get_username(common.get_ref_key(msg, "sender").parent()),
                        }
                        for msg in new_messages
                    ],
                }
                path = os.path.join(os.path.dirname(__file__), "_messages.html")
                self.client_update["messages_html"] = template.render(path, template_values).decode("utf-8")
            elif message_entity is not None:
                self.client_update["chat_timestamp"] = str(message_entity.date_time)
                template_values = {
                    "username": models.User.get_username(self.user_key),
                    "messages": [
                        {
                            "message_string": message_entity.message_string,
                            "username": models.User.get_username(common.get_ref_key(message_entity, "sender").parent()),
                        }
                    ],
                }
                path = os.path.join(os.path.dirname(__file__), "_messages.html")
                self.client_update["messages_html"] = template.render(path, template_values).decode("utf-8")

            if chat_id and message_entity:
                self.chat_update_id = memcache.incr(config.MEMCACHE_CHAT_UPDATE_ID(chat_id), delta=1, initial_value=0)

            self.client_update["status_class"] = "offline" if peer_status.get_result() is None else "online"

        self._get_client_update()
        return self.client_update
Exemple #2
0
    def get(self):
        q = self.request.get("q").strip()

        if not q:
            self.redirect("/")
            return

        self.login()

        clean_string = search.clean_query_string(q)
        query_hash = common.get_query_hash(clean_string)

        query_key = db.Key.from_path("Query", query_hash, parent=self.user_key)
        existing_query = self.datastore_fetcher.get(query_key)

        keyword_hashes = search.get_keyword_hashes(clean_string)
        search_hashes = keyword_hashes[: config.MAX_SEARCH_KEYWORDS]

        context = self.datastore_fetcher.get(db.Key.from_path("UserContext", self.user_key.id_or_name()))

        search_query = search.get_search_query(search_hashes)
        cur = self.request.get("cursor")
        if cur is not None:
            search_query.with_cursor(cur)

        result_keys = []
        existing_chats = {}
        users_status = {}
        unread_chats = {}
        cursor = None

        res_keys = search_query.fetch(config.ITEMS_PER_PAGE)
        if len(res_keys) >= config.ITEMS_PER_PAGE:
            cursor = search_query.cursor()

        for k in res_keys:
            q_key = search.decode_query_index_key_name(k.name())
            user_key = q_key.parent()
            if user_key != self.user_key:
                result_keys.append(q_key)
                chat_id = common.get_chat_key_name(self.user_key, user_key)
                existing_chats[user_key] = self.datastore_fetcher.get(
                    db.Key.from_path("User", self.user_key.id_or_name(), "UserChat", chat_id)
                )
                users_status[user_key] = self.memcache_fetcher.get(
                    config.MEMCACHE_LAST_BEEN_ONLINE(user_key.id_or_name())
                )
                unread_chats[user_key] = self.datastore_fetcher.get(
                    db.Key.from_path("User", self.user_key.id_or_name(), "UnreadChat", chat_id)
                )

        results = self.datastore_fetcher.get(result_keys)

        result_values = []
        online_count = 1
        for r in results:
            user_key = r.parent_key()
            status_class = "online" if users_status[user_key].get_result() is not None else "offline"
            if status_class == "online":
                online_count += 1

            v = {
                "query": r.query_string,
                "key": r.key(),
                "username": models.User.get_username(user_key),
                "status_class": status_class,
                "context": common.htmlize_string(r.context),
            }

            if existing_chats[user_key].get_result() is not None:
                v["existing_chat"] = existing_chats[user_key].name
                if unread_chats[user_key].get_result() is not None:
                    v["existing_chat_unread"] = True

            result_values.append(v)

        if not result_values:
            self.template_values["top_searches"] = get_top_searches()

        if not cursor:
            context_text = ""
            if context:
                context_text = context.context
                keyword_hashes = list(
                    keyword_hashes + search.get_keyword_hashes(search.clean_query_string(context_text))
                )[: config.MAX_KEYWORDS]
            query = existing_query.get_result()
            if query is not None:
                existing_index = db.Query(models.QueryIndex, keys_only=True).filter("query =", query).get()
                if existing_index is not None:
                    db.delete(existing_index)
                query.query_string = q
                query.context = context_text
                query.date_time = self.now
            else:
                query = models.Query(key=query_key, query_string=q, context=context_text, date_time=self.now)

            index = models.QueryIndex(
                key_name=search.encode_query_index_key_name(query_key),
                query=query_key,
                user=self.user_key,
                keyword_hashes=keyword_hashes,
            )

            top_search = models.TopSearch(
                key_name=query_key.name(), query_string=q, rating=float(len(search_hashes) * online_count)
            )
            db.put([query, index, top_search])

        self.template_values["results"] = result_values
        self.template_values["key"] = query.key()
        self.template_values["query"] = q
        self.template_values["cursor"] = cursor

        self.render_page("SearchPage.html")
Exemple #3
0
    def get_update(self):
        update_id = self.request.get('update_id', None)
        if update_id is not None:
            update_id = int(update_id)

        chat_update_id = self.request.get('chat_update_id', None)
        if chat_update_id is not None:
            chat_update_id = int(chat_update_id)

        userchat_key = db.Key(self.request.get("userchat_key", None))

        chat_id = userchat_key.id_or_name()
        if chat_id:
            peer_id_holder = self.memcache_fetcher.get(
                config.MEMCACHE_PEER_ID(userchat_key.parent().id_or_name(),
                                        chat_id))
        self.login(prev_update_id=update_id,
                   chat_id=chat_id,
                   prev_chat_update_id=chat_update_id)

        message = None
        if chat_id:
            if userchat_key.parent() != self.user_key:
                self.response.set_status(404)
                return
            chat_key = db.Key.from_path('Chat', chat_id)
            chat_timestamp = common.str2datetime(
                self.request.get('chat_timestamp'))

            message = self.request.get("message", None)

            peer_id = peer_id_holder.get_result()
            if peer_id is None:
                userchat = self.datastore_fetcher.get(userchat_key)
                peer_userchat_key = common.get_ref_key(userchat.get_result(),
                                                       'peer_userchat')
                peer_id = peer_userchat_key.parent().id_or_name()
                memcache.set(peer_id_holder.get_key(), peer_id, time=600)

            peer_status = self.memcache_fetcher.get(
                config.MEMCACHE_LAST_BEEN_ONLINE(peer_id))
            message_entity = None
            if message:
                message = common.htmlize_string(
                    common.sanitize_string(message))
                message_entity = models.Message(parent=chat_key,
                                                message_string=message,
                                                sender=userchat_key)

                peer_chat_open = self.memcache_fetcher.get(
                    config.MEMCACHE_USER_OPEN_CHAT(peer_id, chat_id))
                if peer_chat_open.get_result() is None:
                    peer_unreadchat_key = db.Key.from_path(
                        'User', peer_id, 'UnreadChat', chat_id)
                    peer_unreadchat = models.UnreadChat(
                        key=peer_unreadchat_key)

                    userchat_holder = self.datastore_fetcher.get(userchat_key)
                    peer_userchat_holder = self.datastore_fetcher.get(
                        db.Key.from_path('User', peer_id, 'UserChat', chat_id))
                    userchat = userchat_holder.get_result()
                    peer_userchat = peer_userchat_holder.get_result()
                    userchat.last_updated = self.now
                    peer_userchat.last_updated = self.now
                    db.put([
                        message_entity, peer_unreadchat, peer_userchat,
                        userchat
                    ])

                    peer_update_id = memcache.incr(
                        config.MEMCACHE_USER_UPDATE_ID(peer_id),
                        initial_value=0)
                    memcache.set(
                        config.MEMCACHE_USER_NOTIFICATION(
                            peer_id, peer_update_id),
                        {
                            'username':
                            models.User.get_username(self.user_key),
                            'chat_id':
                            chat_id,
                            'message':
                            message,
                            'link':
                            '/chat/%s' %
                            models.User.get_username(self.user_key),
                            'timestamp':
                            message_entity.date_time,
                        },
                        time=config.NOTIFICATION_DURATION,
                    )
                else:
                    db.put(message_entity)

            if self.chat_update_id:
                new_messages = db.Query(
                    models.Message).ancestor(chat_key).filter(
                        'date_time >',
                        chat_timestamp).order('-date_time').fetch(10)
                try:
                    self.client_update['chat_timestamp'] = str(
                        new_messages[0].date_time)
                except:
                    pass
                new_messages.reverse()

                template_values = {
                    "username":
                    models.User.get_username(self.user_key),
                    "messages": [{
                        'message_string':
                        msg.message_string,
                        'username':
                        models.User.get_username(
                            common.get_ref_key(msg, 'sender').parent())
                    } for msg in new_messages],
                }
                path = os.path.join(os.path.dirname(__file__),
                                    '_messages.html')
                self.client_update['messages_html'] = template.render(
                    path, template_values).decode('utf-8')
            elif message_entity is not None:
                self.client_update['chat_timestamp'] = str(
                    message_entity.date_time)
                template_values = {
                    "username":
                    models.User.get_username(self.user_key),
                    "messages": [{
                        'message_string':
                        message_entity.message_string,
                        'username':
                        models.User.get_username(
                            common.get_ref_key(message_entity,
                                               'sender').parent())
                    }],
                }
                path = os.path.join(os.path.dirname(__file__),
                                    '_messages.html')
                self.client_update['messages_html'] = template.render(
                    path, template_values).decode('utf-8')

            if chat_id and message_entity:
                self.chat_update_id = memcache.incr(
                    config.MEMCACHE_CHAT_UPDATE_ID(chat_id),
                    delta=1,
                    initial_value=0)

            self.client_update[
                'status_class'] = "offline" if peer_status.get_result(
                ) is None else "online"

        self._get_client_update()
        return self.client_update
Exemple #4
0
    def get(self):
        q = self.request.get('q').strip()

        if not q:
            self.redirect("/")
            return

        self.login()

        clean_string = search.clean_query_string(q)
        query_hash = common.get_query_hash(clean_string)

        query_key = db.Key.from_path('Query', query_hash, parent=self.user_key)
        existing_query = self.datastore_fetcher.get(query_key)

        keyword_hashes = search.get_keyword_hashes(clean_string)
        search_hashes = keyword_hashes[:config.MAX_SEARCH_KEYWORDS]

        context = self.datastore_fetcher.get(
            db.Key.from_path('UserContext', self.user_key.id_or_name()))

        search_query = search.get_search_query(search_hashes)
        cur = self.request.get('cursor')
        if cur is not None:
            search_query.with_cursor(cur)

        result_keys = []
        existing_chats = {}
        users_status = {}
        unread_chats = {}
        cursor = None

        res_keys = search_query.fetch(config.ITEMS_PER_PAGE)
        if len(res_keys) >= config.ITEMS_PER_PAGE:
            cursor = search_query.cursor()

        for k in res_keys:
            q_key = search.decode_query_index_key_name(k.name())
            user_key = q_key.parent()
            if user_key != self.user_key:
                result_keys.append(q_key)
                chat_id = common.get_chat_key_name(self.user_key, user_key)
                existing_chats[user_key] = self.datastore_fetcher.get(
                    db.Key.from_path('User', self.user_key.id_or_name(),
                                     'UserChat', chat_id))
                users_status[user_key] = self.memcache_fetcher.get(
                    config.MEMCACHE_LAST_BEEN_ONLINE(user_key.id_or_name()))
                unread_chats[user_key] = self.datastore_fetcher.get(
                    db.Key.from_path('User', self.user_key.id_or_name(),
                                     'UnreadChat', chat_id))

        results = self.datastore_fetcher.get(result_keys)

        result_values = []
        online_count = 1
        for r in results:
            user_key = r.parent_key()
            status_class = "online" if users_status[user_key].get_result(
            ) is not None else "offline"
            if status_class == 'online':
                online_count += 1

            v = {
                'query': r.query_string,
                'key': r.key(),
                'username': models.User.get_username(user_key),
                'status_class': status_class,
                'context': common.htmlize_string(r.context),
            }

            if existing_chats[user_key].get_result() is not None:
                v['existing_chat'] = existing_chats[user_key].name
                if unread_chats[user_key].get_result() is not None:
                    v['existing_chat_unread'] = True

            result_values.append(v)

        if not result_values:
            self.template_values['top_searches'] = get_top_searches()

        if not cursor:
            context_text = ""
            if context:
                context_text = context.context
                keyword_hashes = list(
                    keyword_hashes + search.get_keyword_hashes(
                        search.clean_query_string(context_text)))[:config.
                                                                  MAX_KEYWORDS]
            query = existing_query.get_result()
            if query is not None:
                existing_index = db.Query(models.QueryIndex,
                                          keys_only=True).filter(
                                              'query =', query).get()
                if existing_index is not None:
                    db.delete(existing_index)
                query.query_string = q
                query.context = context_text
                query.date_time = self.now
            else:
                query = models.Query(key=query_key,
                                     query_string=q,
                                     context=context_text,
                                     date_time=self.now)

            index = models.QueryIndex(
                key_name=search.encode_query_index_key_name(query_key),
                query=query_key,
                user=self.user_key,
                keyword_hashes=keyword_hashes)

            top_search = models.TopSearch(
                key_name=query_key.name(),
                query_string=q,
                rating=float(len(search_hashes) * online_count))
            db.put([query, index, top_search])

        self.template_values["results"] = result_values
        self.template_values["key"] = query.key()
        self.template_values["query"] = q
        self.template_values["cursor"] = cursor

        self.render_page('SearchPage.html')