Ejemplo n.º 1
0
class Memcache:
    WAIT_ASK = 1
    WAIT_ANSWER = 2

    def __init__(self):
        self.cache = MemcachedCache(['127.0.0.1:11211'])

    def get(self, key):
        ret = self.cache.get(key)
        try:
            ret = ret.decode('utf-8')
        except:
            pass
        return ret

    def set(self, key, value):
        try:
            value = value.encode('utf-8')
        except:
            pass
        return self.cache.set(key, value, timeout=600)

    def delete(self, key):
        return self.cache.delete(key)

    def check_history(self, qid, gid=0):
        r = self.get(u'H' + str(qid) + u'G' + str(gid))
        if r is None:
            return r, r
        if r == self.WAIT_ANSWER:
            return self.WAIT_ANSWER, self.get(u'A' + str(qid) + u'G' +
                                              str(gid))
        if r == self.WAIT_ASK:
            return self.WAIT_ASK, None
        return None

    def set_before_ask(self, qid, gid=0):
        self.set(u'H' + str(qid) + u'G' + str(gid), self.WAIT_ASK)

    def set_before_answer(self, qid, ask, gid=0):
        self.set(u'A' + str(qid) + u'G' + str(gid), ask)
        self.set(u'H' + str(qid) + u'G' + str(gid), self.WAIT_ANSWER)

    def clear_state(self, qid, gid=0):
        self.delete(u'A' + str(qid) + u'G' + str(gid))
        self.delete(u'H' + str(qid) + u'G' + str(gid))

    def last_warn_time(self, qid):
        self.set(u'W' + str(qid), time.time())

    def check_last_chat_same(self, qid, msg):
        if self.get(u'LC' + str(qid)) and self.get(u'LC' + str(qid)) == msg:
            return self.last_chat_count(qid, add=True)
        self.set(u'LC' + str(qid), msg)
        self.set(u'LCC' + str(qid), 1)
        return True

    def last_chat_count(self, qid, add=False):
        lcc = self.get(u'LCC' + str(qid))
        if not lcc:
            self.set(u'LCC' + str(qid), 1)
            return True
        if add and lcc <= AdvancedSettings.same_response_limit:
            self.cache.inc(u'LCC' + str(qid))
            lcc += 1
        return lcc < AdvancedSettings.same_response_limit

    def check_block_user(self, qid):
        x = self.get(u'BU' + str(qid))
        if x is not None:
            return x
        db = MyDB()
        is_blocked = db.check_blocked(qid, 'user')
        logging.info("is_blocked")
        logging.info(is_blocked)
        self.set(u'BU' + str(qid), is_blocked)
        return is_blocked

    def check_block_group(self, gid):
        x = self.get(u'BG' + str(gid))
        if x is not None:
            return x
        db = MyDB()
        is_blocked = db.check_blocked(gid, 'group')
        self.set(u'BG' + str(gid), is_blocked)
        return is_blocked

    def check_disable_group(self, gid):
        x = self.get(u'BD' + str(gid))
        if x is not None:
            return x
        db = MyDB()
        is_disabled = db.check_disabled(gid)
        self.set(u'BD' + str(gid), is_disabled)
        return is_disabled