def test_document_update_transformerArrayUnionNested(self):
        fs = MockFirestore()
        fs._data = {
            'foo': {
                'first': {
                    'nested': {
                        'arr': [1]
                    },
                    'other': {
                        'labels': ["a"]
                    },
                }
            }
        }
        fs.collection('foo').document('first').update({
            'nested': {
                'arr': firestore.ArrayUnion([2])
            },
            'other': {
                'labels': firestore.ArrayUnion(["b"]),
                'smoked': 'salmon'
            },
        })

        doc = fs.collection('foo').document('first').get().to_dict()
        self.assertEqual(
            doc, {
                'nested': {
                    'arr': [1, 2]
                },
                'other': {
                    'labels': ["a", "b"],
                    'smoked': 'salmon'
                }
            })
예제 #2
0
def saveIngredients(ingredients, id):
    for ingredient in ingredients:
        ingredientRef = db.collection('ingredients').document(ingredient)
        try:
            ingredientRef.update({u'usedIn': firestoreCloud.ArrayUnion([id])})
        except NotFound:
            ingredientRef.set({u'usedIn': firestoreCloud.ArrayUnion([id])})
예제 #3
0
    def insert_monitor(self, user, object_uri, percentage):
        ref = db.collection(u'users').document(user)

        if ref.get().exists:
            ref.update({object_uri: firestore.ArrayUnion([percentage])})
        else:
            ref.set({object_uri: firestore.ArrayUnion([percentage])})

        return True
예제 #4
0
    def post_booking(self, date, time, seat):
        if seat is None:
            return None

        try:
            cinema_ref.document(f'{date}T{time}').update(
                {'postiPrenotati': firestore.ArrayUnion([seat])})
        except Exception:
            cinema_ref.document(f'{date}T{time}').set(
                {'postiPrenotati': firestore.ArrayUnion([seat])})
예제 #5
0
 def post_book_cinema(self, date, time, seat):
     ref = db.collection(u'cinema').document(f'{date}T{time}')
     if ref.get().exists:
         ref.update({
                     "bookedSeats": firestore.ArrayUnion([seat])
         })
     else:
         ref.set({
                     "bookedSeats": firestore.ArrayUnion([seat])
         })
예제 #6
0
파일: Database.py 프로젝트: realmayus/chime
 def create_if_non_existant(self, user_id: int, name: str):
     profile: DocumentReference = self.db.collection(str(user_id)).document("profile")
     if check_if_playlist_exists(profile, name):
         return
     playlist_id = str(uuid.uuid4())
     playlist_doc: DocumentReference = self.db.collection(str(user_id)).document(playlist_id)
     playlist_doc.set({"contents": []})
     try:
         profile.update({"playlists": firestore.ArrayUnion([{"name": name, "ref": playlist_id}])})
     except google.api_core.exceptions.NotFound:
         profile.set({"playlists": []}, merge=True)
         profile.update({"playlists": firestore.ArrayUnion([{"name": name, "ref": playlist_id}])})
     return playlist_doc
 def test_document_update_transformerArrayUnionBasic(self):
     fs = MockFirestore()
     fs._data = {"foo": {"first": {"arr": [1, 2]}}}
     fs.collection("foo").document("first").update(
         {"arr": firestore.ArrayUnion([3, 4])})
     doc = fs.collection("foo").document("first").get().to_dict()
     self.assertEqual(doc["arr"], [1, 2, 3, 4])
예제 #8
0
    def add_tag(self, word: str, tag: str):
        """ タグ追加
        """
        tag_data = tag_service.get_tag(tag)
        if tag_data:
            docs = db.collection(self.collection_name).where(
                "word", "==", word).limit(1).get()

            if docs:
                set_data = {
                    "tags": firestore.ArrayUnion([tag_data["text"]]),
                    "tags_cnt": {
                        tag_data["text"]: firestore.Increment(1)
                    },
                    "updated_at": datetime.now(),
                    "cnt": firestore.Increment(1),
                }
                # 初めてのタグはlikeに計算
                if tag_data["text"] not in docs[0].to_dict()["tags"]:
                    set_data["like"] = firestore.Increment(tag_data["pnt"])

                docs[0]._reference.set(set_data, merge=True)
                return True

        return False
