Exemplo n.º 1
0
def get_pi_info(uid):
    tags = []
    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        row = RasPi()
        row.uuid = uid
        row.url = "http://www.stackexchange.com"
        row.landscape = True
        row.lastseen = datetime.now()
        row.description = ""
        row.orientation = 0
        row.browser = True
        DBSession.add(row)
        DBSession.flush()
    else:
        try:
            tagset = DBSession.query(Tags).filter(Tags.uuid == uid).all()
            for tag in tagset:
                tags.append(tag.tag)
        except Exception:
            pass

    rowdict = row.get_dict()
    rowdict['tags'] = tags
    return rowdict
Exemplo n.º 2
0
def view_api_screenshot_save(request):
    uid = request.matchdict['uid']
    imgblob = request.POST['screenshot'].file

    '''first, delete previous screenshot'''
    DBSession.query(Screenshot).filter(Screenshot.uuid == uid).delete()

    '''Now, lets make a new screenshot'''
    foo = Screenshot()
    foo.uuid = uid
    foo.image = imgblob.read()
    DBSession.add(foo)
    DBSession.flush()
Exemplo n.º 3
0
def view_api_screenshot_save(request):
    uid = request.matchdict['uid']
    imgblob = request.POST['screenshot'].file

    '''first, delete previous screenshot'''
    DBSession.query(Screenshot).filter(Screenshot.uuid == uid).delete()

    '''Now, lets make a new screenshot'''
    foo = Screenshot()
    foo.uuid = uid
    foo.image = imgblob.read()
    DBSession.add(foo)
    DBSession.flush()
Exemplo n.º 4
0
def view_api_log_save(request):
    uid = request.matchdict['uid']
    pi_log = request.POST['pi_log']
    filename = request.POST['filename']
    DBSession.query(Logs).filter(
        Logs.uuid == uid).filter(
        Logs.filename == filename).delete()

    new_log = Logs()
    new_log.filename = filename
    new_log.uuid = uid
    new_log.log = pi_log
    DBSession.add(new_log)
    DBSession.flush()
Exemplo n.º 5
0
def view_api_log_save(request):
    uid = request.matchdict['uid']
    pi_log = request.POST['pi_log']
    filename = request.POST['filename']
    DBSession.query(Logs).filter(
        Logs.uuid == uid).filter(
        Logs.filename == filename).delete()

    new_log = Logs()
    new_log.filename = filename
    new_log.uuid = uid
    new_log.log = pi_log
    DBSession.add(new_log)
    DBSession.flush()
Exemplo n.º 6
0
def make_an_admin(request):
    email = request.matchdict['email']
    '''First, make sure there aren't already admins in the system'''
    res = DBSession.query(UserModel).filter(UserModel.AccessLevel == 2).first()
    if res != None:
        msg = "User already an admin: {user}".format(user=res.email)
        return False
    user = DBSession.query(UserModel).filter(UserModel.email == email).first()
    if user == None:
        user = UserModel()
        user.email = email
        DBSession.add(user)
    user.AccessLevel = 2
    DBSession.flush()
    return True
Exemplo n.º 7
0
def view_ajax_set_commands(request):
    uid = request.matchdict['uid']
    response = request.json_body

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return '{"status":"error"}'

    # convert response into something with stable sorting
    cmds = []
    tmpcmds = sorted(response.items(), key=operator.itemgetter(0))
    for tmptuple in tmpcmds:
        # extract cmdid/cmd
        cmdid = int(tmptuple[0])
        cmd = tmptuple[1]['cmd']
        del tmptuple[1]['cmd']

        # extract arguments
        tmpargs = sorted(tmptuple[1].items(), key=operator.itemgetter(0))
        args = [item[1] for item in tmpargs]

        # put into our cmd object in the correct order
        cmds.insert(cmdid, {})
        cmds[cmdid]['cmd'] = cmd
        cmds[cmdid]['args'] = args

        # command hasn't been run yet, so this is blank
        cmds[cmdid]['result'] = ''

    row.requested_commands = json.dumps(cmds)
    DBSession.flush()

    return str(cmds)
Exemplo n.º 8
0
def view_api_refresh_get(request):
    uid = request.matchdict['uid']

    refresh_cmd={}
    refresh_cmd['cmd']='su'
    refresh_cmd['args']=['-c','/home/pi/refresh.sh','pi']
    refresh_cmd['result']=''


    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    try:
        # If there are already records to be run,
        # we'll start with them in the array already
        cmd_data = json.loads(row.requested_commands)
    except (ValueError, TypeError):
        cmd_data=[]
        pass

    cmd_data.append(refresh_cmd)

    row.requested_commands = json.dumps(cmd_data)
    DBSession.flush()

    return {'status': 'OK'}
