def get(self): args = self.parser.parse_args() query = args["query"] maxResults = args["maxResults"] if query == None: return jsonify({"results": {}}) searchResults = {} isDone = False for collectionAttrs in SEARCHABLE_COLLECTION_ATTRIBUTES: if isDone: break collectionResults = [] collection = db[collectionAttrs["collectionName"]] collection.create_index([("$**", TEXT)]) rawCollectionResults = collection.find({"$text": {"$search": query}}) for res in rawCollectionResults: if len(searchResults) >= maxResults: isDone = True break collectionResults.append({"title": res[collectionAttrs['nameField']], "url": collectionAttrs['linkLead']+str(res["_id"])}) if len(collectionResults) > 0: searchResults[collectionAttrs["collectionName"]] = {"name": collectionAttrs["categoryName"], "results": collectionResults} return jsonify({"results": searchResults})
def api_addguest(key): if key != API_KEY: return api_log_wrong_key() full_name = request.form['full_name'] admin_username = request.form['admin_username'] admin = mongodb.admin_collection.find_one({'username': admin_username}) admin_name = admin.get("full_name") guest_exist = mongodb.guest_exist(full_name) if guest_exist is True: return jsonify(result="failure", details="guest already exists") guest_photo = request.files['guest_photo'] photo_simplename = "guest_" + full_name + "_" + secure_filename(guest_photo.filename) photo_filepath = "static/original/guest_photos/" + photo_simplename mongodb.add_photo("guest", full_name, photo_filepath, photo_simplename) mongodb.add_guest(admin_username, admin_name, full_name) guest_photo.save(photo_filepath) Popen(['./DetectImage', PROJECT_DIRECTORY + photo_filepath], cwd=DETECT_IMAGE_DIRECTORY) return jsonify(result="success")
def api_addphoto(key): if key != API_KEY: return api_log_wrong_key() profile_type = request.form['profile_type'] profile_name = request.form['profile_name'] photo = request.files['photo'] photo_simplename = profile_type + "_" + profile_name + "_" + secure_filename(photo.filename) if profile_type == "admin": photo_filepath = "static/original/admin_photos/" + photo_simplename elif profile_type == "user": photo_filepath = "static/original/user_photos/" + photo_simplename elif profile_type == "guest": photo_filepath = "static/original/guest_photos/" + photo_simplename add_photo = mongodb.add_photo(profile_type, profile_name, photo_filepath, photo_simplename) if add_photo is -1: return jsonify(result="failure", details="choose photo with unique file name") photo.save(photo_filepath) Popen(['./DetectImage', PROJECT_DIRECTORY + photo_filepath], cwd=DETECT_IMAGE_DIRECTORY) return jsonify(result="success", details="photo add successful")
def layers_route(): # current_user if request.method == "GET": return jsonify(select_layers(current_user)) if request.method == "POST": return jsonify(add_or_replace_layers(current_user, request.json)) pass
def api_newadmin(key): if key != API_KEY: return api_log_wrong_key() username = request.form['username'] password = request.form['password'] full_name = request.form['full_name'] device_id = request.form['device_id'] admin_photo = request.files['admin_photo'] if mongodb.device_available(device_id) is False: return jsonify(result="failure", details="given device not available") if mongodb.admin_exist(username) is True: return jsonify(result="failure", details="given username not available") photo_simplename = "admin_" + username + "_" + secure_filename(admin_photo.filename) photo_filepath = "static/original/admin_photos/" + photo_simplename mongodb.add_photo("admin", username, photo_filepath, photo_simplename) mongodb.add_admin(full_name, username, password, device_id) mongodb.claim_device(device_id, username) admin_photo.save(photo_filepath) Popen(['./DetectImage', PROJECT_DIRECTORY + photo_filepath], cwd=DETECT_IMAGE_DIRECTORY) return jsonify(result="success")
def patch(self, song_id): return {"error": "api disabled"}, 405 args = self.vote_parser.parse_args() votes = {"up": +1, "down": -1} # check input if args["vote"] not in votes: return {"error": "wrong vote value"}, 400 # is the user a new user if not args["voter_id"]: # cast a vote r = mongo.db.songs.find_and_modify({"_id": song_id}, {"$inc": {"points": votes[args["vote"]]}}, new=True) # that song didnt exist if not r: return {"error": "Song does not exists"}, 404 # create a new user voter = mongo.db.voters.insert({"voted_songs":{str(r["_id"]):args["vote"]}, "created_at":datetime.now()}) # create a responce with user cookie resp = make_response(jsonify(r)) resp.set_cookie("voter_id", value=str(voter), max_age=86400) # user has voted before aka old user else: # load user voter = mongo.db.voters.find_one({"_id":ObjectId(args["voter_id"])}) vote = votes[args["vote"]] print(voter["voted_songs"]) print(song_id) # if user has voted on that song before if str(song_id) in voter["voted_songs"].keys(): if args["vote"] != voter["voted_songs"][str(song_id)]: # undo last vote and cast a new vote vote = -vote-vote update = mongo.db.voters.update({"_id":voter["_id"]}, {"$set":{'voted_songs.'+str(song_id):args['vote']}}) print("update set", update) elif args["vote"] == voter["voted_songs"][str(song_id)]: # undo last vote vote = -vote update = mongo.db.voters.update({"_id":voter["_id"]}, {"$unset":'voted_songs.'+str(song_id)}) print("update unset", update) # actually cast that vote else: return {"error":"wtf"}, 500 r = mongo.db.songs.find_and_modify({"_id": song_id}, {"$inc": {"points": vote}}, new=True) if not r: # that song didnt exist return {"error": "Song does not exists"}, 404 return jsonify(r) # user hasn't voted before else: return {"error": "not implemented"}, 500 return resp
def get(self): parser = reqparse.RequestParser() parser.add_argument("problemID", type=str, required=False, location="args") args = parser.parse_args() if args["problemID"] is not None: return jsonify([a for a in db.entry.find({"problemID": args["problemID"]})]) else: return jsonify([a for a in db.entry.find({})])
def get(self): if "userID" not in session: return jsonify({"loggedIn": False}) user = db.user.find_one({"_id": session["userID"]}) if user is None: session.pop("userID") return jsonify({"loggedIn": False}) return jsonify({ "loggedIn": True, "user": user })
def get(self): if "userID" not in session: return jsonify({"loggedIn": False}) user = db.user.find_one({"_id": session["userID"]}) if user is None: session.pop("userID") return jsonify({"loggedIn": False}) return jsonify({"loggedIn": True, "user": user})
def signup_route(): if request.form: username = request.form["username"] password = request.form["password"] if request.json: username = request.json["username"] password = request.json["password"] if username is not None and password is not None: return jsonify({"message": create_user(username, password)}) return jsonify({"message": "something wrong with your credentials"})
def api_removephoto(key): if key != API_KEY: return api_log_wrong_key() photo_simplename = request.form['photo_simplename'] delete_photo = mongodb.delete_one_photo(photo_simplename, os) if delete_photo is -1: return jsonify(result="failure", details="given photo with photo_simplename does not exist") return jsonify(result="success", details="photo delete successful")
def get(self): parser = reqparse.RequestParser() parser.add_argument("problemID", type=str, required=False, location="args") args = parser.parse_args() if args["problemID"] is not None: return jsonify( [a for a in db.entry.find({"problemID": args["problemID"]})]) else: return jsonify([a for a in db.entry.find({})])
def api_getdooractivities(key): if key != API_KEY: return api_log_wrong_key() admin = request.form['admin'] if mongodb.admin_exist(admin) is False: return jsonify(result="failure", details="given admin does not exist") door_activities = mongodb.door_collection.find({'admin': admin}) door_activity_list = [] for activity in door_activities: door_activity_list.append(activity) return jsonify(result="success", door_activities=door_activity_list)
def post(self): parser = reqparse.RequestParser() parser.add_argument("problemID", type=str, required=True, location="json") parser.add_argument("userID", type=str, required=True, location="json") parser.add_argument("file", type=FileStorage, required=True, location="files") entry = parser.parse_args() try: if db.problem.find_one({"_id": ObjectId(entry['problemID'])}) == None: abort(400) if db.user.find_one({"_id": entry['userID']}) == None: abort(400) except: abort(400) problemName = db.problem.find_one({"_id": ObjectId(entry['problemID'])})['name'] gradingFilePath = os.path.join(os.path.join(PROBLEMS_DIR, problemName.lower()), GRADING_SCRIPT) command = "python3 "+gradingFilePath+" \""+entry["file"].stream+"\"" gradingOutput = subprocess.Popen(shlex.split(command.replace('\\','/')), stdout=subprocess.PIPE).communicate()[0] structuredGradingOutput = json.loads(gradingOutput) status_code = None if "score" in structuredGradingOutput: entry["score"] = structuredGradingOutput["score"] entry.pop("file") db.entry.insert_one(entry) status_code = 201 else: status_code = 400 return jsonify(structuredGradingOutput, status=status_code)
def busca(nome, ext='html'): resultado = mongo.db.politicos.find_one({"nome": nome}) if resultado: if ext == 'json': return jsonify(resultado) else: if '2010' not in resultado['candidaturas']: resultado['candidaturas']['2010'] = { 'total' : 0, 'outras_doacoes' : 0.0 } else: resultado['candidaturas']['2010']['doacoes'] = sorted(iter(resultado['candidaturas']['2010']['doacoes'].items()), key=lambda x: x[1]['valor'], reverse=True)[0:5] resultado['candidaturas']['2010']['outras_doacoes'] = float(resultado['candidaturas']['2010']['total']) for r in resultado['candidaturas']['2010']['doacoes']: resultado['candidaturas']['2010']['outras_doacoes'] += -1*float(r[1]['valor']) if '2014' not in resultado['candidaturas']: resultado['candidaturas']['2014'] = { 'total' : 0, 'outras_doacoes' : 0.0 } else: resultado['candidaturas']['2014']['doacoes'] = sorted(iter(resultado['candidaturas']['2014']['doacoes'].items()), key=lambda x: x[1]['valor'], reverse=True)[0:5] resultado['candidaturas']['2014']['outras_doacoes'] = float(resultado['candidaturas']['2014']['total']) for r in resultado['candidaturas']['2014']['doacoes']: resultado['candidaturas']['2014']['outras_doacoes'] += -1*float(r[1]['valor']) return render_template('popup.html', data=resultado) else: abort(404)
def _projeto(tipo, numero, ano, json=False): pid = tipo.lower() + '-' + numero + '-' + ano projeto = mongo.db.legis.find_one({"_id": pid}) explicacoes = mongo.db.explicacoes.find() # Monta tramitacao for p in projeto['tramitacoes']: if p['data_inicio'] == '': p['data_inicio'] = futuro() p['tipo'] = 'tramita' if projeto.has_key('encerramento'): projeto['tramitacoes'].append({ 'data_inicio' : projeto['data_encerramento'], #pensar 'tramitacao' : projeto['encerramento'], 'tipo' : 'encerramento' }) for p in projeto['tramitacoes']: if p['data_inicio'] > projeto['data_encerramento'] and p['tipo'] == 'tramita': p['tipo'] = 'arquivo' for c in projeto['comissoes']: if not any(p['tramitacao'] == c for p in projeto['tramitacoes']) and not projeto.has_key('encerramento'): #adicionar tramitacao conjunta projeto['tramitacoes'].append({ 'tipo' : 'comdes', 'tramitacao' : c, 'data_inicio' : futuro() }) if not projeto: abort(404) if json == 'json': return jsonify(projeto) elif json == False: return render_template('legis.html', p=projeto, explicacoes=explicacoes)
def get(self): parser = reqparse.RequestParser() parser.add_argument("code", type=str, required=True, location="json") code = parser.parse_args()["code"] response = json.loads( requests.post("https://github.com/login/oauth/access_token", json={ "code": code, "client_id": GITHUB_CLIENT_ID, "client_secret": GITHUB_CLIENT_SECRET }).text) accessToken = response["access_token"] githubUser = json.loads( requests.get("https://api.github.com/user", data={ "access_token": accessToken }).text) dbUser = db.user.find_one({"_id": githubUser['id']}) if dbUser is None: newUser = { "_id": githubUser["id"], "name": githubUser['username'], "joinDate": datetime.datetime.today().strftime('%Y-%m-%d') } db.tempUser.insert_one(newUser) return redirect(WEBSITE_DOMAIN + "/signup.html#" + newUser["_id"]) else: session['userID'] = dbUser["_id"] return jsonify({"loggedIn": True, "user": user})
def busca(nome, ext='html'): resultado = mongo.db.politicos.find_one({"nome": nome}) if resultado: if ext == 'json': return jsonify(resultado) else: if not resultado['candidaturas'].has_key('2010'): resultado['candidaturas']['2010'] = { 'total' : 0, 'outras_doacoes' : 0.0 } else: resultado['candidaturas']['2010']['doacoes'] = sorted(resultado['candidaturas']['2010']['doacoes'].iteritems(), key=lambda x: x[1]['valor'], reverse=True)[0:5] resultado['candidaturas']['2010']['outras_doacoes'] = float(resultado['candidaturas']['2010']['total']) for r in resultado['candidaturas']['2010']['doacoes']: resultado['candidaturas']['2010']['outras_doacoes'] += -1*float(r[1]['valor']) if not resultado['candidaturas'].has_key('2014'): resultado['candidaturas']['2014'] = { 'total' : 0, 'outras_doacoes' : 0.0 } else: resultado['candidaturas']['2014']['doacoes'] = sorted(resultado['candidaturas']['2014']['doacoes'].iteritems(), key=lambda x: x[1]['valor'], reverse=True)[0:5] resultado['candidaturas']['2014']['outras_doacoes'] = float(resultado['candidaturas']['2014']['total']) for r in resultado['candidaturas']['2014']['doacoes']: resultado['candidaturas']['2014']['outras_doacoes'] += -1*float(r[1]['valor']) return render_template('popup.html', data=resultado) else: abort(404)
def api_adminlogin(key): if key != API_KEY: return api_log_wrong_key() username = request.form['username'] password = request.form['password'] access = mongodb.admin_allow_login(username, password) if access is False: return api_log_wrong_credentials() profile = mongodb.admin_collection.find_one({'username': username, 'password': password}) device = mongodb.device_collection.find_one({'admin': username}) door_activity = mongodb.door_collection.find({'admin': username}) door_list = [] for door in door_activity: door_list.append(door) photos = mongodb.photo_collection.find({'profile_type': "admin", 'profile_name': username}) photos_list = [] for photo in photos: photos_list.append(photo) return jsonify(result="success", profile=profile, device=device, photos=photos_list, door=door_list)
def api_get_user_feed_entries_by_feed(feedid): user = users.load_user_by_apikey(request.args['apikey']) feeds = current_user.get_feeds_as_dict(True) for f in feeds['feeds']: if str(f['_id']) == str(feedid): return jsonify(f) abort(400)
def api_toggledoormobile(key): if key != API_KEY: return api_log_wrong_key() device_id = request.form['device_id'] toggle_photo = request.files['photo'] admin_username = request.form['admin_username'] profile_type = request.form['profile_type'] profile_name = request.form['profile_name'] create_csv() if mongodb.door_collection.count() >= 50: mongodb.delete_door_collections(os) photo_simplename = "toggle_testing_device_" + device_id + "_photo_" + mongodb.door_collection.count() photo_filepath = "static/original/toggle_photos/" + photo_simplename toggle_photo.save(photo_filepath) out = check_output(['./MatchImage', CSV_PATH, PROJECT_DIRECTORY + photo_filepath], cwd=MATCH_IMAGE_DIRECTORY) # create door activity record and save mongodb.add_door_activity(admin_username, profile_type, profile_name, photo_simplename, out) mongodb.update_device_status(device_id, str(out)) return jsonify(result="success", access=out) # 1 means access granted, 0 means access denied
def get(self, userID): try: user = db.user.find_one({"_id": userID}) except: abort(404) if user is None: abort(404) return jsonify(user)
def get(self, eventID): try: event = db.event.find_one({"_id": ObjectId(eventID)}) except: abort(404) if event is None: abort(404) return jsonify(event)
def get(self, problemID): try: problem = db.problem.find_one({"_id": ObjectId(problemID)}) except: abort(404) if problem is None: abort(404) return jsonify(problem)
def get(self, entryID): try: entry = db.entry.find_one({"_id": ObjectId(entryID)}) except: abort(404) if entry is None: abort(404) return jsonify(entry)
def api_updatedoorbattery(key): if key != API_KEY: return api_log_wrong_key() device_id = request.form['device_id'] battery = request.form['battery'] mongodb.update_device_battery(device_id, battery) return jsonify(result="success")
def api_updatedoorstatus(key): if key != API_KEY: return api_log_wrong_key() device_id = request.form['device_id'] status = request.form['status'] mongodb.update_device_status(device_id, str(status)) return jsonify(result="success")
def projeto(tipo, numero, ano, json=False): pid = tipo + '-' + numero + '-' + ano projeto = mongo.db.legis.find_one({"_id": pid}) if not projeto: abort(404) if json == 'json': return jsonify(projeto) elif json == False: return render_template('legis.html', p=projeto)
def api_deleteuser(key): if key != API_KEY: return api_log_wrong_key() username = request.form['username'] mongodb.delete_user(username) mongodb.delete_all_photos("user", username, os) return jsonify(result="success")
def api_deleteguest(key): if key != API_KEY: return api_log_wrong_key() guestname = request.form['full_name'] mongodb.delete_guest(guestname) mongodb.delete_all_photos("guest", guestname, os) return jsonify(result="success")
def _vereador(nome, json=False): vereador = mongo.db.vereadores.find_one({"nomes_parlamentares" : nome}) if not (vereador): abort(404) vereador['assuntos'] = [] if not json: return render_template('vereador.html', v=vereador) elif json == 'json': return jsonify(v)
def _vereador(nome, json=False): vereador = mongo.db.vereadores.find_one({"nomes_parlamentares": nome}) if not (vereador): abort(404) vereador['assuntos'] = [] if not json: return render_template('vereador.html', v=vereador) elif json == 'json': return jsonify(vereador)
def post(self): event = self.parser.parse_args() try: db.user.find_one({"_id": event['userID']}) except: abort(400) db.event.insert_one(event) return jsonify(event, status=201)
def get(self): args = self.parser.parse_args() query = args["query"] maxResults = args["maxResults"] if query == None: return jsonify({"results": {}}) searchResults = {} isDone = False for collectionAttrs in SEARCHABLE_COLLECTION_ATTRIBUTES: if isDone: break collectionResults = [] collection = db[collectionAttrs["collectionName"]] collection.create_index([("$**", TEXT)]) rawCollectionResults = collection.find( {"$text": { "$search": query }}) for res in rawCollectionResults: if len(searchResults) >= maxResults: isDone = True break collectionResults.append({ "title": res[collectionAttrs['nameField']], "url": collectionAttrs['linkLead'] + str(res["_id"]) }) if len(collectionResults) > 0: searchResults[collectionAttrs["collectionName"]] = { "name": collectionAttrs["categoryName"], "results": collectionResults } return jsonify({"results": searchResults})
def create_workout(): if not request.form or not 'title' in request.form: abort(400) workout = { 'title': request.form['title'], 'user': request.form['user'], 'strokes': request.form['strokes'], 'lengths': request.form['lengths'], 'calories': request.form['calories'], 'raw': request.form['raw'] } mongo.db.workouts.insert(workout) return jsonify( { 'workouts': workout } ), 201
def api_getguest(key): if key != API_KEY: return api_log_wrong_key() guest = request.form['guest'] profile = mongodb.guest_collection.find_one({'full_name': guest}) photos = mongodb.photo_collection.find({'profile_type': "guest", 'profile_name': guest}) photos_list = [] for photo in photos: photos_list.append(photo) return jsonify(result="success", profile=profile, photos=photos_list)
def api_getuser(key): if key != API_KEY: return api_log_wrong_key() user = request.form['user'] profile = mongodb.user_collection.find_one({'username': user}) photos = mongodb.photo_collection.find({'profile_type': "user", 'profile_name': user}) photos_list = [] for photo in photos: photos_list.append(photo) return jsonify(result="success", profile=profile, photos=photos_list)
def _projeto(tipo, numero, ano, json=False): pid = tipo.lower() + '-' + numero + '-' + ano projeto = mongo.db.legis.find_one({"_id": pid}) explicacoes = mongo.db.explicacoes.find() # Monta tramitacao for p in projeto['tramitacoes']: if p['data_inicio'] == '': p['data_inicio'] = futuro() p['tipo'] = 'tramita' if projeto.has_key('encerramento'): projeto['tramitacoes'].append({ 'data_inicio': projeto['data_encerramento'], #pensar 'tramitacao': projeto['encerramento'], 'tipo': 'encerramento' }) for p in projeto['tramitacoes']: if p['data_inicio'] > projeto['data_encerramento'] and p[ 'tipo'] == 'tramita': p['tipo'] = 'arquivo' for c in projeto['comissoes']: if not any(p['tramitacao'] == c for p in projeto['tramitacoes']) and not projeto.has_key( 'encerramento'): #adicionar tramitacao conjunta projeto['tramitacoes'].append({ 'tipo': 'comdes', 'tramitacao': c, 'data_inicio': futuro() }) if not projeto: abort(404) if json == 'json': return jsonify(projeto) elif json == False: return render_template('legis.html', p=projeto, explicacoes=explicacoes)
def post(self): parser = reqparse.RequestParser() parser.add_argument("problemID", type=str, required=True, location="json") parser.add_argument("userID", type=str, required=True, location="json") parser.add_argument("file", type=FileStorage, required=True, location="files") entry = parser.parse_args() try: if db.problem.find_one({"_id": ObjectId(entry['problemID'])}) == None: abort(400) if db.user.find_one({"_id": entry['userID']}) == None: abort(400) except: abort(400) problemName = db.problem.find_one( {"_id": ObjectId(entry['problemID'])})['name'] gradingFilePath = os.path.join( os.path.join(PROBLEMS_DIR, problemName.lower()), GRADING_SCRIPT) command = "python3 " + gradingFilePath + " \"" + entry[ "file"].stream + "\"" gradingOutput = subprocess.Popen( shlex.split(command.replace('\\', '/')), stdout=subprocess.PIPE).communicate()[0] structuredGradingOutput = json.loads(gradingOutput) status_code = None if "score" in structuredGradingOutput: entry["score"] = structuredGradingOutput["score"] entry.pop("file") db.entry.insert_one(entry) status_code = 201 else: status_code = 400 return jsonify(structuredGradingOutput, status=status_code)
def post(self): parser = reqparse.RequestParser() parser.add_argument("schoolID", type=str, required=True, location="json") parser.add_argument("userID", type=str, required=True, location="json") args = parser.parse_args() user = db.tempUser.find_one({"_id": args["userID"]}) if user is None: abort(400) school = db.school.find_one({"_id": args["schoolID"]}) if school is None: abort(400) user["schoolID"] = args["schoolID"] db.user.insert_one(user) session['userID'] = user["_id"] return jsonify(user, status=201)
def api_get_user_feed_entries(): user = users.load_user_by_apikey(request.args['apikey']) feeds = current_user.get_feeds_as_dict(True) return jsonify(feeds)
def get(self): return jsonify([a for a in db.user.find({})])
def get(self, blogID): blog = db.blog.find_one({"_id": blogID}) if blog is None: abort(404) return jsonify(blog)
def get(self): return jsonify([a for a in db.blog.find({}).sort('_id', -1)])
def get(self): return jsonify([a for a in db.event.find({})])
def get(self): return jsonify([a for a in db.problem.find({}).sort('_id', -1)])
def delete(self): if "userID" not in session: abort(404) session.pop("userID") return jsonify({"result": True})