Beispiel #1
0
def init():
    rst_Ref = db.collection(u'root').document(u'restaurants')
    #build restaurants document
    items_Ref = db.collection(u'root').document(u'items')

    rst_Ref.set({u'id': u'restaurants', u'numRestaurants': 0})

    items_Ref.set({u'id': u'items', u'numItems': 0})

    data = getData()

    for idx, rst in enumerate(data):
        rst_Ref.update({u'numRestaurants': fs.Increment(1)})

        new_rst_ref = rst_Ref.collection('rstList').document(rst['name'])

        # print(rst['loc'])

        new_rst_ref.set({
            'id': idx + 2,  #set id in ascending from 0-n
            'name': rst['name'],
            'location': rst['loc'],
        })

        for item in rst['menu']:
            menu_ref = new_rst_ref.collection('menu').document(item['name'])
            menu_ref.set({u'name': item['name'], u'price': item['price']})
            items_Ref.update({u'numItems': fs.Increment(1)})

            new_item_Ref = items_Ref.collection('itemList').document(
                item['name'])
            new_item_Ref.set({u'name': item['name'], u'price': item['price']})
Beispiel #2
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
Beispiel #3
0
    def add_janken_result(self, result, session_id):
        if result == 0:
            set_result = "win_cnt"
        elif result == 1:
            set_result = "lose_cnt"
        elif result == 2:
            set_result = "draw_cnt"
        else:
            return False

        doc_ref = db.collection(self.collection_session).document(
            document_id=session_id)
        doc_ref.set({
            set_result: firestore.Increment(1)
        }, merge=True)

        doc_ref = db.collection(
            self.collection_name).document("TOTAL")
        doc_ref.set({
            set_result: firestore.Increment(1)
        }, merge=True)

        doc_ref = db.collection(
            self.collection_name).document(datetime.today().strftime("%y-%m-%d"))
        doc_ref.set({
            set_result: firestore.Increment(1)
        }, merge=True)
        return True
Beispiel #4
0
    def test_analytics_male_female_count_increment(self):
        fs = MockFirestore()
        fs._data = {
            'advertisements': {
                'analytics': {
                    'male': {
                        'count': 20
                    },
                    'female': {
                        'count': 10
                    },
                }
            }
        }
        fs.collection('advertisements').document('analytics').update({
            'male': {
                'count': firestore.Increment(1)
            },
            'female': {
                'count': firestore.Increment(1)
            },
        })

        doc = fs.collection('advertisements').document(
            'analytics').get().to_dict()
        self.assertEqual(doc, {'male': {'count': 21}, 'female': {'count': 11}})
    def test_document_update_transformerIncrementNested(self):
        fs = MockFirestore()
        fs._data = {
            'foo': {
                'first': {
                    'nested': {
                        'count': 1
                    },
                    'other': {
                        'likes': 0
                    },
                }
            }
        }
        fs.collection('foo').document('first').update({
            'nested': {
                'count': firestore.Increment(-1)
            },
            'other': {
                'likes': firestore.Increment(1),
                'smoked': 'salmon'
            },
        })

        doc = fs.collection('foo').document('first').get().to_dict()
        self.assertEqual(doc, {
            'nested': {
                'count': 0
            },
            'other': {
                'likes': 1,
                'smoked': 'salmon'
            }
        })
Beispiel #6
0
    def update_highlights(self, wordlist, filename):
        # Increments the firestore total upload count for that particular document
        stats_collection = self.db.collection(u'pdfs').document(
            filename).collection(u'words')
        stats_collection.document(u'total').update(
            {u'total': firestore.Increment(1)})

        # Iterates through the collection to upload the highlight count of each individual word on the firebase
        for wordstore in wordlist:
            name = str(wordstore.getPage()) + "_" + str(
                (wordstore.getX1() + wordstore.getX2()) / 2) + "_" + str(
                    wordstore.getY2())
            current = stats_collection.document(name)
            if current.get().exists:
                current.update(
                    {'count': firestore.Increment(wordstore.getCount())})
            else:
                current.set(wordstore.to_dict())

        # Initialises the list before pulling the updated firebase collection.
        text_list = list()
        docs = stats_collection.stream()
        count = 1
        for doc in docs:
            current_doc = doc.to_dict()
            if len(current_doc) > 1:
                text_list.append(Token.from_dict(current_doc))
                # text_list[-1].setCount(current_doc[u'count'])
            else:
                count = current_doc[u'total']
        return text_list, count
 def delete(self, identifier):
     document = self._find(identifier)
     doc_data = document.get().to_dict()
     if doc_data['verified']:
         self.metadata.update({
             'total_verified': firestore.Increment(-1),
             'total_documents': firestore.Increment(-1)
         })
     document.delete()
Beispiel #8
0
    def add_system_cnt(self, key):
        doc_ref = db.collection(self.collection_name).document("TOTAL")
        doc_ref.set({
            key: firestore.Increment(1),
        }, merge=True)

        doc_ref = db.collection(
            self.collection_name).document(datetime.today().strftime("%y-%m-%d"))
        doc_ref.set({
            key: firestore.Increment(1),
        }, merge=True)
Beispiel #9
0
def update_relationship():
    """
        update_relationship() : increment/decrement relationship score between users.
        - Input JSON should include: 
          - string for direction "discrete" (src->trgt) or "mutual" for both 
          - string for relationship type
          - array of UUID strings. First UUID in the array is always the src, second is always trgt (for POC)
          - int for how much to change the score (delta)
        Note:   This is currently implemented somewhat oddly during PoC while we decide
                if we want to be able to update more than two relationships at once.
        TODO (joeholley): Decrementing below init_score should be floored at
                          init_score (or deleted)

    """
    try:
        ur_logger = log.withFields({
            'direction': request.json['direction'],
            'relationship': request.json['relationship'],
            'uuid_src': request.json['uuids'][0],
            'uuid_trgt': request.json['uuids'][1],
            'delta': request.json['delta'],
        })
        ur_logger.debug("updateRelationship called")

        # TODO(joeholley): configurable initial score
        if request.json['direction'] == 'mutual':
            ur_logger.debug("bi-directional relationship update")
            batch = db.batch()
            # This is using a loop as it /could/ be easily made to modify more
            # than two players simultaneously.  Not settled on having this
            # feature yet but could see it as useful in many group-based games.
            for uuid_src in request.json['uuids']:
                for uuid_trgt in request.json['uuids']:
                    if uuid_src != uuid_trgt:
                        # Nested JSON keys are handled using dot operators in firestore
                        key = "%s.%s" % (request.json['relationship'],
                                         uuid_trgt)
                        batch.update(fs.document(uuid_src), {
                            key:
                            firestore.Increment(int(request.json['delta']))
                        })
            batch.commit()
        else:
            ur_logger.debug("uni-directional relationship update")
            key = "%s.%s" % (request.json['relationship'],
                             request.json['uuids'][1])
            fs.document(request.json['uuids'][0]).update(
                {key: firestore.Increment(int(request.json['delta']))})

        return jsonify({"success": True}), 200

    except Exception as e:
        return f"An Error Occured: {e}"
Beispiel #10
0
    def dec_unknown(self):
        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_dec_cnt": firestore.Increment(1),
        }, merge=True)
Beispiel #11
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)
Beispiel #12
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)
Beispiel #13
0
    def dispense_done(self, amount):
        # Cleanup and turnoff the LED
        self.set_motor(MOTOR_OFF)
        if amount > 0:
            JobOnce(lambda: self.set_led('holder', LOW), seconds=3)
            JobOnce(lambda: self.set_led('reader', HIGH), seconds=3)

        # Notify server of departure
        # Raise a flag that we are empty
        self.game['is_empty'] = amount != self.dispense_no

        # Check if we are empty, if so, we reduce credit
        if self.game['is_empty']:
            logger.info(f'We are empty, we only dispensed {amount} coins')
            # Only reduce
            self.area_ref.set(
                {
                    'paid': firestore.Increment(amount),
                    'is_empty': self.game['is_empty'],
                    'players': {
                        self.current_uid: {
                            'present': False,
                            'credit': firestore.Increment(-amount),
                        }
                    }
                },
                merge=True)
        else:
            logger.info(f'Dispense done, gave {amount} coins')
            self.area_ref.update({
                'paid':
                firestore.Increment(amount),
                'is_empty':
                self.game['is_empty'],
                f'players.{self.current_uid}':
                firestore.DELETE_FIELD,
            })
            del self.players[self.current_uid]

        # Finally, remove player from area
        self.player_ref.document(self.current_uid).set(
            {
                'area': None,
                AREA: firestore.Increment(amount),
            }, merge=True)

        # Our flag that we are not dispensing
        self.current_uid = None
        self.dispense_no = 0
