Esempio n. 1
0
    def get(self):
        """
        returns the most used coupon code in last two hours

        :return: coupon code object
        """
        store = Store.objects.filter(app_id=request.headers.get('APP-ID'),
                                     deleted_at=None).first()

        redis_conn = get_redis_connection()

        redis_response = json.loads(redis_conn.get(TOP_COUPON))

        coupon_code_id = None
        redemptions = 0
        for key, value in sorted(redis_response.items(),
                                 key=lambda x: x[1][1],
                                 reverse=True):
            if value[0] == store.store_id:
                coupon_code_id = key
                redemptions = value[1]
                break

        if coupon_code_id is None:
            return jsonify("{}"), 404

        coupon = CouponCode.objects.filter(
            coupon_code_id=coupon_code_id).first().to_dict()

        coupon["redemptions"] = redemptions

        response = {"result": "ok", "coupon": coupon}

        return jsonify(response), 200
Esempio n. 2
0
def conf(conference_name):
    """
    Renders the XML to start a conference based on the conference name
    it receives. It checks if the conference exists in our memory (to make
    sure it hasn't expired). 

    This URL is passed as the Answer URL to Plivo. When the call gets
    answered, the call will be put into a conference.
    """

    redis_conn = get_redis_connection()
    room_exists = redis_conn.exists(conference_name)
    plivo_response = plivo.XML.Response()

    if not room_exists:
        plivo_response.addHangup(reason="invalid conference")
        response = make_response(render_template('response_template.xml', response=plivo_response))
        response.headers['content-type'] = 'text/xml'
        return response

    plivo_response.addWait(length=2)
    plivo_response.addSpeak(config.CONFERENCE_ANNOUNCEMENT)
    wait_sound_url = url_for('conf_music', _external=True)

    plivo_response.addConference(conference_name,
                        enterSound="beep:1",
                        exitSound="beep:2",
                        waitSound=wait_sound_url,
                        )
    response = make_response(render_template('response_template.xml', response=plivo_response))
    response.headers['content-type'] = 'text/xml'
    return response
Esempio n. 3
0
def get_ssh_key():
    """
    Gets host key

    """
    rds = utils.get_redis_connection()
    return rds.get(SSH_KEY_KEY)
Esempio n. 4
0
def get_ssh_user():
    """
    Gets host user

    """
    rds = utils.get_redis_connection()
    return rds.get(SSH_USER_KEY)
Esempio n. 5
0
def create_reset_code(username=None):
    code = ''.join(Random().sample(string.letters + string.digits, 24))
    rds = get_redis_connection()
    key = RESET_CODE_KEY.format(code)
    rds.set(key, username)
    rds.expire(key, getattr(config, 'RESET_CODE_TTL', 3600))
    return code
Esempio n. 6
0
def get_user_from_code(code=None):
    rds = get_redis_connection()
    key = RESET_CODE_KEY.format(code)
    user = None
    if key:
        user = db.get_user(rds.get(key))
    return user
Esempio n. 7
0
def get_hosts():
    """
    Gets all hosts

    """
    rds = utils.get_redis_connection()
    return rds.smembers(HOST_KEY)
Esempio n. 8
0
def conference(conference_name):
    """
    Returns the HTML page for a particular conference name. The HTML page 
    uses the Plivo WebSDK to register to Plivo and make calls.
    """

    if conference_exists(conference_name):
        redis_conn = get_redis_connection()
        endpoint_username = redis_conn.hget(conference_name, 'username')
        endpoint_password = redis_conn.hget(conference_name, 'password')
        inbound_did = redis_conn.hget(conference_name, 'inbound_did')

        conference_url = url_for('conference',
                                 _external=True,
                                 conference_name=conference_name)

        data = {
            'endpoint_username': endpoint_username,
            'endpoint_password': endpoint_password,
            'inbound_did': inbound_did,
            'conference_name': conference_name,
            'conference_url': conference_url,
        }

        if request.query_string == 'share':
            template_name = 'conference_share.html'
        else:
            template_name = 'conference.html'

        response = make_response(render_template(template_name, response=data))
        return response
    return render_template('404.html')
