Exemplo n.º 1
0
def api_friend_approve(request):
    api_result = {"api": "friend approve", "status": "success"}

    try:
        token = request.GET["token"]
        user = get_user_from_token(token)
        friend_id = request.GET["user_id"]
        decision = request.GET["decision"]

        try:
            existing_conn = Connection.objects.get(source_id=friend_id, target=user)
            if decision == "yes":
                existing_conn.pending = False
                existing_conn.save()
                rev_conn = Connection(source=user, target_id=friend_id, pending=False)
                rev_conn.save()
            else:
                existing_conn.delete()
        except Exception as e:
            api_result["status"] = "failure"
            api_result["error"] = e.message
            pass

    except Exception as e:
        api_result["status"] = "failure"
        api_result["error"] = e.message
        pass

    return JsonResponse(api_result)
Exemplo n.º 2
0
def login(redirect_after=None):
    jwt = request.args.get("jwt", False)
    if not jwt:
        return force_auth()
    r = registry_request("/auth/profile.json", jwt)
    try:
        profile = r.json()
        conn = Connection()
        conn.token = b64encode(urandom(30))[:30]
        conn.logged_in = datetime.datetime.now()
        conn.last_click = conn.logged_in
        conn.remote_addr = request.remote_addr
        conn.user_id = profile["person"]["id"]
        conn.name = profile["person"]["name"]
        conn.profile = r.text
        conn.jwt = jwt
        db.session.add(conn)
        db.session.commit()
        session["conn_id"] = conn.id
        session["conn_token"] = conn.token
        if redirect_after:
            return redirect(b64decode(redirect_after))
        return redirect(url_for("index"))
    except:
        raise
        return force_auth()
Exemplo n.º 3
0
def up():
    for item in seed:
        connection = Connection(**item["init"])

        if item["approve"]:
            connection.approve()

        db.session.add(connection)

    db.session.commit()
Exemplo n.º 4
0
 def save_conn(self, request):
     form = AddConnectionForm(request)
     if form.is_valid():
         print "Form valid"
         instance = form.save(commit=False)
         new_conn = Connection(source=instance.source,
                               destination=instance.destination)
         print new_conn.id
         new_conn.save()
         print new_conn.id
Exemplo n.º 5
0
def login(redirect_after=None):
    jwt = request.args.get("jwt", False)
    if not jwt:
        return force_auth()
    r = registry_request("/auth/profile.json", jwt)
    try:
        profile = r.json()
        conn = Connection()
        conn.token = b64encode(urandom(30))[:30]
        conn.logged_in = datetime.datetime.now()
        conn.last_click = conn.logged_in
        conn.remote_addr = request.remote_addr
        conn.user_id = profile["person"]["id"]
        conn.name = profile["person"]["name"]
        conn.profile = r.text
        conn.jwt = jwt
        db.session.add(conn)
        db.session.commit()
        session["conn_id"] = conn.id
        session["conn_token"] = conn.token
        if redirect_after:
            return redirect(b64decode(redirect_after))
        return redirect(url_for("index"))
    except:
        raise
        return force_auth()
