Пример #1
0
 def form_valid(self, form):
     message = form.cleaned_data.get('message')
     chatroom = form.cleaned_data.get('chatroom')
     name = form.cleaned_data.get('name')
     p = pusher.pusher_from_url()
     if p[chatroom].trigger('new-message', {'id': '1', 'name': name, 'message': message}):
         return http.HttpResponse('Ok')
     return self.form_invalid(form=form)
Пример #2
0
def event(request, access_token):
    if not request.is_ajax():
        return HttpResponseBadRequest()
    if not request.method == 'POST':
        return HttpResponseBadRequest()

    def get_unsaved_bids(experiement, key):
        # return current unsaved bids
        unsaved_bids = r.hgetall(key)
        # experiment doesn't exist
        if not unsaved_bids:
            unsaved_bids = {item: '0' for
                     item in experiment.items.values_list('name', flat=True)}
            r.hmset(key, unsaved_bids)
            r.expire(key, 3600)
        return unsaved_bids

    session = get_object_or_404(Session, access_token=access_token)
    experiment = session.experiment
    exp_key = experiment.short_name

    if not experiment.is_active() or session.has_completed:
        return HttpResponseNotAllowed()

    p = pusher.pusher_from_url(url=settings.PUSHER_URL)
    r = redis.from_url(settings.REDIS_URL)

    data = json.loads(request.POST['data'])
    event = data['event']
    if event == 'new-participant':
        session.events.create(event_type='exp_started', data=data)
        return HttpResponse(json.dumps({'result': get_unsaved_bids(experiment, exp_key)}),
                            content_type='application/javascript')
    elif event == 'item-bid':
        # update item bid, then trigger event
        item = data['item']
        bid = data['bid']
        if r.exists(exp_key):
            # may result in negative values; handle it client-side
            r.hincrby(exp_key, item, 1 if bid else -1)
            r.expire(exp_key, 3600)
        else:
            unsaved_bids = get_unsaved_bids(experiment, exp_key)
            unsaved_bids[item] = 1 if bid else 0
            r.hmset(exp_key, unsaved_bids)

        session.events.create(event_type='item_bid' if bid else 'item_unbid',
                              data=data)
        p[exp_key].trigger('item-bid', data)
        return HttpResponse(json.dumps({'result': True}),
                            content_type='application/javascript')

    return HttpResponseBadRequest()
Пример #3
0
# -*- coding: utf-8 -*-
import os
from flask import Blueprint, request, jsonify, current_app
from flask.ext.login import current_user

from pusher import pusher_from_url

pusher = pusher_from_url(os.getenv('PUSHER_URL'))
notification = Blueprint('pusher', __name__, template_folder='templates')


@notification.route('/pusher/auth', methods=['POST'])
def auth():
    channel_name = request.form['channel_name']
    socket_id = request.form['socket_id']

    return jsonify(pusher[channel_name].authenticate(
        socket_id, dict(email=current_user.email,
                        user_id=str(current_user.id))))


@notification.route('/pusher/presence', methods=['POST'])
def presence():
    current_app.logger.info(request.json)
    return ''
Пример #4
0
import os, time
import web, pusher
import courier, simplethread

REPO_STORAGE = '/tmp/dudley_repo'
NOW = web.sqlliteral('now()')
pushcloud = pusher.pusher_from_url()
env = web.storage(os.environ)
buildqueue = simplethread.Queue()

def watchdb(db):
    while 1:
        try: buildqueue.get(timeout=60)
        except simplethread.Empty: pass
        for job in db.select('jobs', where="builder is null and done='f'"):
            simplethread.spawn(lambda: start_build(db, job))

def get_buildserver(db, build_id):
    buildservers = db.select('buildservers', where="building is null", limit=1).list()
    if buildservers and db.update('buildservers', building=build_id, where="building is null and id=$buildservers[0].id", vars=locals()):
        return buildservers[0]
    else:
        return False

def claim_job(db, job_id, build_id):
    return db.update('jobs', builder=build_id, where="id=$job_id and builder is null", vars=locals())

def start_build(db, job):
    build_id = db.insert('builds', job_id=job.id, updated_at=NOW)
    if not claim_job(db, job.id, build_id):
        # someone else is already building this job
Пример #5
0
import json

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.views.decorators.http import require_POST

import pusher


p = pusher.pusher_from_url()


def json_response(data):
    return HttpResponse(json.dumps(data), content_type='application/json')


@login_required
@require_POST
def auth(request):
    channel = request.POST.get('channel_name')
    socket_id = request.POST.get('socket_id')

    # We could check permissions here to see if the user should have access to
    # a certain channel.

    auth = p[channel].authenticate(socket_id)
    return json_response(auth)


@login_required
@require_POST
Пример #6
0
from pymongo import Connection
from flask import Flask
from flask import render_template

MONGO_URL = os.environ.get('MONGOHQ_URL')
PUSHER_URL = os.environ.get('PUSHER_URL')

# check to see if the MONGO_URL exists, otherwise just connect locally
if MONGO_URL:
    connection = Connection(MONGO_URL)
    db = connection[urlparse.urlparse(MONGO_URL).path[1:]]
else:
    connection = Connection('localhost', 27017)
    db = connection['home_automation']
if PUSHER_URL:
    p = pusher.pusher_from_url()
else:
    p = pusher.Pusher(app_id=os.environ.get('PUSHER_APP_ID'),
                      key=os.environ.get('PUSHER_KEY'),
                      secret=os.environ.get('PUSHER_SECRET'))

app = Flask(__name__, template_folder='static/templates')


@app.route('/')
def index():
    weather_data = db.settings.find_one({'data': 'forecast_api'})['json']
    hvac_data = db.settings.find_one({'data': 'hvac'})['json']
    light_data = db.settings.find_one({'data': 'lights'})['light_list']
    settings = db.settings.find_one({'data': 'settings'})['json']
    return render_template('index.html',
Пример #7
0
import os, time
import web, pusher
import courier, simplethread

REPO_STORAGE = '/tmp/dudley_repo'
NOW = web.sqlliteral('now()')
pushcloud = pusher.pusher_from_url()
env = web.storage(os.environ)
buildqueue = simplethread.Queue()


def watchdb(db):
    while 1:
        try:
            buildqueue.get(timeout=60)
        except simplethread.Empty:
            pass
        for job in db.select('jobs', where="builder is null and done='f'"):
            simplethread.spawn(lambda: start_build(db, job))


def get_buildserver(db, build_id):
    buildservers = db.select('buildservers', where="building is null",
                             limit=1).list()
    if buildservers and db.update(
            'buildservers',
            building=build_id,
            where="building is null and id=$buildservers[0].id",
            vars=locals()):
        return buildservers[0]
    else: