def fake_data(): db = firestore.client() doc_ref = db.collection("users").document("manummasson8") doc_ref.delete() doc_ref.set({}) for month in range(1, 13): fireBatch = db.batch() for day in range(1, 29): if day % 2 == 0: # make it more common to do nothing x = randint(0, 3) obj = [] for amount in range( 0, x ): # some days add multiple tasks, some days have 0 tasks. obj.append({ 'title': "Physics", 'desc': "Circular Motion " + str(amount), 'date': datetime.datetime(2019, month, day).strftime('%Y-%m-%d') }) if obj: fireBatch.update(doc_ref, {str(month): ArrayUnion(obj)}) if day % 3 == 0: # make it more common to do nothing x = randint(0, 3) obj = [] for amount in range( 0, x ): # some days add multiple tasks, some days have 0 tasks. obj.append({ 'title': "Economics", 'desc': "Circular Motion " + str(amount), 'date': datetime.datetime(2019, month, day).strftime('%Y-%m-%d') }) if obj: fireBatch.update(doc_ref, {str(month): ArrayUnion(obj)}) fireBatch.set(doc_ref, { 'name': "manummasson8", 'currMonth': "4", 'tasks': True, }, merge=True) fireBatch.commit( ) # in month loop since only 500 requests per batch allowed.
def update(self, new_flag_count, flag_user, uuid, db): self.flag_users.append(flag_user) self.flag_count = new_flag_count db.collection(Classifier.collection_name).document(uuid).update({ u"flag_users": ArrayUnion([flag_user]), u"flag_count": new_flag_count })
def update_add_upvote(self, uid, new_count, uuid, db): self.upvoters.append(uid) self.count = new_count db.collection(Upvote.collection_name).document(uuid).update({ u"upvoters": ArrayUnion([uid]), u"count": self.count })
def add_report(self, incident_id, db): self.reports.append( db.collection(Event.collection_name).document(incident_id)) db.collection(self.collection_name).document(self.user_uuid).update({ u'reports': ArrayUnion( [db.collection(Event.collection_name).document(incident_id)]) }) return self.user_uuid
def add_flag_to_user(username, server_code, flag): """ Add flag to user, true if success, else false """ room = list(u2r.where('rid', '==', server_code).get()) if room: for user in u2r.document(room[0].id).collection("users").get(): if user.get("username") == username: return bool(u2r.document(room[0].id).collection("users").document(user.id) .update({"flags": ArrayUnion([flag])})) return False
def update_doc_array(): db = firestore.Client() # [START fs_update_doc_array] city_ref = db.collection(u'cities').document(u'DC') # Atomically add a new region to the 'regions' array field. city_ref.update({u'regions': ArrayUnion([u'greater_virginia'])}) # // Atomically remove a region from the 'regions' array field. city_ref.update({u'regions': ArrayRemove([u'east_coast'])}) # [END fs_update_doc_array] city = city_ref.get() print(u'Updated the regions field of the DC. {}'.format(city.to_dict()))
def convert_data(v): # Replace the strings 'ServerTimestamp' and 'Delete' with the corresponding # sentinels. from google.cloud.firestore_v1beta1 import ArrayRemove from google.cloud.firestore_v1beta1 import ArrayUnion from google.cloud.firestore_v1beta1 import DELETE_FIELD from google.cloud.firestore_v1beta1 import SERVER_TIMESTAMP if v == "ServerTimestamp": return SERVER_TIMESTAMP elif v == "Delete": return DELETE_FIELD elif isinstance(v, list): if v[0] == "ArrayRemove": return ArrayRemove([convert_data(e) for e in v[1:]]) if v[0] == "ArrayUnion": return ArrayUnion([convert_data(e) for e in v[1:]]) return [convert_data(e) for e in v] elif isinstance(v, dict): return {k: convert_data(v2) for k, v2 in v.items()} else: return v
def webhook_handler(): body = request.get_json() logging.info('Request body:') logging.info(body) global labels_chat_id global labels if 'callback_query' in body: # Callback received try: query_id = body['callback_query'].get('id') data = body['callback_query'].get('data') user_id = body['callback_query'].get('from').get('id') chat_id = body['callback_query'].get('message').get('chat').get( 'id') inline_message_id = body['callback_query'].get('message').get( 'message_id') if body['callback_query'].get('message').get( 'reply_to_message') is not None: reply_id = body['callback_query'].get('message').get( 'reply_to_message').get('message_id') reply_from_id = body['callback_query'].get('message').get( 'reply_to_message').get('from').get('id') if data == 'no': bot.delete_message(chat_id, inline_message_id) if data == 'yes': if user_id == reply_from_id or user_id == secrets[ 'alessandro_id']: photos = body['callback_query'].get('message').get( 'reply_to_message').get('photo') if photos is not None: photo_id = photos[-1].get('file_id') if photo_id is not None: reply_markup = { 'inline_keyboard': [[{ 'text': 'Primo', 'callback_data': 'none' }, { 'text': '1', 'callback_data': 'primo1' }, { 'text': '2', 'callback_data': 'primo2' }, { 'text': '3', 'callback_data': 'primo3' }], [{ 'text': 'Riso', 'callback_data': 'riso' }], [{ 'text': 'Secondo', 'callback_data': 'none' }, { 'text': '1', 'callback_data': 'secondo1' }, { 'text': '2', 'callback_data': 'secondo2' }], [{ 'text': 'Contorno', 'callback_data': 'none' }, { 'text': '1', 'callback_data': 'contorno1' }, { 'text': '2', 'callback_data': 'contorno2' }, { 'text': '3', 'callback_data': 'contorno3' }, { 'text': '4', 'callback_data': 'contorno4' }], [{ 'text': 'Non vengo', 'callback_data': 'noshow' }, { 'text': 'Ordinato', 'callback_data': 'ordered' }]] } reply_markup = json.dumps(reply_markup) post = bot.send(chat_id, msg="Menù pranzo", photo_id=photo_id, keyboard=reply_markup) post_json = post.decode('utf8') post_id = json.loads(post_json)['result'].get( 'message_id') orders = bot.send(chat_id, msg="Ordinazioni:") orders_json = orders.decode('utf8') orders_id = json.loads(orders_json)['result'].get( 'message_id') init_database(orders_id, chat_id) bot.pin(post_id, chat_id) bot.delete_message(chat_id, inline_message_id) bot.delete_message(chat_id, reply_id) elif data == 'none': pass else: doc_ref = db.collection(u'data').document(u'one') doc = doc_ref.get() order = Order.from_dict(doc.to_dict()) if body['callback_query'].get('from').get( 'first_name') is not None: username = body['callback_query'].get('from').get( 'first_name') elif body['callback_query'].get('from').get( 'username') is not None: username = body['callback_query'].get('from').get( 'username') else: username = body['callback_query'].get('from').get('id') if data == 'ordered': doc_ref.update({'ordered': username}) elif data == 'noshow': if username in getattr(order, data): doc_ref.update({data: ArrayRemove([username])}) else: doc_ref.update({'seats': ArrayRemove([username])}) for key in list(Order.default_labels.keys()): doc_ref.update({key: ArrayRemove([username])}) doc_ref.update({data: ArrayUnion([username])}) else: if username in getattr(order, data): doc_ref.update({data: ArrayRemove([username])}) else: doc_ref.update({data: ArrayUnion([username])}) doc_ref.update({'seats': ArrayUnion([username])}) doc_ref.update({'noshow': ArrayRemove([username])}) doc = doc_ref.get() order = Order.from_dict(doc.to_dict()) bot.edit_message(chat_id, order.post_id, str(order), parse_mode="Markdown") return bot.answer_callback(query_id) except Exception as e: logging.info(e) return make_response('Error in callback handling') # Useful variables try: message = body['message'] except Exception: if body.get('edited_message') is not None: message = body['edited_message'] else: return json.dumps(body) message_id = message.get('message_id') text = message.get('text') is_forward = message.get('forward_from') fr = message.get('from') fr_id = fr.get('id') chat = message['chat'] chat_id = chat['id'] is_private_chat = (fr_id == chat_id) reply_message = None reply_text = None fr = message.get('from') if message.get('reply_to_message') is not None: reply_message = message.get('reply_to_message') if message.get('reply_to_message').get('text') is not None: reply_text = message.get('reply_to_message').get('text') if (not text) or is_forward: # Image received? timestamp = message.get('date') message_date = datetime.fromtimestamp(timestamp).astimezone( pytz.timezone('Europe/Rome')) caption = message.get('caption') photos = message.get('photo') if 11 <= message_date.hour <= 13: if fr_id in secrets['sender_ids']: if photos is not None: photo_id = photos[-1].get('file_id') if photo_id is not None: reply_markup = { 'inline_keyboard': [[{ 'text': 'Yes', 'callback_data': 'yes' }]] } reply_markup = json.dumps(reply_markup) return bot.send(chat_id, msg="Menù pranzo?", reply=message_id, keyboard=reply_markup) if (caption and caption == 'testphoto') and (fr_id == secrets['alexalder_id'] or fr_id == secrets['alessandro_id']): photo_id = photos[-1].get('file_id') if photo_id is not None: reply_markup = { 'inline_keyboard': [[{ 'text': 'Yes', 'callback_data': 'yes' }, { 'text': 'No', 'callback_data': 'no' }]] } reply_markup = json.dumps(reply_markup) return bot.send(chat_id, msg="Menù pranzo?", reply=message_id, keyboard=reply_markup) print('no text') return json.dumps(body) else: uniformed_text = text.lower() if text.startswith('/labels'): labels_chat_id = chat_id return bot.send( chat_id, msg="Manda la lista dei piatti, separati andando a capo (9 linee)") elif text.startswith('/conto'): return bot.send(chat_id, msg=secrets['bill_address']) elif text.startswith('/ping'): answers = ['Welo', 'Bopo'] return bot.send(chat_id, msg=random.choice(answers)) elif labels_chat_id == chat_id: lines = [] if ';' in text: lines = [x.strip() for x in text.split(';')] else: lines = text.splitlines() if len(lines) == 9: doc_ref = db.collection(u'data').document(u'two') doc = doc_ref.get() dic = doc.to_dict() keys = list(Order.default_labels.keys()) for i in range(9): dic[keys[i]] = lines[i].strip() dic[keys[10]] = datetime.today().day db.collection(u'data').document(u'two').set(dic) labels = None doc_ref = db.collection(u'data').document(u'one') doc = doc_ref.get() order = Order.from_dict(doc.to_dict()) bot.edit_message(order.chat_id, order.post_id, str(order), parse_mode="Markdown") reply_markup = { 'inline_keyboard': [[{ 'text': dic['primo1'], 'callback_data': 'primo1' }], [{ 'text': dic['primo2'], 'callback_data': 'primo2' }], [{ 'text': dic['primo3'], 'callback_data': 'primo3' }], [{ 'text': 'Riso', 'callback_data': 'riso' }], [{ 'text': dic['secondo1'], 'callback_data': 'secondo1' }], [{ 'text': dic['secondo2'], 'callback_data': 'secondo2' }], [{ 'text': dic['contorno1'], 'callback_data': 'contorno1' }], [{ 'text': dic['contorno2'], 'callback_data': 'contorno2' }], [{ 'text': dic['contorno3'], 'callback_data': 'contorno3' }], [{ 'text': dic['contorno4'], 'callback_data': 'contorno4' }], [{ 'text': 'Non vengo', 'callback_data': 'noshow' }, { 'text': 'Ordinato', 'callback_data': 'ordered' }]] } reply_markup = json.dumps(reply_markup) bot.edit_caption(order.chat_id, order.post_id - 1, "Menù pranzo", keyboard=reply_markup) return bot.send(chat_id, msg="Label aggiornate") elif is_private_chat: return bot.send( chat_id, msg= "Errore nella lettura, il messaggio deve avere solo 9 righe con i 9 nomi dei piatti" ) return json.dumps(body)
def update_add_participant(self, new_participant_uuid, incident_id, db): self.participants.append(new_participant_uuid) db.collection(Comment.collection_name).document(incident_id).update({ u"participants": ArrayUnion([new_participant_uuid]), })
import firebase_admin from firebase_admin import credentials, firestore from google.cloud.firestore_v1beta1 import ArrayRemove, ArrayUnion cred = credentials.Certificate("key.json") firebase_admin.initialize_app(cred) db = firestore.client() doc_ref = db.collection('users').document('massons').collection( 'tasks').document('physics') doc_ref.set({'tasks': True}, merge=True) doc_ref.update({'subTasks': ArrayUnion([{'date': '23', 'desc': 'yoldso'}])}) doc_ref = db.collection('users').document('manummasson8') doc = doc_ref.get() print(u'Document data: {}'.format(doc.to_dict()))
# [END_EXCLUDE] def __repr__(self): return ( u'City(name={}, country={}, population={}, capital={}, regions={})' .format(self.name, self.country, self.population, self.capital, self.regions)) ## create an instnace of a class city = City(u'New Delhi', u'Delhi', u'India') print(city.to_dict()) ## creating a collection and add data to document doc_ref = db.collection(u'cities').document(u'new-delhi') doc_ref.set(city.to_dict(), merge=True) # update the data doc_ref.update({ u'capital': True, u'timestamp': firestore.SERVER_TIMESTAMP, u'regions': ['old_delhi', 'new_delhi', 'karol_bag', 'sarojni'] }) ## update the array -> add and remove doc_ref.update({u'regions': ArrayUnion([u'hauz_khas'])}) doc_ref.update({u'regions': ArrayRemove([u'new_delhi'])}) # verify data added print("Sucessfully added to database.")
def create_channel_conversation_for_user(self, uid, uid_contact, uuid): doc_ref_vendor = self.db.collection(u'UsersDetails').document(uid) doc_ref_vendor.update( {u'MessageChannel': ArrayUnion([{ uid_contact: uuid }])})
def add_message_to_conversation(self, message, uuid_conv, uid): doc_ref = self.db.collection(u'Messages').document(uuid_conv) doc_ref.update({u'Messages': ArrayUnion([{uid: message}])})
def save(self, incident_id, db): db.collection(Event.collection_name).document(incident_id).update( {u'images': ArrayUnion([self.to_dict()])}) return self.uuid
def createEvent(self, title, desc, dateCreated): # logging.basicConfig(filename='myapp.log', level=logging.INFO) try: print("Create event?", title, desc, dateCreated) doc_ref = db.collection('users').document(self.userName) doc = doc_ref.get().to_dict() currentMonth = datetime.datetime.now().month print("todict") # print(doc['tasks']) if not 'tasks' in doc: print("in if") doc_ref.set( { 'name': self.userName, 'currMonth': currentMonth, 'tasks': True, '0': [], '1': [], '2': [], '3': [], '4': [], '5': [], '6': [], '7': [], '8': [], '9': [], '10': [], '11': [], '12': [] }, merge=True) print("created firebase") # monthOffset = 0 print("beforebatch") fireBatch = db.batch() calBatch = self.cal.new_batch_http_request() print("afterbach") for r in gCal.spacings: time = dateCreated + datetime.timedelta(days=r) time = time.strftime('%Y-%m-%d') print("working????") month = int(time.split("-")[1]) print("after split") # monthOffset = int(time.split("-")[1]) - datetime.datetime.now().month # print(monthOffset) timers = time time += "T00:00:00-00:00" event = gCal.eventSchema(title, desc, time, self.TIMEZONE) print("a") calBatch.add(self.cal.events().insert(calendarId=self.calID, body=event)) print(event.get('htmlLink')) print("b") month = str(month) fireBatch.update( doc_ref, { month: ArrayUnion([{ 'title': title, 'desc': desc, 'date': timers, }]) }) print("c") print("a1") fireBatch.commit() calBatch.execute() print("a2") except Exception as e: print(e)
def _manage_db_data(self): """Return Data based on request..reading the data will check for the site ID and return response only if the password is provided. Writing the data will take the site_id """ data_action: int = self.js_data.get("db_action") if data_action == READ_TYPE: """Read the data. Should only be uswed in the dashboard or data.pycode.tk""" pw: str = self.js_data.get("password", "") if not pw: return self._err("No Password Provided") meta_doc: DocumentReference = manager.get_document( f"/{SITE_META}/{self.origin}") if not manager.document_exists(meta_doc): return self._err("Incorrect username or password") doc_snap_shot: DocumentSnapshot = meta_doc.get() site_id = doc_snap_shot.get("site_id") if not check_password_hash(doc_snap_shot.get("hashedPassword"), pw): return self._err("Incorrect username or password") doc: CollectionReference = manager.get_collection( f"/{SITE_DATA}/{site_id}/{ANALYTICS}") actions_doc_snap: DocumentSnapshot = doc.document("ACTIONS").get() visiter_doc_snap: DocumentSnapshot = doc.document( "VISITOR_DATA").get() return { "actions": actions_doc_snap.to_dict(), "visitor_data": visiter_doc_snap.to_dict(), } if data_action == WRITE_TYPE: """js_data should be a dictionary with the keys: INTERNAL_JSON_CONFIG_DATA,INDIVIDUAL_VISIT_DATA,SESSION_STORAGE_DATA """ exclude_updates_for: list = self.js_data.get("exclude", []) _site_id: str = manager.get_document( f"{SITE_META}/{self.origin}").get().get("site_id") if _site_id != self.site_id: return self._err("Invalid Site ID") doc: DocumentReference = manager.get_document( f"{SITE_DATA}/{self.site_id}") col: CollectionReference = doc.collection(ANALYTICS) analytics_arr: DocumentReference = col.document("VISITOR_DATA") internal_arr: DocumentReference = col.document("INTERNAL_DATA") actions_arr: DocumentReference = col.document("ACTIONS") analytics_arr_exists = manager.document_exists(analytics_arr) doc.set({"last_update_from_backend": now()}) visit_id = self.js_data.get("visit_id") for field in ANALYTICS_FIELDS: name: str = field.get("NAME") if name in exclude_updates_for: continue set_by_server: bool = field.get("SET_BY_SERVER", False) expected_type: Any = field.get( "EXPECTED_TYPE" ) # Check for malformed input..like [object Object] if name not in self.js_data and not set_by_server: return self._err(f"Required Field Missing - {name}") if set_by_server: """Values that will be set by the server..like VIEW_COUNT""" data_fields: DocumentReference = col.document(name) data_field_snapshot: DocumentSnapshot = data_fields.get() if name == "VIEW_COUNT" and self.js_data.get( "update_view_count"): if manager.document_exists(data_fields): data_fields.update({ "value": data_field_snapshot.get("value") + 1 }) else: data_fields.set({ "value": data_field_snapshot.get("value") + 1 }) continue if name == "INTERNAL_JSON_CONFIG_DATA": """internal json data including errors""" config = self.js_data[name] if not isinstance(config, expected_type): return self.__err_msg(name) internal_arr.set({name: {visit_id: config}}, merge=True) continue if name == "INDIVIDUAL_VISIT_DATA": """Indiviual user data including session tokens, user agent, time spent on the site (sent during window.onunload or other event specified by the user """ visit_data = self.js_data[name] visit_data["id"] = visit_id visit_data["addr"] = self.headers.get("X-Forwarded-For") if not isinstance(visit_data, expected_type): return self.__err_msg(name) if analytics_arr_exists: analytics_arr.update({name: ArrayUnion([visit_data])}) else: analytics_arr.set({name: [visit_data]}, merge=True) analytics_arr_exists = True continue if name == "SESSION_STORAGE_DATA": """Session storage data.. useful for tracking session times and visit counters""" sess_data = self.js_data[name] sess_data["id"] = visit_id if not isinstance(sess_data, expected_type): return self.__err_msg(name) if analytics_arr_exists: analytics_arr.update({name: ArrayUnion([sess_data])}) else: analytics_arr.set({name: [sess_data]}, merge=True) analytics_arr_exists = True continue if name == "ACTIONS": action_data = self.js_data.get(name) if not action_data: continue if not isinstance(action_data, expected_type): return self.__err_msg(name) if manager.document_exists(actions_arr): actions_arr.update({name: ArrayUnion([action_data])}) else: actions_arr.set({name: [action_data]}) continue return {"success": True} else: return self._err("bad data_action type")