Esempio n. 9
0
def create_reset_code(username=None):
    code = "".join(Random().sample(string.letters + string.digits, 24))
    rds = get_redis_connection()
    key = RESET_CODE_KEY.format(code)
    rds.set(key, username)
    rds.expire(key, getattr(config, "RESET_CODE_TTL", 3600))
    return code
Esempio n. 10
0
def get_hosts():
    """
    Gets all hosts

    """
    rds = utils.get_redis_connection()
    return rds.smembers(HOST_KEY)
Esempio n. 11
0
def conf(conference_name):
    """
    Renders the XML to start a conference based on the conference name
    it receives. It checks if the conference exists in our memory (to make
    sure it hasn't expired). 

    This URL is passed as the Answer URL to Plivo. When the call gets
    answered, the call will be put into a conference.
    """

    redis_conn = get_redis_connection()
    room_exists = redis_conn.exists(conference_name)
    plivo_response = plivo.XML.Response()

    if not room_exists:
        plivo_response.addHangup(reason="invalid conference")
        response = make_response(
            render_template('response_template.xml', response=plivo_response))
        response.headers['content-type'] = 'text/xml'
        return response

    plivo_response.addWait(length=2)
    plivo_response.addSpeak(config.CONFERENCE_ANNOUNCEMENT)
    wait_sound_url = url_for('conf_music', _external=True)

    plivo_response.addConference(
        conference_name,
        enterSound="beep:1",
        exitSound="beep:2",
        waitSound=wait_sound_url,
    )
    response = make_response(
        render_template('response_template.xml', response=plivo_response))
    response.headers['content-type'] = 'text/xml'
    return response
Esempio n. 12
0
    def get_all(cls, offset=0, count=-1):

        # If we want all then always is -1 if not, then we need to set the start
        #and finish for redis. But we ask for the start and how many elements
        #we want to retrieve (included the start element) so, if we start in the
        #10 and we want 3 then thsi would be 10, 11, 12 but if we set 13 to the
        #upper limit in redis then we obtain 4 so we rest one
        if count != -1:
            count -= 1

        messages = []

        r = utils.get_redis_connection()
        get_msgs = r.register_script(RMessage.LUA_RETRIEVE)

        result = get_msgs(
            keys=[
                RMessage.MESSAGES_KEY,
            ],
            args=[
                offset,
                offset + count
            ]
        )

        for i in result:
            # Map fields to attrs
            msg = RMessage(None, None, None)
            for j in range(0, len(i), 2):
                # Little hack(Dont want to set default attrs to the constructor)
                setattr(msg, i[j], i[j+1])
            messages.append(msg)

        return messages
Esempio n. 13
0
def get_ssh_user():
    """
    Gets host user

    """
    rds = utils.get_redis_connection()
    return rds.get(SSH_USER_KEY)
Esempio n. 14
0
def get_ssh_key():
    """
    Gets host key

    """
    rds = utils.get_redis_connection()
    return rds.get(SSH_KEY_KEY)
Esempio n. 15
0
def get_user_from_code(code=None):
    rds = get_redis_connection()
    key = RESET_CODE_KEY.format(code)
    user = None
    if key:
        user = db.get_user(rds.get(key))
    return user
Esempio n. 16
0
def conference(conference_name):
    """
    Returns the HTML page for a particular conference name. The HTML page 
    uses the Plivo WebSDK to register to Plivo and make calls.
    """
    
    if conference_exists(conference_name):
        redis_conn = get_redis_connection()
        endpoint_username = redis_conn.hget(conference_name, 'username')
        endpoint_password = redis_conn.hget(conference_name, 'password')
        inbound_did = redis_conn.hget(conference_name, 'inbound_did')

        conference_url = url_for('conference', _external=True, conference_name=conference_name)

        data = {
                'endpoint_username': endpoint_username, 
                'endpoint_password': endpoint_password,
                'inbound_did': inbound_did,
                'conference_name': conference_name,
                'conference_url': conference_url,
                }

        if request.query_string == 'share':
            template_name = 'conference_share.html'
        else:
            template_name = 'conference.html'

        response = make_response(render_template(template_name, response=data))
        return response
    return render_template('404.html')
 def test_delete_user_code(self):
     rds = utils.get_redis_connection()
     user = self._create_user()
     self.assertEqual(user.get('username'), self.test_user_username)
     code = accounts.create_reset_code(self.test_user_username)
     self.assertNotEqual(code, None)
     accounts.delete_reset_code(code)
     self.assertEqual(rds.get(accounts.RESET_CODE_KEY.format(code)), None)