Exemplo n.º 9
0
def get_pi_cmd_info(uid):
    tags = []
    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return []
    else:
        try:
            tagset = DBSession.query(Tags).filter(Tags.uuid==uid).all()
            for tag in tagset:
                tags.append(tag.tag)
        except Exception:
            pass

    rowdict = row.get_dict()
    rowdict['tags']=tags
    return rowdict
Exemplo n.º 10
0
def get_pi_cmd_info(uid):
    tags = []
    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return []
    else:
        try:
            tagset = DBSession.query(Tags).filter(Tags.uuid == uid).all()
            for tag in tagset:
                tags.append(tag.tag)
        except Exception:
            pass

    rowdict = row.get_dict()
    rowdict['tags'] = tags
    return rowdict
Exemplo n.º 11
0
def redirect_me(request):
    uid = request.matchdict['uid']
    url = "http://www.stackexchange.com"
    try:
        row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
        if row:
            url = row.url
            logging.info("UID {uid}: {page}".format(uid=row.uuid, page=url))
        else:
            row = RasPi()
            row.uuid = uid
            row.url = "http://www.stackexchange.com"
            row.landscape = True
            row.browser = True
            DBSession.add(row)
            DBSession.flush()
            logging.warn(
                "UID {uid} NOT FOUND. ADDED TO TABLE WITH DEFAULT URL".format(
                    uid=uid))
            url = row.url
    except Exception:
        logging.error(
            "Something went south with DB when searching for {uid}".format(
                uid=uid))

    raise exc.HTTPFound(url)
Exemplo n.º 12
0
def view_api_refresh_get(request):
    uid = request.matchdict['uid']

    refresh_cmd={}
    refresh_cmd['cmd']='su'
    refresh_cmd['args']=['-c','/home/pi/refresh.sh','pi']
    refresh_cmd['result']=''


    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    try:
        # If there are already records to be run,
        # we'll start with them in the array already
        cmd_data = json.loads(row.requested_commands)
    except (ValueError, TypeError):
        cmd_data=[]
        pass

    cmd_data.append(refresh_cmd)

    row.requested_commands = json.dumps(cmd_data)
    DBSession.flush()

    return {'status': 'OK'}
Exemplo n.º 13
0
def view_ajax_set_commands(request):
    uid = request.matchdict['uid']
    response = request.json_body

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return '{"status":"error"}'

    # convert response into something with stable sorting
    cmds = []
    tmpcmds = sorted(response.items(), key=operator.itemgetter(0))
    for tmptuple in tmpcmds:
        # extract cmdid/cmd
        cmdid = int(tmptuple[0])
        cmd = tmptuple[1]['cmd']
        del tmptuple[1]['cmd']

        # extract arguments
        tmpargs = sorted(tmptuple[1].items(), key=operator.itemgetter(0))
        args = [item[1] for item in tmpargs]

        # put into our cmd object in the correct order
        cmds.insert(cmdid, {})
        cmds[cmdid]['cmd'] = cmd
        cmds[cmdid]['args'] = args

        # command hasn't been run yet, so this is blank
        cmds[cmdid]['result'] = ''

    row.requested_commands = json.dumps(cmds)
    DBSession.flush()

    return str(cmds)
Exemplo n.º 14
0
def make_an_admin(request):
    email=request.matchdict['email']

    '''First, make sure there aren't already admins in the system'''
    res=DBSession.query(UserModel).filter(UserModel.AccessLevel==2).first()
    if res != None:
        msg="User already an admin: {user}".format(user=res.email)
        return False
    user=DBSession.query(UserModel).filter(UserModel.email==email).first()
    if user == None:
        user=UserModel()
        user.email=email
        DBSession.add(user)
    user.AccessLevel=2
    DBSession.flush()    
    return True
Exemplo n.º 15
0
def LookupUser(request):
  userid=authenticated_userid(request)
  try:
    logging.debug("Looking up user session for %s", userid)
    UserObject = DBSession.query(UserModel).filter(UserModel.email==userid).one()
    return UserObject
  except NoResultFound, e:
    return None
Exemplo n.º 16
0
def groupfinder(userid,request):
  try:
    user = DBSession.query(UserModel).filter(UserModel.email==userid).one()
    if user is not None:
      if user.AccessLevel >= 0:
        return[AccessLevels[user.AccessLevel]]
  except NoResultFound, e:
    return None