Exemplo n.º 6
0
def connectionWizard(request, step):
    render = {}
    step = int(step)
    if step == 1:
        if request.method == 'GET':
            render['form'] = ConnectionStep1Wizard()
            render['form'].fields['teacher'].queryset = Teacher.objects.filter(grades = request.user.grade)
            return render_to_response('curatorship/connectionWizard.html', render, context_instance = RequestContext(request))
        else:
            render['form'] = ConnectionStep1Wizard(request.POST)
            if render['form'].is_valid():
                request.session['teacher'] = render['form'].cleaned_data['teacher']
                if request.session['teacher'].subjects.count()==1:
                    request.session['subject'] = request.session['teacher'].subjects.all()[0]
                    return HttpResponseRedirect('/curatorship/connections/wizard/3/')
                return HttpResponseRedirect('/curatorship/connections/wizard/2/')
            else:
                render['form'].fields['teacher'].queryset = Teacher.objects.filter(grades = request.user.grade)
                return render_to_response('curatorship/connectionWizard.html', render, context_instance = RequestContext(request))
    if step == 2:
        if request.method == 'GET':
            render['form'] = ConnectionStep2Wizard()
            render['form'].fields['subject'].queryset = request.session['teacher'].subjects
            return render_to_response('curatorship/connectionWizard.html', render, context_instance = RequestContext(request))
        else:
            render['form'] = ConnectionStep2Wizard(request.POST)
            if render['form'].is_valid():
                request.session['subject'] = render['form'].cleaned_data['subject']
                return HttpResponseRedirect('/curatorship/connections/wizard/3')
            else:
                render['form'].fields['subject'].queryset = Subject.objects.filter(teacher = request.session['teacher'])
                return render_to_response('curatorship/connectionWizard.html', render, context_instance = RequestContext(request))
    if step == 3:
        if request.method == 'GET':
            render['form'] = ConnectionStep3Wizard()
            return render_to_response('curatorship/connectionWizard.html', render, context_instance = RequestContext(request))
        else:
            render['form'] = ConnectionStep3Wizard(request.POST)
            if render['form'].is_valid():
                connection = Connection(teacher = request.session['teacher'],
                                        subject = request.session['subject'],
                                        grade = request.user.grade,
                                        connection = render['form'].cleaned_data['connection'])
                connection.save()
                del request.session['teacher']
                del request.session['subject']
                return HttpResponseRedirect('/curatorship/connections/')
            else:
                return render_to_response('curatorship/connectionWizard.html', render, context_instance = RequestContext(request))
Exemplo n.º 7
0
def get_connection_list_for_device(device_id):
    result = [{
        "id": c.id,
        "deviceId": c.device_id,
        "topic": c.topic
    } for c in Connection.select().where(Connection.device_id == int(device_id))]
    return json.dumps(result, ensure_ascii=False)
Exemplo n.º 8
0
    def get(self):
        oauth_token = self.request.get("oauth_token", None)
        oauth_verifier = self.request.get("oauth_verifier", None)
        if oauth_token is None:
            # Invalid request!
            self.response.out.write(template.render('error.html', {
                    'message': 'Missing required parameters!'
            }))
            return

        # Lookup the request token
        connector = Connection.gql("WHERE token_key=:key", key=oauth_token).get()
        if connector is None:
            # We do not seem to have this request token, show an error.
            self.response.out.write(template.render('error.html', {'message': 'Invalid token!'}))
            return

        # Rebuild the auth handler
        auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
        auth.set_request_token(connector.token_key, connector.token_secret)

        # Fetch the access token
        try:
            auth.get_access_token(oauth_verifier)
            api = tweepy.API(auth_handler=auth, secure=True, retry_count=3)
            connector.twitterName = api.me().screen_name
        except tweepy.TweepError, e:
            # Failed to get access token
            self.response.out.write(template.render('templates/error.html', {'message': e}))
            return
Exemplo n.º 9
0
    def post(self):
        oauth_token = self.request.get('oauth_token')
        oauth_verifier = self.request.get('oauth_verifier')

        justOne = self.request.get('submitType') == 'Tweet this'
        linkThem = self.request.get('submitType') == 'Tweet this, and tweet future entries!'
        
        connector = Connection.gql("WHERE token_key=:key and verifier=:verifier", key=oauth_token, verifier=oauth_verifier).get()

        (title, link, id) = feedreader.getLatestEntry(connector.atomUrl)

        if justOne:
            if id not in connector.entryIdsThatHaveBeenTweeted:
                tweet = tweetwriter.makeTweet(title, link, connector.tweetTemplate)        

                # Rebuild the auth handler
                auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
                auth.set_access_token(connector.access_token_key, connector.access_token_secret)

                api = tweepy.API(auth_handler=auth, secure=True, retry_count=3)
                api.update_status(tweet)
                
                self.response.out.write(template.render('templates/tweetingout.html', {'tweet' : tweet }))
            else:
                self.response.out.write(template.render('templates/alreadytweeted.html', {}))
        else:
            entryIds = feedreader.getAllEntryIds(connector.atomUrl)
            connector.entryIdsThatHaveBeenTweeted.extend(entryIds)
            connector.enabled = True
            connector.put()
            self.response.out.write(template.render('templates/setupcomplete.html', {}))
    
        connector.enabled = linkThem
        connector.put()
