Beispiel #1
0
 def deactivate_player(self, player: Player) -> None:
     team = self.team_from_id(player.team_id)
     team_player_count = self.count_players(from_team=team)
     batch = self._client.batch()
     player_ref = self._client.document("games/{}/players/{}".format(
         self._game_id, player.id))
     tribe_ref = self._client.document("games/{}/tribes/{}".format(
         self._game_id, player.tribe_id))
     team_ref = self._client.document("games/{}/teams/{}".format(
         self._game_id, player.team_id))
     game_ref = self._client.document("games/{}".format(self._game_id))
     batch.update(player_ref, {'active': False})
     batch.update(tribe_ref, {'count_players': Increment(-1)})
     batch.update(team_ref, {'count_players': Increment(-1)})
     batch.update(game_ref, {'count_players': Increment(-1)})
     users = self._client.collection("users").where(
         "phone_number", "==", player.phone_number).get()
     if len(users) > 0:
         user_ref = users[0].reference
         batch.update(user_ref, {'game_id': None})
     batch.commit()
     # NOTE(brandon): we use LTE to here since the count
     # was retrieved prior to the decrement commit.
     if team_player_count <= 1:
         self.deactivate_team(team=team)
Beispiel #2
0
    def batch_update_tribe(self, from_tribe: Tribe, to_tribe: Tribe) -> None:
        # TODO(brandon): consider strengthening this because if the server crashes
        # mid-merge the counts will be difficult to fix.
        teams = self._client.collection('games/{}/teams'.format(
            self._game_id)).where('tribe_id', '==', from_tribe.id).stream()
        players = self._client.collection('games/{}/players'.format(
            self._game_id)).where('tribe_id', '==', from_tribe.id).stream()
        player_count = self.count_players(from_tribe=from_tribe)
        team_count = self.count_teams(from_tribe=from_tribe)
        with ThreadPoolExecutor(
                max_workers=self._thread_pool_size) as executor:
            executor.submit(self._tribe_update_fn, teams,
                            {"tribe_id": to_tribe.id})
            executor.submit(self._tribe_update_fn, players,
                            {"tribe_id": to_tribe.id})

        batch = self._client.batch()
        batch.update(
            self._client.document('games/{}/tribes/{}'.format(
                self._game_id, to_tribe.id)), {
                    'count_players': Increment(player_count),
                    'count_teams': Increment(team_count),
                    'active': True
                })
        batch.update(
            self._client.document('games/{}/tribes/{}'.format(
                self._game_id, from_tribe.id)), {
                    'count_players': 0,
                    'count_teams': 0,
                    'active': False
                })
        batch.commit()
Beispiel #3
0
 def deactivate_team(self, team: Team) -> None:
     batch = self._client.batch()
     team_ref = self._client.document("games/{}/teams/{}".format(
         self._game_id, team.id))
     tribe_ref = self._client.document("games/{}/tribes/{}".format(
         self._game_id, team.tribe_id))
     game_ref = self._client.document("games/{}".format(self._game_id))
     batch.update(team_ref, {'active': False, 'count_players': 0})
     batch.update(tribe_ref, {'count_teams': Increment(-1)})
     batch.update(game_ref, {'count_teams': Increment(-1)})
     batch.commit()
Beispiel #4
0
def get_auth(db, user_private_id):
    try:
        user = auth.get_user(user_private_id)
    except:
        return user_not_found(user_private_id)

    user_public_id = get_user_public_id(user_private_id)

    now = datetime.datetime.now()

    if user_public_id:
        user_private_ref = db.collection(u'users').document(
            user_public_id).collection(u'private').document(user_private_id)
        user_private_ref.update({
            "num_opened": Increment(1),
            "last_opened": now
        })
        return JsonResponse({"success": {"user_public_id": user_public_id}})
    else:
        # new user
        try:
            user_ref = db.collection(u'users').document()
            public_id = user_ref.id
            user_private_ref = user_ref.collection(u'private').document(
                user_private_id)
            batch = db.batch()

            batch.set(user_ref, {"name": user.display_name, "friends": []})
            batch.set(
                user_private_ref, {
                    "avg_time": 0.0,
                    "num_opened": 1,
                    "date_joined": now,
                    "last_opened": now,
                    "default_card": -1,
                    "stripe_id": ""
                })
            user_map_ref = db.collection(u'general').document(
                u'user-verification').collection(user_private_id).document(
                    u'map')
            batch.set(user_map_ref, {"public_id": public_id})

            general_ref = db.collection('general').document('maint')
            batch.update(general_ref, {"total_users": Increment(1)})

            batch.commit()
            return JsonResponse({"success": {"user_public_id": public_id}})
        except:
            return general_error()

    pass
 def dao_remove_bike(self, bike_id):
     db = firestore.Client()
     tran = db.transaction()
     db.collection('bikes').document(bike_id).delete()
     db.collection('bikes').document("metainfo").set(
         {"total": Increment(-1)}, merge=True)
     tran.commit()