예제 #9
0
def update_image_metadata(bucket_name, image_name):
    labels = request.get_json(force=True)
    doc_ref = db.collection('images').document(bucket_name).collection(
        'labels').document(image_name)
    doc = doc_ref.get()
    curr_label_groups = list(doc.get('labels'))
    curr_labels = [lab.get('group') for lab in doc.get('labels')]
    if len(labels) == 0:
        doc_ref.update({'valid': False})
    else:
        doc_ref.update({'valid': True})
    for label in labels:
        # each label looks like { groupName: 'group-name', value: val }
        if label['groupId'] in curr_labels:
            ind = curr_labels.index(label['groupId'])
            tmp = curr_label_groups.pop(ind)
            doc_ref.update({'labels': firestore.ArrayRemove([tmp])})
        doc_ref.update({
            'labels':
            firestore.ArrayUnion([{
                'group': label['groupId'],
                'values': label['value']
            }])
        })
    doc_ref.update({'seen': True, 'lastSeen': None})

    return {}
    def update_repos(self, pid, data):
        project = self._db.collection('projects').document(pid)

        print(data)

        if project.get().exists:
            if not self.__is_project_owner(project.get().to_dict(), self._uid):
                return None, status_code.OK

            action = data['repositories']['action']
            if action == 'update':
                project.update({
                    'repositories.Github':
                    firestore.ArrayUnion(data['repositories']['Github']),
                    'updated':
                    firestore.SERVER_TIMESTAMP
                })
            elif action == 'remove':
                project.update({
                    'repositories.Github':
                    firestore.ArrayRemove(data['repositories']['Github']),
                    'updated':
                    firestore.SERVER_TIMESTAMP
                })
            else:
                return 'missing action', status_code.BAD_REQUEST
            return None, status_code.OK
        else:
            return None, status_code.NOT_FOUND
예제 #11
0
 def post_object(self, user_uuid, object_id, percentage):
     ref = price_ref.document(object_id)
     try:
         ref.update({
             'items': firestore.ArrayUnion([{
                 'user_uuid' : user_uuid,
                 'percentage': percentage
             }])
         })
     except Exception:
         ref.set({
             'items':firestore.ArrayUnion([{
                 'user_uuid' : user_uuid,
                 'percentage': percentage
             }])
         })
예제 #12
0
def associate_orphans(deploy_stage="stage"):
    orphaned = orphaned_clusters(deploy_stage, True)
    for xp in orphaned:
        for state in orphaned[xp]["clusters"]:
            this_set = orphaned[xp]["clusters"][state]
            if len(this_set) > 0:
                pool_ref = DB.collection(deploy_stage + "pool").document(xp)
                pool_ref.update({state: firestore.ArrayUnion(this_set)})
    def test_document_update_transformerArrayUnionNonExistent(self):
        fs = MockFirestore()
        fs._data = {'foo': {'first': {'spicy': 'tuna'}}}
        fs.collection('foo').document('first').update(
            {'arr': firestore.ArrayUnion([1])})

        doc = fs.collection('foo').document('first').get().to_dict()
        self.assertEqual(doc, {'arr': [1], 'spicy': 'tuna'})
예제 #14
0
파일: Database.py 프로젝트: realmayus/chime
 def add_to_playlist(self, user_id: int, name: str, tracks: List[Track]):
     profile: DocumentReference = self.db.collection(str(user_id)).document("profile")
     playlist_doc: DocumentReference = self.db.collection(str(user_id)).document(check_if_playlist_exists(profile, name))
     if playlist_doc is False:
         raise DatabaseExceptions.PlaylistDoesNotExistException()
     playlist_doc.update({"contents": firestore.ArrayUnion(
                         [{"title": track_to_add.title, "author": track_to_add.author, "data": track_to_add.id, "url": track_to_add.uri, "id": str(uuid.uuid4()), "duration": track_to_add.duration} for
                          track_to_add in tracks])})
예제 #15
0
def add_follower(team_id, chat_id):
    user = generate_user(chat_id)

    print(f"Adding follower {user} to {team_id}.")

    team_document_ref = db.collection("teams").document(str(team_id))
    team_document_ref.set(
        merge=True, document_data={u"followers": firestore.ArrayUnion([user])})