Exemplo n.º 10
0
def add_device():
    # Attributes can be null
    name = request.form['name']
    dcode = request.form['dcode']
    secret = request.form['secret']
    device_type = request.form['type']
    description = request.form['description']
    # Attributes cannot be null
    ip = request.form['ip']
    port = request.form['port']
    topic = request.form['topic']
    device = Device.create(name=name,
                           dcode=dcode,
                           secret=secret,
                           type=device_type,
                           ip=ip,
                           port=port,
                           description=description)
    device.save()
    for s in topic.split(";"):
        Connection.create(device_id=device.id, topic=s.strip()).save()
    RuleEngine.add_client(device)
    response = {'status': 1, 'msg': "添加成功"}
    return json.dumps(response, ensure_ascii=False)
Exemplo n.º 11
0
    def post(self):
        """
        Create a new network connection
        """

        if "Administrator" != current_user.role:
            return make_response(jsonify({"msg": "Forbidden"}), 403)

        id = request.json.get("id")
        direction = request.json.get("direction")
        organization_A = request.json.get("organization_A")
        organization_B = request.json.get("organization_B")
        server_group_A = request.json.get('server_group_A')
        server_group_B = request.json.get('server_group_B')
        network_id = request.json.get('network_id')

        connection = Connection.query.filter_by(direction=direction,
                                                organization_A=organization_A,
                                                organization_B=organization_B,
                                                server_group_A=server_group_A,
                                                server_group_B=server_group_B,
                                                network_id=network_id).first()

        if not connection:  # If that connection doesn't already exists, then we can create a new one
            connection = Connection(id=id,
                                    direction=direction,
                                    organization_A=organization_A,
                                    organization_B=organization_B,
                                    server_group_A=server_group_A,
                                    server_group_B=server_group_B,
                                    network_id=network_id)
            db.session.add(connection)
            db.session.commit()
            ret = {'msg': 'Success'}
            return make_response(jsonify(ret), 200)

        else:
            return make_response(
                jsonify({
                    "msg":
                    "Unable to add connection. That connection already exists"
                }), 400)
Exemplo n.º 12
0
def get_all_device():
    result = []
    for device in Device.select():
        topics = [
            c.topic for c in Connection.select().where(
                Connection.device_id == device.id)
        ]
        result.append({
            "id": device.id,
            "name": device.name,
            "dcode": device.dcode,
            "secret": device.secret,
            "type": device.type,
            "description": device.description,
            "ip": device.ip,
            "port": device.port,
            "topic": ";".join(topics),
            "status": "已连接" if query_status(device.name) else "未连接"
        })
    return json.dumps(result)
Exemplo n.º 13
0
from earnings_grab import get_earning_data
from models import Connection
from datetime import date, datetime, timedelta
import pandas as pd
from pandas.tseries.offsets import BDay
import sqlite3
from models import Connection
import pandas_datareader.data as web
conn, c = Connection()