Exemplo n.º 17
0
def LookupUser(request):
    userid = authenticated_userid(request)
    try:
        logging.debug("Looking up user session for %s", userid)
        UserObject = DBSession.query(UserModel).filter(
            UserModel.email == userid).one()
        return UserObject
    except NoResultFound, e:
        return None
Exemplo n.º 18
0
def groupfinder(userid, request):
    try:
        user = DBSession.query(UserModel).filter(
            UserModel.email == userid).one()
        if user is not None:
            if user.AccessLevel >= 0:
                return [AccessLevels[user.AccessLevel]]
    except NoResultFound, e:
        return None
Exemplo n.º 19
0
def view_ajax_get_command_results(request):
    uid = request.matchdict['uid']

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    data = json.loads(row.requested_commands)

    return {'status': 'OK', 'data': data}
Exemplo n.º 20
0
def view_ajax_get_command_results(request):
    uid = request.matchdict['uid']

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    data = json.loads(row.requested_commands)

    return {'status': 'OK', 'data': data}
Exemplo n.º 21
0
def view_ajax_set_command_results(request):
    uid = request.matchdict['uid']

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    row.requested_commands = ''
    DBSession.flush()

    return {'status': 'OK'}
Exemplo n.º 22
0
def view_ajax_set_command_results(request):
    uid = request.matchdict['uid']

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    row.requested_commands = ''
    DBSession.flush()

    return {'status': 'OK'}
Exemplo n.º 23
0
def view_api_screenshow_show(request):
    uid = request.matchdict['uid']
    shot = DBSession.query(Screenshot).filter(Screenshot.uuid == uid).first()
    if shot:
        with BytesIO() as ss:
            ss.write(shot.image)
            return Response(content_type='image/png', content_length=len(ss.getvalue()), body=ss.getvalue())
    else:
        with BytesIO() as ss:
            emptypng = '89504E470D0A1A0A0000000D49484452000000010000000108000000003A7E9B550000000A4944' \
                       '4154789C63FA0F0001050102CFA02ECD0000000049454E44AE426082'.decode('hex')
            ss.write(emptypng)
            return Response(content_type='image/png', content_length=len(ss.getvalue()), body=ss.getvalue())
Exemplo n.º 24
0
def view_api_screenshow_show(request):
    uid = request.matchdict['uid']
    shot = DBSession.query(Screenshot).filter(Screenshot.uuid == uid).first()
    if shot:
        with BytesIO() as ss:
            ss.write(shot.image)
            return Response(content_type='image/png', content_length=len(ss.getvalue()), body=ss.getvalue())
    else:
        with BytesIO() as ss:
            emptypng = '89504E470D0A1A0A0000000D49484452000000010000000108000000003A7E9B550000000A4944' \
                       '4154789C63FA0F0001050102CFA02ECD0000000049454E44AE426082'.decode('hex')
            ss.write(emptypng)
            return Response(content_type='image/png', content_length=len(ss.getvalue()), body=ss.getvalue())
Exemplo n.º 25
0
def get_tagged_pis(tags):
    splitter = shlex.shlex(tags)
    splitter.whitespace += ','
    splitter.whitespace += ';'
    splitter.whitespace_split = True
    taglist = list(splitter)

    taglist_str = ""
    for tag in taglist:
        taglist_str += "\'{tag}\',".format(tag=tag)
    taglist_str = taglist_str.rstrip(taglist_str[-1:])

    tagged_pis = []

    if (len(taglist) > 1):
        query_str = """
    SELECT t1.uuid,count(*) AS ct
      FROM Tags t1
      JOIN Tags t2 ON t1.tag!=t2.tag AND t1.uuid==t2.uuid
     WHERE 1
       AND t1.tag IN ({taglist})
       AND t2.tag IN ({taglist})
  GROUP BY t1.uuid
    HAVING ct >= {args}
        """.format(taglist=taglist_str, args=len(taglist))

        result = DBSession.get_bind().execute(query_str)

        for row in result:
            tagged_pis.append(row[0])
    else:
        PisWithTags = DBSession.query(Tags).filter(Tags.tag.in_(taglist)).all()
        for pi in PisWithTags:
            tagged_pis.append(pi.uuid)

    PiList = DBSession.query(RasPi).filter(RasPi.uuid.in_(tagged_pis)).order_by(desc(RasPi.lastseen)).all()
    return PiList