Beispiel #6
0
def update_user(data, user_id):
    try:
        user_ref = db.collection('users').document(user_id)
    except google.cloud.exceptions.NotFound:
        return Response('failed', 'User does not exist!', 401)

    if 'transaction' in data:
        transaction = data['transaction']
        user_ref.update({
            'balance': Increment(-transaction['price']),
            'transaction_history': ArrayUnion([transaction])
        })
    if 'load' in data:
        load = data['load']
        user_ref.update({'gross_loaded': Increment(load)})

    return Response('User data successfully updated', 200)
    def dao_add_bike(self, bike):
        db = firestore.Client()
        tran = db.transaction()
        doc = db.collection('bikes').document()
        doc.set(bike)
        db.collection('bikes').document("metainfo").set(
            {"total": Increment(1)}, merge=True)
        tran.commit()

        return doc.id
Beispiel #8
0
    def deactivate_player(self, player: Player) -> None:
        batch = self._client.batch()
        player_ref = self._client.document("games/{}/players/{}".format(
            self._game_id, player.id))
        tribe_ref = self._client.document("games/{}/tribes/{}".format(
            self._game_id, player.tribe_id))
        team_ref = self._client.document("games/{}/teams/{}".format(
            self._game_id, player.team_id))
        game_ref = self._client.document("games/{}".format(self._game_id))

        batch.update(player_ref, {'active': False})

        batch.update(tribe_ref, {'count_players': Increment(-1)})

        batch.update(team_ref, {'count_players': Increment(-1)})

        batch.update(game_ref, {'count_players': Increment(-1)})

        batch.commit()
Beispiel #9
0
 def deactivate_player(self, player: DocumentReference) -> None:
     batch = self._client.batch()
     player_ref = self._client.document("games/{}/players/{}".format(
         self._game_id, player.id))
     tribe_ref = self._client.document("games/{}/tribes/{}".format(
         self._game_id, player.get('tribe_id')))
     team_ref = self._client.document("games/{}/teams/{}".format(
         self._game_id, player.get('team_id')))
     game_ref = self._client.document("games/{}".format(self._game_id))
     batch.update(player_ref, {'active': False})
     batch.update(tribe_ref, {'count_players': Increment(-1)})
     batch.update(team_ref, {'count_players': Increment(-1)})
     batch.update(game_ref, {'count_players': Increment(-1)})
     users = self._client.collection("users").where(
         "phone_number", "==", player.get("phone_number")).get()
     if len(users) > 0:
         user_ref = users[0].reference
         batch.update(user_ref, {'game_id': None})
     batch.commit()
Beispiel #10
0
    def player(self, name: Text) -> Player:
        batch = self._client.batch()
        player_ref = self._client.collection("games/{}/players".format(
            self._game_id)).document()
        batch.set(player_ref, {'name': name, 'active': True})

        game_ref = self._client.document("games/{}".format(self._game_id))
        batch.update(game_ref, {'count_players': Increment(1)})

        batch.commit()
        return FirestoreData(player_ref.get())
Beispiel #11
0
    async def spend_char(self, count):
        """成功した場合はTrue、文字数が足りなかった場合はNoneを返す"""
        guild = await self.data()
        if guild.count - count > 0:
            await self.bot.loop.run_in_executor(
                self.executor,
                partial(self.document.set, {'count': Increment(-count)},
                        merge=True))
            return True

        await self.bot.loop.run_in_executor(
            self.executor, partial(self.document.set, {'count': 0},
                                   merge=True))
 def dao_generate_bikes(self, number):
     db = firestore.Client()
     tran = db.transaction()
     for i in range(0, number):
         db.collection('bikes').document().set(
             {
                 "title": random_string(10),
                 "price": random.randint(100, 2000),
                 "stars": random.choice([1, 2, 3, 4, 5]),
                 "createdOn": datetime.now(tz=None)
             },
             merge=True)
         db.collection('bikes').document("metainfo").set(
             {"total": Increment(1)}, merge=True)
     tran.commit()
Beispiel #13
0
def firestore_add(user, db, confidence):
    doc_ref = db.collection(u'userMessages').document(str(user))
    docCheck = doc_ref.get()
    if docCheck.exists:
        doc_ref.update({
            u'userID': user,
            u'positive': Increment(confidence[0]),
            u'neutral': Increment(confidence[1]),
            u'negative': Increment(confidence[2]),
            u'count': Increment(1)
        })
    else:
        doc_ref.set({
            u'userID': user,
            u'positive': Increment(confidence[0]),
            u'neutral': Increment(confidence[1]),
            u'negative': Increment(confidence[2]),
            u'count': Increment(1)
        })