예제 #16
0
 def update_create_if_missing(self, objectId):
     # [START update_create_if_missing]
     user_ref = Attendance.db.collection(u'users').document(f"{objectId}")
     uuidDate = self.getUuidDate()
     doc = user_ref.get()
     if doc.exists:
         if self.check(doc):
             user_ref.update(
                 {u'contacts_temp': fire.ArrayUnion([f"{uuidDate}"])})
         else:
             user_ref.set(
                 {u'contacts_temp': fire.ArrayUnion([f"{uuidDate}"])},
                 merge=True)
     else:
         # Atomically add a new region to the 'regions' array field.
         user_ref.set({u'contacts_temp': fire.ArrayUnion([f"{uuidDate}"])},
                      merge=True)
     return uuidDate
예제 #17
0
    def create(self, account_create: AccountCreate) -> Account:
        data = account_create.dict()
        # create document inside client document
        client_ref = self.get_client_ref(data['client_id'])
        client_ref.update({self.array_name: firestore.ArrayUnion([data])})
        # the object will be the last one created
        account = client_ref.get().to_dict()['accounts'][-1]

        if account['id'] == data['id']:
            return Account(**account)
예제 #18
0
def _point(user_id, user_torate, event):
    def switch_event(event):
        return {'over': 'under', 'under': 'over'}[event]

    edit_profile(
        return_get=0,
        user_id=user_torate,
        dict_update={
            'point_' + event: gcloud_firestore.Increment(1),
            event + '_by': gcloud_firestore.ArrayUnion([user_id])
        },
        #dict_set={ 'spent_over': 0, 'spent_under': 0, 'point_'+event: 1,'point_'+switch_event(event): 0, event+'_by': gcloud_firestore.ArrayUnion([user_id]), 'day': today() }
        dict_set={
            'spent_over': 0,
            'spent_under': 0,
            'point_' + event: 1,
            event + '_by': gcloud_firestore.ArrayUnion([user_id]),
            'day': today()
        }  #remove 0
    )
예제 #19
0
    def order_intent_no(request):
        response = None
        user_id = request.userid

        # Get the current order for the user
        doc_ref_current_order = Factory.firestore_client.collection(u'current_order').document(user_id)
        if doc_ref_current_order.get().exists:

            # create key  closed timestamp for the order
            doc_ref_current_order.update({u'closed_timestamp': firestore.SERVER_TIMESTAMP})
            doc_ref_dict = doc_ref_current_order.get().to_dict()

            # remove from current_order collection and move to history collection

            del doc_ref_dict[u'current_item_count']
            drinks_dict = doc_ref_current_order.get().to_dict().get(u'drinks')

            doc_ref_history = Factory.firestore_client.collection(u'history').document(user_id)
            if doc_ref_history.get().exists:
                orders_dict = doc_ref_history.get().to_dict().get(u'orders')
                if orders_dict is None:
                    doc_ref_history.set({u'orders': [doc_ref_dict]})
                else:
                    doc_ref_history.update({u'orders': firestore.ArrayUnion([doc_ref_dict])})
            else:
                doc_ref_history.set({u'orders': [doc_ref_dict]})

            # delete from current_order
            doc_ref_current_order.delete()

            response_formatter = ResponseFormatter(drinks_dict)
            response_string = response_formatter.format_complete_order()
            if 'guest' not in request.userid:
                response = {'fulfillmentText': 'Your order \n\n' + response_string + ' \n\n is confirmed.',}
            else:
                response = {
                    "payload": {
                        "google": {
                            "expectUserResponse": True,
                            "systemIntent": {
                                "intent": "actions.intent.SIGN_IN",
                                "data": {
                                    "@type": "type.googleapis.com/google.actions.v2.SignInValueSpec",
                                     "optContext": 'Your order \n\n' + response_string + ' \n\n is confirmed. \n\n' +
                                                    'Would you like to sign in  help in personalization? \n \n For that '
                                }
                            }
                        }
                    }
                }
        else:
            response = {'fulfillmentText': 'There is no existing order to place'}

        return response