Exemplo n.º 26
0
def get_tagged_pis(tags):
    splitter = shlex.shlex(tags)
    splitter.whitespace += ','
    splitter.whitespace += ';'
    splitter.whitespace_split = True
    taglist = list(splitter)

    taglist_str = ""
    for tag in taglist:
        taglist_str += "\'{tag}\',".format(tag=tag)
    taglist_str = taglist_str.rstrip(taglist_str[-1:])

    tagged_pis = []

    if (len(taglist) > 1):
        query_str = """
        SELECT t1.uuid,count(*)
        FROM "Tags" t1
        JOIN "Tags" t2 ON t1.tag!=t2.tag AND t1.uuid=t2.uuid
        WHERE t1.tag IN ({taglist})
        AND t2.tag IN ({taglist})
        GROUP BY t1.uuid
        HAVING count(*) >= {args};
        """.format(taglist=taglist_str, args=len(taglist))

        result = DBSession.get_bind().execute(query_str)

        for row in result:
            tagged_pis.append(row[0])
    else:
        PisWithTags = DBSession.query(Tags).filter(Tags.tag.in_(taglist)).all()
        for pi in PisWithTags:
            tagged_pis.append(pi.uuid)

    PiList = DBSession.query(RasPi).filter(RasPi.uuid.in_(tagged_pis)).order_by(desc(RasPi.lastseen)).all()
    return PiList
Exemplo n.º 27
0
def login_complete_view(request):
  context = request.context
  result = {
    'provider_type': context.provider_type,
    'provider_name': context.provider_name,
    'profile': context.profile,
    'credentials': context.credentials,
  }
  email = context.profile['verifiedEmail']
  try:
    User = DBSession.query(UserModel).filter(UserModel.email==email).one()
  except NoResultFound, e:
    User = UserModel()
    User.email = email
    User.AccessLevel = 1
    DBSession.add(User)
    DBSession.flush()
Exemplo n.º 28
0
def view_api_ping(request):
    uid = request.matchdict['uid']

    now = datetime.now()

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        row = RasPi()
        row.uuid = uid
        row.url = "http://www.stackexchange.com"
        row.landscape = True
        row.orientation = 0
        row.description = ""

    row.lastseen = now
    DBSession.add(row)
    DBSession.flush()
Exemplo n.º 29
0
def login_complete_view(request):
    context = request.context
    result = {
        'provider_type': context.provider_type,
        'provider_name': context.provider_name,
        'profile': context.profile,
        'credentials': context.credentials,
    }
    email = context.profile['verifiedEmail']
    try:
        User = DBSession.query(UserModel).filter(
            UserModel.email == email).one()
    except NoResultFound, e:
        User = UserModel()
        User.email = email
        User.AccessLevel = 1
        DBSession.add(User)
        DBSession.flush()
Exemplo n.º 30
0
def view_api_ping(request):
    uid = request.matchdict['uid']

    now = datetime.now()

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        row = RasPi()
        row.uuid = uid
        row.url = "http://www.stackexchange.com"
        row.landscape = True
        row.orientation = 0
        row.description = ""
        row.browser = True

    row.lastseen = now
    DBSession.add(row)
    DBSession.flush()
Exemplo n.º 31
0
def redirect_me(request):
    uid = request.matchdict['uid']
    url = "http://www.stackexchange.com"
    try:
        row = DBSession.query(RasPi).filter(RasPi.uuid==uid).first()
        if row:
            url = row.url
            logging.info("UID {uid}: {page}".format(uid=row.uuid, page=url))
        else:
            row = RasPi()
            row.uuid = uid
            row.url = "http://www.stackexchange.com"
            row.landscape = True
            DBSession.add(row)
            DBSession.flush()
            logging.warn("UID {uid} NOT FOUND. ADDED TO TABLE WITH DEFAULT URL".format(uid=uid))
            url = row.url
    except Exception:
            logging.error("Something went south with DB when searching for {uid}".format(uid=uid))

    raise exc.HTTPFound(url)
Exemplo n.º 32
0
def view_json_set_pi(request):
    # TODO: move into controller(s)
    uid = request.matchdict['uid']
    response = request.json_body

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        row = RasPi()
        row.uuid = uid
    row.url = response['url']
    row.description = response['description']
    row.orientation = response['orientation']
    row.browser = response['browser']
    DBSession.add(row)
    DBSession.flush()
    rowdict = {
        'uuid': row.uuid,
        'url': row.url,
        'description': row.description,
        'orientation': row.orientation,
        'browser': row.browser
    }
    return rowdict
