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'}
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)
def main(argv=sys.argv): if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.create_all(engine) with transaction.manager: model = RasPi() model.uuid = '11:22:33:44:55:66' model.description = "Testing Pi" model.url = "http://www.facebook.com" model.orientation = 0 model.browser = True model.lastseen = datetime.now() DBSession.add(model) tag = Tags() tag.uuid = '11:22:33:44:55:66' tag.tag = 'test' DBSession.add(tag) User = UserModel() User.email = '*****@*****.**' User.AccessLevel = 2 DBSession.add(User) DBSession.flush()
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)
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ NotSoSecret = 'CIeUz0RK8fjRq1wJSrID' authn_policy = AuthTktAuthenticationPolicy(NotSoSecret, callback=groupfinder, hashalg='sha512') authz_policy = ACLAuthorizationPolicy() session_factory = SignedCookieSessionFactory(NotSoSecret) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings, root_factory=Root) config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) config.include('velruse.providers.google_oauth2') config.set_session_factory(session_factory) config.add_google_oauth2_login_from_settings(prefix='velruse.google.') config.include('cornice') config.include('pyramid_mako') config.add_static_view('static', 'static', cache_max_age=3600) config.add_static_view('client_agent', 'client_agent', cache_max_age=3600) config.add_route('home', '/') config.add_route('tagged', '/tagged/{tags}') config.add_route('users', '/users') config.add_route('logout', '/logout') config.add_route('redirectme', '/go/{uid}') config.add_route('provision', '/provision') config.add_route('logs', '/logs/{uuid}') config.add_route('wall', '/wall/{tags}') config.add_request_method(LookupUser, 'user', reify=True) config.scan() return config.make_wsgi_app()
def view_api_post_new_tag(request): uid=request.matchdict['uid'] tag=request.matchdict['tag'] newtag = Tags() newtag.uuid=uid newtag.tag=tag DBSession.add(newtag) DBSession.flush()
def setUp(self): self.config = testing.setUp() from sqlalchemy import create_engine engine = create_engine('sqlite://') from pi_director.models.models import ( Base, RasPi, ) DBSession.configure(bind=engine)
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'}
def setUp(self): self.config = testing.setUp() from sqlalchemy import create_engine engine = create_engine('sqlite://') from pi_director.models.models import ( Base, RasPi, ) DBSession.configure(bind=engine) Base.metadata.create_all(engine) with transaction.manager: model = RasPi(name='one', value=55) DBSession.add(model)
def main(argv=sys.argv): if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) engine = engine_from_config(settings, "sqlalchemy.") DBSession.configure(bind=engine) Base.metadata.create_all(engine) with transaction.manager: model = RasPi(uuid="default", url="http://www.facebook.com") DBSession.add(model)
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
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
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()
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
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()
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
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()
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
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
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()
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}
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)
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
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())
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
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
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'}
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
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()
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()
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
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
def get_users(): UserList = DBSession.query(UserModel).all() return UserList
def view_json_delete_pi(request): uid = request.matchdict['uid'] DBSession.query(RasPi).filter(RasPi.uuid == uid).delete()
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()
def get_log(uuid, filename): log = DBSession.query(Logs).filter( Logs.uuid == uuid).filter( Logs.filename == filename).first() return log
def get_logs(uuid): logs = DBSession.query(Logs).filter(Logs.uuid==uuid).all() return logs
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()
def tearDown(self): DBSession.remove() testing.tearDown()
def delete_user(email): DBSession.query(UserModel).filter(UserModel.email == email).delete()
def authorize_user(email): user = DBSession.query(UserModel).filter(UserModel.email == email).one() user.AccessLevel = 2 DBSession.flush()