Esempio n. 18
0
def add_host(hostname=None):
    """
    Adds a host

    :param hostname: Hostname

    """
    rds = utils.get_redis_connection()
    return rds.sadd(HOST_KEY, hostname)
Esempio n. 19
0
def delete_user(username=None):
    """
    Deletes a user

    :param username: Username to delete

    """
    rds = get_redis_connection()
    return rds.delete(USER_KEY.format(username))
Esempio n. 20
0
def add_results(key=None, text=''):
    """
    Stores (appends) result output

    :param key: Key (for retrieval)

    """
    rds = get_redis_connection()
    return rds.append(RESULT_KEY.format(key), text)
Esempio n. 21
0
def delete_host(hostname=None):
    """
    Deletes a host

    :param hostname: Hostname

    """
    rds = utils.get_redis_connection()
    return rds.srem(HOST_KEY, hostname)
Esempio n. 22
0
def get_job_status(job_id=None):
    """
    Gets an RQ job status

    :param job_id: Job ID

    """
    rds = get_redis_connection()
    return rds.hget(RQ_JOB_KEY.format(job_id), 'status')
Esempio n. 23
0
def get_results(key=None):
    """
    Gets result output

    :param key: Command key

    """
    rds = get_redis_connection()
    return rds.get(RESULT_KEY.format(key))
Esempio n. 24
0
def conference_exists(conference_name):
    """
    Checks if the conference has been created and exists in memory

    Returns True/False
    """

    redis_conn = get_redis_connection()
    return redis_conn.exists(conference_name)
Esempio n. 25
0
def delete_host(hostname=None):
    """
    Deletes a host

    :param hostname: Hostname

    """
    rds = utils.get_redis_connection()
    return rds.srem(HOST_KEY, hostname)
Esempio n. 26
0
def add_host(hostname=None):
    """
    Adds a host

    :param hostname: Hostname

    """
    rds = utils.get_redis_connection()
    return rds.sadd(HOST_KEY, hostname)
Esempio n. 27
0
def conference_exists(conference_name):
    """
    Checks if the conference has been created and exists in memory

    Returns True/False
    """

    redis_conn = get_redis_connection()
    return redis_conn.exists(conference_name)
Esempio n. 28
0
def get_job_status(job_id=None):
    """
    Gets an RQ job status

    :param job_id: Job ID

    """
    rds = get_redis_connection()
    return rds.hget(RQ_JOB_KEY.format(job_id), 'status')
Esempio n. 29
0
def add_results(key=None, text=''):
    """
    Stores (appends) result output

    :param key: Key (for retrieval)

    """
    rds = get_redis_connection()
    return rds.append(RESULT_KEY.format(key), text)
Esempio n. 30
0
def delete_user(username=None):
    """
    Deletes a user

    :param username: Username to delete

    """
    rds = get_redis_connection()
    return rds.delete(USER_KEY.format(username))
Esempio n. 31
0
def get_results(key=None):
    """
    Gets result output

    :param key: Command key

    """
    rds = get_redis_connection()
    return rds.get(RESULT_KEY.format(key))
Esempio n. 32
0
def link_conference(conference_name, endpoint_username, endpoint_password, inbound_did=None):
    """
    Store the conference name in memory along with
    endpoint username and password associated with it.
    """

    redis_conn = get_redis_connection()
    redis_conn.hmset(conference_name, {'username': endpoint_username, 'password': endpoint_password, 'inbound_did': inbound_did})
    if config.EXPIRE_CONFERENCE:
        redis_conn.expire(conference_name, 24*60*60)