Beispiel #14
0
 def add_bad(self, word: str):
     """ bad加算
     """
     docs = db.collection(self.collection_name).where("word", "==",
                                                      word).limit(1).get()
     if docs:
         docs[0]._reference.set(
             {
                 "bad": firestore.Increment(1),
                 "updated_at": datetime.now(),
                 "cnt": firestore.Increment(1),
             },
             merge=True)
         return True
     return False
    def _add(self,
             data,
             *,
             validating_data=None,
             validation_fields=None,
             client,
             metadata,
             check_unique=False,
             check_exists=False,
             validation_client=None):
        found_item = None
        if validating_data is not None:
            validate_against = deep_merge(data, validating_data)
        else:
            validate_against = data
        if validation_fields is not None:
            for field in validation_fields:
                found_item = self._find({field: validate_against[field]},
                                        validation_client)

                if check_unique and found_item is not None:
                    return None
                if check_exists and found_item is None:
                    return None

        _, doc_ref = client.add(data)
        metadata.update({'total_documents': firestore.Increment(1)})

        return doc_ref.id
    def test_document_update_transformerIncrementBasic(self):
        fs = MockFirestore()
        fs._data = {'foo': {'first': {'count': 1}}}
        fs.collection('foo').document('first').update(
            {'count': firestore.Increment(2)})

        doc = fs.collection('foo').document('first').get().to_dict()
        self.assertEqual(doc, {'count': 3})
Beispiel #17
0
def log_exit(doc, coll):
    doc.update({
        u'Count': firestore.Increment(-1)
    })
    coll.add({
        u'Count': -1,
        u'time': datetime.now()
    })
Beispiel #18
0
def log_entrance(doc, coll):
    doc.update({
        u'Count': firestore.Increment(1)
    })
    coll.add({
        u'Count': 1,
        u'time': datetime.now()
    })
    def test_document_update_transformerIncrementNonExistent(self):
        fs = MockFirestore()
        fs._data = {'foo': {'first': {'spicy': 'tuna'}}}
        fs.collection('foo').document('first').update(
            {'count': firestore.Increment(1)})

        doc = fs.collection('foo').document('first').get().to_dict()
        self.assertEqual(doc, {'count': 1, 'spicy': 'tuna'})
Beispiel #20
0
 def inc_table_header(self, **kwargs):
     header_ref = self.get_table_header()
     header_dict = header_ref.to_dict()
     content = kwargs.copy()
     for key, value in content.items():
         content[key] = firestore.Increment(value)
         header_dict[key] = header_dict.get(key, 0) + value
     self.update_document(header_ref, content)
     return header_dict
    def _verify(self, id_str, *, client, metadata):
        document = client.document(id_str)

        if document.get().to_dict()['verified'] is True:
            return False

        document.update({'verified': True})
        metadata.update({'total_verified': firestore.Increment(1)})

        return True
def store_data(product):
    global DB_CLIENT

    if not DB_CLIENT:
        DB_CLIENT = firestore.Client()

    doc_ref = DB_CLIENT.collection(APP_COLLECTION).document(product)
    doc_ref.set({
        u"recomended_times": firestore.Increment(1),
    }, merge=True)