def get_data(df, minpx, maxpx, maxvol):
    # df = pd.read_sql('''SELECT stockid,date from stockDataTable''',conn,index_col='stockid')
    df = df[(df['price'] > minpx) & (df['price'] < maxpx) &
            (df['volume'] < maxvol)]
    df2 = pd.read_sql('''SELECT stockid,earningsdate FROM earningsTable''',
                      conn)
    df3 = pd.read_sql('''SELECT date FROM marketTable''', conn)
    df3['date'], df2['earningsdate'], df['date'] = pd.DatetimeIndex(
        df3.date), pd.DatetimeIndex(
            df2.earningsdate).normalize(), pd.DatetimeIndex(
                df.date).normalize()
    df = df.set_index('stockid')
    fail_list = []
    df_final = pd.DataFrame()
    for i in df2['stockid'].unique().tolist():
        try:
            df_sub, df2_sub = df.ix[i], df2[df2['stockid'] == i]
            df_sub['Earning'] = df_sub['date'].isin(df2_sub['earningsdate'])
            df_final = df_final.append(df_sub)
        except:
def facebook_authorized(resp):
    next_url = request.args.get('next') or '/'
    if resp is None or 'access_token' not in resp:
        return redirect(next_url)

    session['facebook_token'] = (resp['access_token'], '')
    data = facebook.get('/me').data
    profile_picture = 'https://graph.facebook.com/' + data['id'] + '/picture?width=1000'
    # profile_picture = facebook.get('/me/picture').data

    if 'id' in data and 'name' in data and 'email' in data and 'link' in data:

        provider_user_id = data['id']
        name = data['name']
        username = data['username']
        user_email = data['email']
        profile_url = data['link']
        # profile_picture = profile_picture['url']

        generated_name = str(uuid.uuid1()) + '.jpg'

        user = User.query.filter(User.email == user_email).first()
        if not user:
            user = users.create_user(
                name=name,
                email=user_email,
                password=None,
                active=True
            )
            users.commit()

            current_user_id = str(user.id)
            folder_path = app.config['UPLOADS_FOLDER'] + '/user/' + current_user_id + '/'
            new_folder = os.path.dirname(folder_path)
            if not os.path.exists(new_folder):
                os.makedirs(new_folder)

            filepath = os.path.join(folder_path, generated_name)
            urllib.urlretrieve(profile_picture, filepath)

            new_photo = 'user/' + current_user_id + '/' + generated_name

            User.query.filter(User.id == user.id).update({User.photo: new_photo})

        connection = Connection.query.filter(Connection.user_id == user.id,
                                             Connection.provider_id == 'facebook').first()
        if not connection:
            print "no prior connection"
            connection = Connection(
                user=user,
                provider_id='facebook',
                provider_user_id=provider_user_id,
                access_token=resp['access_token'],
                profile_url=profile_url,
                image_url=generated_name,
                full_name=name,
                display_name=username
            )
            db.session.add(connection)
            db.session.commit()
        else:
            print "updating prior connection"
            connection.access_token = resp['access_token']
            db.session.commit()

        if connection and login_user(user):
            users.commit()
            return redirect(next_url)

    return redirect("/login")
Exemplo n.º 15
0
def post():
    approver_id = request.json.get("approver_id")

    # find existing approver user and/or existing connection
    approver = User.query.get(approver_id)
    existing_connection = Connection.query.filter(
        or_(
            and_(Connection.requestor_id == approver_id,
                 Connection.approver_id == current_user.id),
            and_(Connection.approver_id == approver_id,
                 Connection.requestor_id == current_user.id))).first()

    # handle requests for non-existent approvers
    if approver is None or approver.is_deleted:
        raise BadRequest(
            response={
                "notification": {
                    "body":
                    "The user you requested to connect with doesn't exist.",
                    "type": "popup",
                    "duration": 4,
                },
            })

    # In the case of an existing, active connection we'll send the client a
    # reminder that they are already connected to this user.
    if existing_connection and not existing_connection.is_deleted:
        raise BadRequest(
            response={
                "notification": {
                    "body": "You are already connected with this user.",
                    "type": "popup",
                    "duration": 3,
                },
            })

    # If the route compiles to this point then it means we're either
    # creating or restoring a connection. Either way, a notification must
    # be sent to the approver.
    elif existing_connection:
        connection = existing_connection
        connection.rejoin(current_user.id)

        status_code = 200

    else:
        connection = Connection(current_user.id, approver_id)

        db.session.add(connection)
        db.session.commit()

        status_code = 201

    notification = Notification()
    notification.recipient_id = approver.id
    notification.type = "bell_notification"
    notification.body = f"{current_user.first_name} {current_user.last_name} wants to connect with you."
    notification.action = f"/#/approvals/{connection.id}"

    db.session.add(notification)
    db.session.commit()

    # Emit a notification to the approver's user notifications channel.
    emit("receive_user_notification", {
        "data": connection.to_dict(approver_id),
        "notification": {
            "id": notification.id,
            "body": notification.body,
            "type": notification.type,
            "action": notification.action,
        }
    },
         room=f"user_notifications_{approver_id}")

    return jsonify({
        "data": connection.to_dict(current_user.id),
        "notification": {
            "body":
            f"A connection request has been sent to {approver.first_name}.",
            "type": "popup",
            "duration": 4,
        },
    }), status_code