Beispiel #14
0
def update_active_league_count(event: Dict, context):
    old_value: Dict = event.get("oldValue", None)
    new_value: Dict = event.get("value", None)

    if not old_value or not new_value:
        return

    old_value: Dict = old_value["fields"]["draft_state"]["stringValue"]
    new_value: Dict = new_value["fields"]["draft_state"]["stringValue"]

    was_inactive = old_value != "completed"
    is_active = new_value == "completed"

    just_activated = was_inactive and is_active
    # print(f"was_inactive: {was_inactive} is_active: {is_active} just_activated: {just_activated}")

    if just_activated:
        count_ref = client.document("admin/stats")
        count_ref.update({"active_league_count": Increment(1)})
Beispiel #15
0
def update_store(store_num, store_increment_val):
    print (f"Updating store {store_num} by {store_increment_val}")
    batch = db.batch()
    detail_ref = db.collection(u'details').document()
    store_ref = db.collection(u'stores').document(store_num)

    detail_data = {
        u'store_num': store_num,
        u'timestamp': firestore.SERVER_TIMESTAMP,
        u'count': store_ref.get().to_dict().get('count') + store_increment_val
    }

    store_data = {
        u'count': Increment(store_increment_val),
        u'timestamp': firestore.SERVER_TIMESTAMP
    }

    batch.set(detail_ref, detail_data)
    batch.set(store_ref, store_data, merge=True)
    batch.commit()
Beispiel #16
0
    def player(self,
               name: str,
               tiktok: str = None,
               phone_number: str = None) -> Player:
        batch = self._client.batch()
        player_ref = self._client.collection("games/{}/players".format(
            self._game_id)).document()
        batch.set(
            player_ref, {
                'name': name,
                'active': True,
                'tiktok': tiktok,
                'phone_number': phone_number
            })

        game_ref = self._client.document("games/{}".format(self._game_id))
        batch.update(game_ref, {'count_players': Increment(1)})

        batch.commit()
        return FirestoreData(player_ref.get())
Beispiel #17
0
 async def spend_char(self, count):
     """使用可能文字数を減らす"""
     data = await self.data()
     data2 = {
         key: value
         for key, value in data.data.items()
         if key != 'subscribe' and value != 0
     }
     used_data = {}
     if not data2:
         return
     while count > 0:
         min_key = min(data2, key=data2.get)
         if count > data2[min_key]:
             count -= data2[min_key]
             used_data[min_key] = 0
             del data2[min_key]
             continue
         used_data[min_key] = Increment(-count)
         count = 0
     await self.document.set(used_data, merge=True)
Beispiel #18
0
    def change_points(self, chat_id, user: User, value):
        chat_doc = self.db.collection("chats").document(str(chat_id))
        try:
            chat_doc.create({})
        except AlreadyExists:
            pass

        try:
            self.db.collection("users").document(str(user.id)).update(
                user.to_dict())
        except NotFound:
            self.db.collection("users").document(str(user.id)).set(
                user.to_dict())

        user_doc = self.db.collection("users").document(str(user.id))

        try:
            chat_doc.collection("scores").document(user.first_name).update(
                dict(score=Increment(value), user=user_doc))
        except NotFound:
            chat_doc.collection("scores").document(user.first_name).set(
                dict(score=value, user=user_doc))
Beispiel #19
0
def update_user_count(event: Dict, context):
    old_value: Dict = event.get("oldValue", None)
    new_value: Dict = event.get("value", None)

    if not old_value or not new_value:
        return

    old_event_data: Dict = old_value["fields"]["event_data"]["mapValue"]["fields"]
    new_event_data: Dict = new_value["fields"]["event_data"]["mapValue"]["fields"]

    old_email_verified: Dict = old_event_data.get("emailVerified", {})
    new_email_verified: Dict = new_event_data.get("emailVerified", None)

    if not new_email_verified:
        return

    was_verified_before = old_email_verified.get("booleanValue", False) if old_email_verified else False
    is_verified_now = new_email_verified.get("booleanValue", False) if new_email_verified else False

    just_verified = not was_verified_before and is_verified_now

    if just_verified:
        count_ref = client.document("admin/stats")
        count_ref.update({"verified_user_count": Increment(1)})