Esempio n. 33
0
def get_users():
    """
    Returns all users

    """
    rds = get_redis_connection()
    users = []
    user_keys = rds.keys(USER_KEY.format('*'))
    [users.append(json.loads(rds.get(x))) for x in user_keys]
    return users
Esempio n. 34
0
def link_conference(conference_name, endpoint_username, endpoint_password, inbound_did=None):
    """
    Store the conference name in memory along with
    endpoint username and password associated with it.
    """

    redis_conn = get_redis_connection()
    redis_conn.hmset(conference_name, {'username': endpoint_username, 'password': endpoint_password, 'inbound_did': inbound_did})
    if config.EXPIRE_CONFERENCE:
        redis_conn.expire(conference_name, 24*60*60)
Esempio n. 35
0
def get_users():
    """
    Returns all users

    """
    rds = get_redis_connection()
    users = []
    user_keys = rds.keys(USER_KEY.format('*'))
    [users.append(json.loads(rds.get(x))) for x in user_keys]
    return users
Esempio n. 36
0
def get_user(username=None):
    """
    Returns a user object from the datastore

    :param username: Username

    """
    rds = get_redis_connection()
    data = rds.get(USER_KEY.format(username))
    if data:
        data = json.loads(data)
    return data
Esempio n. 37
0
def get_user(username=None):
    """
    Returns a user object from the datastore

    :param username: Username

    """
    rds = get_redis_connection()
    data = rds.get(USER_KEY.format(username))
    if data:
        data = json.loads(data)
    return data
Esempio n. 38
0
def set_ssh_key(key=None):
    """
    Sets host key

    :param key: SSH private key (as text)

    """
    rds = utils.get_redis_connection()
    ret = None
    if key:
        ret = rds.set(SSH_KEY_KEY, key)
    return ret
Esempio n. 39
0
def set_ssh_user(username=None):
    """
    Sets host username

    :param username: SSH username

    """
    rds = utils.get_redis_connection()
    ret = None
    if username:
        ret = rds.set(SSH_USER_KEY, username)
    return ret
Esempio n. 40
0
def set_ssh_user(username=None):
    """
    Sets host username

    :param username: SSH username

    """
    rds = utils.get_redis_connection()
    ret = None
    if username:
        ret = rds.set(SSH_USER_KEY, username)
    return ret
Esempio n. 41
0
def set_ssh_key(key=None):
    """
    Sets host key

    :param key: SSH private key (as text)

    """
    rds = utils.get_redis_connection()
    ret = None
    if key:
        ret = rds.set(SSH_KEY_KEY, key)
    return ret
Esempio n. 42
0
def log(data={}):
    """
    Logs item to DB

    :param data: Log data as dict

    """
    if not isinstance(data, dict):
        data = {'log': data}
    data['date'] = int(time.time())
    rds = get_redis_connection()
    return rds.lpush(LOG_KEY, json.dumps(data))
Esempio n. 43
0
def log(data={}):
    """
    Logs item to DB

    :param data: Log data as dict

    """
    if not isinstance(data, dict):
        data = {'log': data}
    data['date'] = int(time.time())
    rds = get_redis_connection()
    return rds.lpush(LOG_KEY, json.dumps(data))
Esempio n. 44
0
    def get(self, n=10):
        """
        returns the top ten products added to customer carts
        """
        try:
            N = int(n)
        except ValueError:
            return jsonify({"error": "N shoud be integer"})

        store = Store.objects.filter(app_id=request.headers.get('APP-ID'),
                                     deleted_at=None).first()

        redis_conn = get_redis_connection()

        response = json.loads(redis_conn.get(TOP_TEN_CART_ITEMS))

        product_ids = {}
        counter = 0
        for key, value in sorted(response.items(),
                                 key=lambda x: x[1],
                                 reverse=True):
            split_values = key.split("|")
            if split_values[1] == store.store_id:
                product_ids[split_values[0]] = value
            counter += 1
            if counter == N:
                break

        products = Product.objects.filter(product_id__in=product_ids.keys())

        products = products.paginate(page=1, per_page=N)

        response = {"result": "ok", "products": products_obj(products)}

        for product in response["products"]:
            for key, value in product_ids.items():
                if product["product_id"] == key:
                    product["number_of_cart_adds"] = value

        response["products"] = sorted(
            response["products"],
            key=lambda product: product["number_of_cart_adds"],
            reverse=True)

        return jsonify(response), 200