예제 #20
0
def create_tr(transaction: Transaction, word_create: models.WordCreate,
              tags: List[models.TagAct], taught: str, collect_word: str,
              collect_unknown: str, collect_session: str):
    """ 新規単語の追加で呼び出すトランザクション処理
    """
    # unknownsコレクションにある場合は削除する
    docs = db.collection(collect_unknown).where("word", "==",
                                                word_create.word).stream()
    for doc in docs:
        transaction.delete(doc._reference)
        system_service.dec_unknown()

    set_like = 0
    set_tags = []
    set_tags_cnt = {}
    for tag in tags:
        set_tags.append(tag["text"])
        set_tags_cnt[tag["text"]] = firestore.Increment(1)
        set_like = set_like + tag["pnt"]

    # wordsコレクションに追加
    word_data = models.WordAll(**word_create.dict()).dict()
    word_data["taught"] = taught
    word_data["like"] = set_like
    word_data["tags"] = set_tags
    word_data["tags_cnt"] = set_tags_cnt
    word_data["cnt"] = firestore.Increment(1)
    word_data["index"] = system_service.get_system_data()["word_cnt"]
    word_ref = db.collection(collect_word).document()
    transaction.set(word_ref, word_data)

    # sessionsコレクション更新
    session_ref = db.collection(collect_session).document(document_id=taught)
    session_data = {
        "teach_words": firestore.ArrayUnion([word_create.word]),
        "teach_refs": firestore.ArrayUnion([word_ref]),
        "teach_cnt": firestore.Increment(1),
    }
    transaction.set(session_ref, session_data, merge=True)

    return word_ref
예제 #21
0
 def update_attr_by_id(self, cls, id, attr, value):
     ref = self.db.collection(cls.__name__).document(id)
     res = cls.get_by_attr('id', id)
     if not res:
         return False
     obj = res[0]
     if obj:
         if type(obj.get(attr)) == list:
             ref.update({attr: firestore.ArrayUnion([value])})
             return True
     ref.update({attr: value})
     return True
예제 #22
0
def add_players_to_room(room_id, users_ids, admin_rights=False):
    """Add one or many players to a room

    Attributes:
        room_id -- Id of the room document
        users_ids -- Array of user id
        admin_rights -- Wether or not added users should have admin rights
    """
    room_id = room_id.lower()
    doc = db.collection("rooms").document(room_id).get()

    if not doc.exists:
        raise DocumentWasNotFoundError("rooms", room_id)

    try:
        batch = db.batch()
        users_ids_ref = []
        for user_id in users_ids:
            user_id = user_id.lower()

            room_ref = db.collection("rooms").document(room_id)
            batch.update(
                db.collection("users_rooms").document(user_id),
                {"rooms": firestore.ArrayUnion([room_ref])})
            users_ids_ref.append(db.collection("users").document(user_id))

        if admin_rights:
            batch.update(
                db.collection("rooms_users").document(room_id), {
                    "users": firestore.ArrayRemove(users_ids_ref),
                    "admin": firestore.ArrayUnion(users_ids_ref)
                })
        else:
            batch.update(
                db.collection("rooms_users").document(room_id),
                {"users": firestore.ArrayUnion(users_ids_ref)})

        batch.commit()
    except NotFound as ex:
        raise ValueError("At least one of the player was not found")
예제 #23
0
    def add_unknown(self, word: str):
        doc_ref = db.collection(
            self.collection_name).document("TOTAL")
        doc_ref.set({
            "unknown_cnt": firestore.Increment(1)
        }, merge=True)

        doc_ref = db.collection(
            self.collection_name).document(datetime.today().strftime("%y-%m-%d"))
        doc_ref.set({
            "unknown_add_cnt": firestore.Increment(1),
            "unknown_add_list": firestore.ArrayUnion([word]),
        }, merge=True)
예제 #24
0
    def add_word_update(self, word: str):
        doc_ref = db.collection(
            self.collection_name).document("TOTAL")
        doc_ref.set({
            "word_update": firestore.Increment(1)
        }, merge=True)

        doc_ref = db.collection(
            self.collection_name).document(datetime.date)
        doc_ref.set({
            "word_update": firestore.Increment(1),
            "word_update_list": firestore.ArrayUnion([word]),
        }, merge=True)