Exemplo n.º 33
0
def view_json_set_pi(request):
    # TODO: move into controller(s)
    uid = request.matchdict['uid']
    response = request.json_body

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        row = RasPi()
        row.uuid = uid
    row.url = response['url']
    row.description = response['description']
    row.orientation = response['orientation']
    row.browser = response['browser']
    DBSession.add(row)
    DBSession.flush()
    rowdict = {
        'uuid': row.uuid,
        'url': row.url,
        'description': row.description,
        'orientation': row.orientation,
        'browser': row.browser
    }
    return rowdict
Exemplo n.º 34
0
def view_api_reqcommands_post(request):
    uid = request.matchdict['uid']
    results = request.json_body
    results['data'] = json.loads(results['data'])

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    cmd_data = json.loads(row.requested_commands)
    new_data = []

    for i, cmdinfo in enumerate(cmd_data):
        if results['status'] == 'OK':
            cmdinfo['result'] = results['data'][i]
        else:
            cmdinfo['result'] = results['msg']

        new_data.append(cmdinfo)

    row.requested_commands = json.dumps(new_data)
    DBSession.flush()

    return {'status': 'OK'}
Exemplo n.º 35
0
def view_api_reqcommands_post(request):
    uid = request.matchdict['uid']
    results = request.json_body
    results['data'] = json.loads(results['data'])

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    cmd_data = json.loads(row.requested_commands)
    new_data = []

    for i, cmdinfo in enumerate(cmd_data):
        if results['status'] == 'OK':
            cmdinfo['result'] = results['data'][i]
        else:
            cmdinfo['result'] = results['msg']

        new_data.append(cmdinfo)

    row.requested_commands = json.dumps(new_data)
    DBSession.flush()

    return {'status': 'OK'}
Exemplo n.º 36
0
def get_log(uuid, filename):
    log = DBSession.query(Logs).filter(
        Logs.uuid == uuid).filter(
        Logs.filename == filename).first()

    return log
Exemplo n.º 37
0
def get_users():
    UserList=DBSession.query(UserModel).all()
    return UserList
Exemplo n.º 38
0
def get_users():
    UserList = DBSession.query(UserModel).all()
    return UserList
Exemplo n.º 39
0
def get_log(uuid, filename):
    log = DBSession.query(Logs).filter(
          Logs.uuid == uuid).filter(
          Logs.filename == filename).first()

    return log
Exemplo n.º 40
0
def get_logs(uuid):
    logs = DBSession.query(Logs).filter(Logs.uuid == uuid).all()
    return logs
Exemplo n.º 41
0
def view_json_delete_pi(request):
    uid = request.matchdict['uid']
    pi = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    for tag in pi.tags:
        DBSession.query(Tags).filter(and_(Tags.uuid == uid, Tags.tag == tag.tag)).delete()
    DBSession.query(RasPi).filter(RasPi.uuid == uid).delete()
Exemplo n.º 42
0
def delete_user(email):
    DBSession.query(UserModel).filter(UserModel.email==email).delete()
Exemplo n.º 43
0
def view_api_delete_tag(request):
    uid=request.matchdict['uid']
    tag=request.matchdict['tag']
    DBSession.query(Tags).filter(and_(Tags.uuid == uid,Tags.tag == tag)).delete()
Exemplo n.º 44
0
def delete_user(email):
    DBSession.query(UserModel).filter(UserModel.email == email).delete()
Exemplo n.º 45
0
def view_api_delete_tag(request):
    uid=request.matchdict['uid']
    tag=request.matchdict['tag']
    DBSession.query(Tags).filter(and_(Tags.uuid == uid,Tags.tag == tag)).delete()
Exemplo n.º 46
0
def authorize_user(email):
    user = DBSession.query(UserModel).filter(UserModel.email == email).one()
    user.AccessLevel = 2
    DBSession.flush()
Exemplo n.º 47
0
def authorize_user(email):
    user=DBSession.query(UserModel).filter(UserModel.email==email).one()
    user.AccessLevel=2
    DBSession.flush()
Exemplo n.º 48
0
def view_json_delete_pi(request):
    uid = request.matchdict['uid']
    DBSession.query(RasPi).filter(RasPi.uuid == uid).delete()
Exemplo n.º 49
0
def get_pis():
    PiList = DBSession.query(RasPi).filter(RasPi.uuid!="default").order_by(desc(RasPi.lastseen)).all()
    return PiList
Exemplo n.º 50
0
def get_logs(uuid):
    logs = DBSession.query(Logs).filter(Logs.uuid==uuid).all()
    return logs
Exemplo n.º 51
0
def get_pis():
    PiList = DBSession.query(RasPi).filter(RasPi.uuid != "default").order_by(desc(RasPi.lastseen)).all()
    return PiList