Beispiel #23
0
def decrementItemQty(item_id: str, user_id: str):
    db = firestore.Client()
    cart_ref = db.collection(u'Users').document(user_id).collection(
        u'Cart').document(item_id)

    cart_ref.update({
        u'quantity': firestore.Increment(-1),
        u'timestamp': firestore.SERVER_TIMESTAMP
    })
    return document_to_dict(cart_ref.get())
Beispiel #24
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
Beispiel #25
0
def visit_count(event, context):
    db = firestore.Client(project='airports-project')
    if 'attributes' in event:
        if 'page' in event['attributes']:
            page_name = event['attributes']['page']
        counter_ref = db.collection(u'visits').document(f'{page_name}')
        if not counter_ref.get().exists:
            counter_ref.set({u'counter': 1})
        else:
            counter_ref.update({u'counter': firestore.Increment(1)})
            print(f'Incremented {page_name} counter visit')
    else:
        page_name = 'Unknown'
        print('Nothing done')
def persist(client, pubname, collname, doc_id, document_dict):

    # Check these values to determine if this is a Publication count incrementor message.
    if collname is None or doc_id is None:
        increment_publication(client, pubname, document_dict['count'])
    else:
        # Map the increment class to the count value.
        document_dict['count'] = firestore.Increment(document_dict['count'])
        # pubdoc is the firestore document for the given publication.
        pubdoc = client.collection(u'publications').document(pubname)
        # wrddoc is the document that stores the word and count
        wrddoc = pubdoc.collection(collname).document(doc_id)
        # Merge will allow the count to be incremented.
        wrddoc.set(document_dict, merge=True)
        log.debug('incremented word counter')
Beispiel #27
0
async def update_or_create(input: Counting, response: Response):
    """ This Method Either creates the New Document for name or update the value if name already exists in docuemnts """
    dict_data = {'name': input.name, 'value': input.value}
    doc_ref = doc_collection.document(input.name)
    record = doc_ref.get()
    print(record.get(u'value'))
    if record.exists:
        doc_ref.update({u'value': firestore.Increment(input.value)})
    else:
        doc_ref.set(dict_data)
        response.status_code = status.HTTP_201_CREATED

    #to send the latest response
    record = doc_ref.get()
    return record.to_dict()
Beispiel #28
0
def _acid_update(transaction, doc_ref, event: Event):
    snapshot = doc_ref.get(transaction=transaction)

    if not snapshot.exists:
        transaction.set(
            doc_ref, {
                u'{}'.format('count'): 1,
                u'{}'.format('temperature'): event.temperature,
                u'{}'.format('temperature_at'): event.timestamp,
                u'{}'.format('updated_at'): firestore.SERVER_TIMESTAMP,
            })
    else:
        transaction.update(
            doc_ref, {
                u'{}'.format('count'): firestore.Increment(1),
                u'{}'.format('temperature'): event.temperature,
                u'{}'.format('temperature_at'): event.timestamp,
                u'{}'.format('updated_at'): firestore.SERVER_TIMESTAMP,
            })
Beispiel #29
0
    def job_game_tick(self):
        tick = datetime.now(timezone.utc)

        # logger.info('Main game tick')
        updates = {}
        for uid, player in self.players.items():
            # Skip players that are not present
            if player['present'] != True:
                continue

            # We limit the credits to [0, limit]
            new_credit = max(
                0,
                min(player['credit'] + self.game['tick_amount'],
                    self.game['limit']))

            # If there is no change, or if we have already more (and positive tick rate), continue
            if player['credit'] == new_credit or (
                    self.game['tick_amount'] > 0
                    and player['credit'] > new_credit):
                continue

            # Check for update
            if tick > player['tick'] + self.game['tick_seconds']:
                logger.info(f'Give money to {uid}')

                # Make sure we keep their checkin alignment
                while tick > player['tick'] + self.game['tick_seconds']:
                    player['tick'] += self.game['tick_seconds']

                # Update player
                updates[uid] = {
                    'credit':
                    firestore.Increment(new_credit - player['credit']),
                    'tick': player['tick'],
                }

        # Update everything in one go
        if len(updates) > 0:
            self.area_ref.set({
                'players': updates,
            }, merge=True)
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
    )