Exemplo n.º 16
0
def facebook_authorized(resp):
    next_url = request.args.get('next') or '/'
    if resp is None or 'access_token' not in resp:
        return redirect(next_url)

    session['facebook_token'] = (resp['access_token'], '')
    data = facebook.get('/me').data
    profile_picture = 'https://graph.facebook.com/' + data[
        'id'] + '/picture?width=1000'
    # profile_picture = facebook.get('/me/picture').data

    if 'id' in data and 'name' in data and 'email' in data and 'link' in data:

        provider_user_id = data['id']
        name = data['name']
        username = data['username']
        user_email = data['email']
        profile_url = data['link']
        # profile_picture = profile_picture['url']

        generated_name = str(uuid.uuid1()) + '.jpg'

        user = User.query.filter(User.email == user_email).first()
        if not user:
            user = users.create_user(name=name,
                                     email=user_email,
                                     password=None,
                                     active=True)
            users.commit()

            current_user_id = str(user.id)
            folder_path = app.config[
                'UPLOADS_FOLDER'] + '/user/' + current_user_id + '/'
            new_folder = os.path.dirname(folder_path)
            if not os.path.exists(new_folder):
                os.makedirs(new_folder)

            filepath = os.path.join(folder_path, generated_name)
            urllib.urlretrieve(profile_picture, filepath)

            new_photo = 'user/' + current_user_id + '/' + generated_name

            User.query.filter(User.id == user.id).update(
                {User.photo: new_photo})

        connection = Connection.query.filter(
            Connection.user_id == user.id,
            Connection.provider_id == 'facebook').first()
        if not connection:
            print "no prior connection"
            connection = Connection(user=user,
                                    provider_id='facebook',
                                    provider_user_id=provider_user_id,
                                    access_token=resp['access_token'],
                                    profile_url=profile_url,
                                    image_url=generated_name,
                                    full_name=name,
                                    display_name=username)
            db.session.add(connection)
            db.session.commit()
        else:
            print "updating prior connection"
            connection.access_token = resp['access_token']
            db.session.commit()

        if connection and login_user(user):
            users.commit()
            return redirect(next_url)

    return redirect("/login")
Exemplo n.º 17
0
 def __init__(self):
     self.conn = Connection()
Exemplo n.º 18
0
 def setUp(self):
     Connection.create_table(fail_silently=True)
     a = Connection(from_url='A', to_url='B', count = 2, project = '')
     b = Connection(from_url='A', to_url='C', count = 9, project = '')
     c = Connection(from_url='C', to_url='D', count = 1, project = '')
     d = Connection(from_url='Q', to_url='A', count = 5, project = '')
     e = Connection(from_url='N', to_url='P', count = 1, project = '')
     f = Connection(from_url='P', to_url='X', count = 1, project = '')
     a.save()
     b.save()
     c.save()
     d.save()
     e.save()
     f.save()
Exemplo n.º 19
0
 def tearDown(self):
     q = Connection.delete()
     q.execute()