예제 #25
0
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': firestore.ArrayUnion([u'greater_virginia'])})

    # // Atomically remove a region from the 'regions' array field.
    city_ref.update({u'regions': firestore.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()))
예제 #26
0
def unlock_module(request: Request) -> str:
    """
    If the requesting player has enough credits
    """
    auth_header = request.headers.get("Authorization")
    if not auth_header:
        abort(401, "No authorization header")
    try:
        token = auth_header.split(' ')[1]
    except IndexError:
        abort(401, "Bad authorization header")

    users = db.collection('users')

    matching_users_query = users.where('token', '==', token)
    matching_users = list(matching_users_query.stream())

    if not matching_users:
        abort(401, "Invalid authorization")
    if len(matching_users) > 1:
        raise RuntimeError("Duplicate tokens in database")

    user = matching_users[0]

    if 'module' not in request.json:
        abort(400, "No module provided")

    modules = db.collection('modules')
    modules_query = modules.where('name', '==', request.json['module'])
    matching_modules = list(modules_query.stream())

    if not matching_modules:
        abort(400, "Module doesn't exist")

    module = matching_modules[0]

    available_credits = user.to_dict()['credits']
    price = module.to_dict()['price']

    if available_credits < price:
        abort(400, "Can't afford module")

    users.document(user.id).update({
        'credits':
        available_credits - price,
        'modules':
        firestore.ArrayUnion([module.to_dict()['name']])
    })

    return json.dumps({'success': True})
def handle_new_file(event, context):
    """
    Appends the name of the file added to the Cloud Storage bucket
    in the "files" array of the "new" document in Firestore.

    :params event: Event payload
    :type event: dict
    :params context: Event metadata
    :type context: google.cloud.functions.Context
    """
    file_path = "gs://%s/%s" % (event["bucket"], event["name"])
    db = firestore.Client(project=project_id)
    db.collection("jobs").document("new").set(
        {"files": firestore.ArrayUnion([file_path])}, merge=True)
    print("Added file: %s" % file_path)
예제 #28
0
def deal_tile_to_player(game_id, player_id, tile):
    client = firestore.Client()
    batch = client.batch()
    tile_dict_list = [tile.to_dict()]

    game_secrets = client.document(f'game_state_secrets/{game_id}')
    player_secrets = client.document(
        f'game_state_secrets/{game_id}/player_secrets/{player_id}')

    batch.update(game_secrets,
                 {'tiles': firestore.ArrayRemove(tile_dict_list)})
    batch.update(player_secrets,
                 {'tiles': firestore.ArrayUnion(tile_dict_list)})

    batch.commit()
예제 #29
0
def update_doc_array():
    db = firestore.Client()
    db.collection(u'cities').document(u'DC').set(
        City(u'Washington D.C.', None, u'USA', True, 680000,
             [u'east_coast']).to_dict())

    # [START firestore_data_set_array_operations]
    city_ref = db.collection(u'cities').document(u'DC')

    # Atomically add a new region to the 'regions' array field.
    city_ref.update({u'regions': firestore.ArrayUnion([u'greater_virginia'])})

    # // Atomically remove a region from the 'regions' array field.
    city_ref.update({u'regions': firestore.ArrayRemove([u'east_coast'])})
    # [END firestore_data_set_array_operations]
    city = city_ref.get()
    print(f'Updated the regions field of the DC. {city.to_dict()}')
예제 #30
0
def add(request):
    """Add all songs from a given playlist to the group's music."""
    party_id = get_val_from_request(request, 'id')
    combined_id = get_val_from_request(request, 'playlist')
    token = get_val_from_request(request, 'token')

    party_ref = db.collection('parties').document(party_id)

    service, playlist_id = combined_id.split('/')
    track_isrcs = SERVICES[service]['track_isrcs'](playlist_id, token)

    party_ref.update({'allTracks': firestore.ArrayUnion(track_isrcs)})
    party = db.collection('parties').document(party_id).get().to_dict()
    isrcs = party['allTracks']

    sp = spotipy.Spotify(auth=token)
    party_ref.update({'filtTracks': add_to_party_playlist(sp, isrcs, num=10)})