Esempio n. 45
0
def create_user(username=None, password='', email=None, is_admin=False):
    """
    Creates a new user

    :param username: Username of user
    :param password: User password
    :param email: User email
    :param is_admin: Admin user

    """
    rds = get_redis_connection()
    data = {
        'username': username,
        'password': utils.hash_text(password),
        'email': email,
        'is_admin': is_admin,
    }
    return rds.set(USER_KEY.format(username), json.dumps(data))
Esempio n. 46
0
    def save(self):
        r = utils.get_redis_connection()
        save_msg = r.register_script(RMessage.LUA_SAVE)

        result = save_msg(
            keys=[
                RMessage.MESSAGES_KEY,
                RMessage.MESSAGE_KEY.format(self.id)
            ],
            args=[
                self.id,
                self.message,
                self.by,
                self.to,
                self.date
            ]
        )
        return result
Esempio n. 47
0
def create_user(username=None, password='', email=None, is_admin=False):
    """
    Creates a new user

    :param username: Username of user
    :param password: User password
    :param email: User email
    :param is_admin: Admin user

    """
    rds = get_redis_connection()
    data = {
        'username': username,
        'password': utils.hash_text(password),
        'email': email,
        'is_admin': is_admin,
    }
    return rds.set(USER_KEY.format(username), json.dumps(data))
Esempio n. 48
0
def results_by_store_id(request, topic_name):
    """
    helper function to return a redis cached result by store_id

    :param request: flask request object
    :return: response object
    """
    store = Store.objects.filter(app_id=request.headers.get('APP-ID'),
                                 deleted_at=None).first()

    redis_conn = get_redis_connection()

    redis_response = json.loads(redis_conn.get(topic_name))

    try:
        result = redis_response[store.store_id]
    except KeyError:
        result = 0

    return {"result": result}
Esempio n. 49
0
def update_user(username=None, data={}):
    """
    Updates a user with the specified data

    :param username: Username to update
    :param data: Data to update as a dict

    """
    rds = get_redis_connection()
    user_data = rds.get(USER_KEY.format(username))
    ret = None
    if user_data:
        user = json.loads(user_data)
        for k, v in data.iteritems():
            # hash password if present
            if k == 'password':
                v = utils.hash_text(v)
            user[k] = v
        ret = rds.set(USER_KEY.format(username), json.dumps(user))
    return ret
Esempio n. 50
0
def update_user(username=None, data={}):
    """
    Updates a user with the specified data

    :param username: Username to update
    :param data: Data to update as a dict

    """
    rds = get_redis_connection()
    user_data = rds.get(USER_KEY.format(username))
    ret = None
    if user_data:
        user = json.loads(user_data)
        for k,v in data.iteritems():
            # hash password if present
            if k == 'password':
                v = utils.hash_text(v)
            user[k] = v
        ret = rds.set(USER_KEY.format(username), json.dumps(user))
    return ret
Esempio n. 51
0
 def tearDown(self):
     rds = utils.get_redis_connection()
     rds.flushdb()
Esempio n. 52
0
def publish(msg=None):
    rds = get_redis_connection()
    rds.publish(config.REDIS_PUBSUB_CHANNEL, msg)
Esempio n. 53
0
def delete_reset_code(code=None):
    rds = get_redis_connection()
    key = RESET_CODE_KEY.format(code)
    return rds.delete(key)
Esempio n. 54
0
def publish(msg=None):
    rds = get_redis_connection()
    rds.publish(config.REDIS_PUBSUB_CHANNEL, msg)
 def tearDown(self):
     rds = utils.get_redis_connection()
     rds.flushdb()
Esempio n. 56
0
def delete_reset_code(code=None):
    rds = get_redis_connection()
    key = RESET_CODE_KEY.format(code)
    return rds.delete(key)
Esempio n. 57
0
 def count(cls):
     r = utils.get_redis_connection()
     return r.llen(RMessage.MESSAGES_KEY)