Beispiel #20
0
    def _add_listen(self, artist_id, track_id, track_details):
        """ Adds a listen event to the firebase 
        
        Parameters
        ----------
        artist_id : str - the id of the song's artist

        track_id : str - the id of the song

        track_details : dict - the information to add to firebase about the listen

        Returns
        -------
        None
        
        """
        # Update Artist
        self.artist_collection.document(artist_id).update({
            "listen_count": Increment(1),
            "listen_time": Increment(track_details["ms_played"]),
            "last_listen_time": track_details["time_info"],
            "last_listen": {"track_id":track_id, "song_name":track_details["song_name"]}
        })

        # Update Song
        listen_info = self._get_time_info(track_details["timestamp"])
        listen_info["duration"] = track_details["ms_played"]
        self.song_collection.document(track_id).update({
            "listen_count": Increment(1),
            "listen_time": Increment(track_details["ms_played"]),
            "last_listen": track_details["time_info"],
            "listens": firestore.ArrayUnion([listen_info])
        })

        # Add to History
        self.history_collections[track_details['time_info']['year']].document(f"{track_details['time_info']['month']}").update({
            "listen_count": Increment(1),
            "listen_time": Increment(track_details["ms_played"]),
            "uq_artists": firestore.ArrayUnion([artist_id]),
            "uq_songs": firestore.ArrayUnion([track_id])
        })
Beispiel #21
0
def update_db(image):
    doc = db.collection('AttendanceInstance').document('CurrentAttendance').get()
    doc = doc.to_dict()
    lecture = doc['lectureType']
    subject = doc['subject']
    lecturesNum = doc['lecturesNum']

    with open('students.txt', 'r') as fp:
        names = fp.readlines()

    names = [n.strip('\n').lower() for n in names]

    with open('students.pkl', 'rb') as fp:
        std_metadata = pickle.load(fp)

    # returns no. of face detected and list of students recognized
    detected, students = get_students.recognize_faces(image)
    print(f'Recognized: {len(students)}/{detected}')
    for face in students:
        face = face.split('_')[1] + ' ' + face.split('_')[0]
        print(f'{face} [{std_metadata[face][0]}]')

    if detected is None or detected is 0:
        print('No face detected')
        return

    for id, name in enumerate(students):
        name = name.split('_')[1] + ' ' + name.split('_')[0]
        if name not in names:
            continue

        id = std_metadata[name][0]

        doc_ref = db.collection('students').document(f'{id}')
        doc_ref.update({
            f'Attendance.{lecture}.{subject}': Increment(lecturesNum),
            'Attendance.Last_Updated': firestore.SERVER_TIMESTAMP,
        })


        # doc_ref.update({
        #     'Attendance': {
        #         'Theory': {
        #             'AM-3': 0,
        #             'DIS': 0,
        #             'DLDA': 0,
        #             'DS': 0,
        #             'ECCF': 0,
        #             'OOPM': 0,
        #         },
        #         'Practical': {
        #             'DLDA': 0,
        #             'DS': 0,
        #             'ECCF': 0,
        #             'OOPM': 0,
        #         },
        #         'Lectures_Attended': 0,
        #         'Last_Updated': firestore.SERVER_TIMESTAMP,
        #     },
        #     'ID': f'{id}',
        #     'Name': f'{name}'
        # })

    print('Database updated successfully!')
Beispiel #22
0
def update_league_count(event: Dict, context):
    count_ref = client.collection("admin").document("stats")

    count_ref.update({"league_count": Increment(1)})
Beispiel #23
0
    game_info = current_game.to_dict()
    #remove from current and add to previous
    if int(time.time() * 1000) > end_date:
        players = game_info["players"]
        db.collection(u'current_games').document(game_id).delete()
        db.collection(u'previous_games').document(game_id).set(game_info)
        
        first_place_total = -100000
        first_place_user = ""
        for player in players:
            # add game_id to each users previous game profile & remove it from current games
            db.collection(u'users').document(player).update({
                "previous_games": ArrayUnion([game_id]),
                "current_games": ArrayRemove([game_id])
            })
            if game_info[player]["total"] > first_place_total:
                first_place_total = game_info[player]["total"]
                first_place_user = player
        
        db.collection(u'users').document(first_place_user).update({
            "games_won": ArrayUnion([game_id]),
            "wins": Increment(1)
        })        
        print(game_id, 'moved to previous games')
    else: 
        print("game session hasn't ended")

db.collection(u"script_counter").document("count").update({
    "count": Increment(1)
})
Beispiel #24
0
    async def spend_char(self, guild_id, count):
        guild = await self.get_guild(guild_id)
        docguild = self.get_document(guild_id)
        if guild['count'] - count < 0:
            await self.bot.loop.run_in_executor(self.executor, partial(docguild.set, {'count': 0}, merge=True))
            return False

        await self.bot.loop.run_in_executor(self.executor, partial(docguild.set, {'count': Increment(-count)}, merge=True))
        return True
def increment_sighting(class_id):
    authority_data_ref.document(class_id).update({u'y': Increment(1)})