def __init__(self, client: Optional[Client] = None):
     self._watchers = {}
     self._collections = defaultdict(dict)
     if client is None:
         self._client = Client()
     else:
         self._client = client
     self._watchers_lock = Lock()
Esempio n. 2
0
    def __init__(self, listening_collection_1):#, listening_collection_2):
        
        # initialize ROS node
        rospy.init_node('dynamicolistener', anonymous=True)
        # initialize publishers/subscribers
        # rospy.Subscriber([topic_name],[topic_type],[callback_function_name])
        # rospy.Publisher([topic_name],[topic_type],[max_queue_size])
        self.pubMsg = rospy.Publisher('dynamicomsg', String, queue_size=10)
        
        # get credentials information from the file
        path = os.path.realpath(__file__).replace('dynamicoListener.py','')
        with open(path + '/DYNAMICO_CREDENTIALS.txt') as f:
        # with open(path + '/DYNAMICO_CREDENTIALS_PARIS.txt') as f:
            data = json.load(f)

        print("DATA", data)

        self.email = data['EMAIL']
        self.password = data['PASSWORD']
        self.API_KEY = data['API_KEY']
        self.user_id = data['USER_ID']   
        self.project_id = data['PROJECT_ID']

        # sign in on the Dynamico Firestore as done in https://gist.github.com/Bob-Thomas/4d9370c6b5432fb5150d3618e0ae71ba
        self.FIREBASE_REST_API = "https://identitytoolkit.googleapis.com/v1/accounts"
        response = self.sign_in_with_email_and_password(self.FIREBASE_REST_API, self.API_KEY, self.email, self.password)
        
        self.listening_collection = listening_collection_1

        # use google.oauth2.credentials and the response object to create the correct user credentials
        creds = Credentials(response['idToken'], response['refreshToken'])
        self.db = Client(self.project_id, creds)

        # create an event to be notified of changes in the Dynamico Firestore
        self.dynamicoCallback = threading.Event()
    
        # watch the changes in the listening_collection only with regards to our user
        doc_ref = self.db.collection(listening_collection_1).where(u'userId', u'==', self.user_id)
        self.doc_watch_1 = doc_ref.on_snapshot(self.on_snapshot_1)

        # watch the changes in the listening_collection only with regards to our user
        # doc_ref_2 = self.db.collection(listening_collection_2).where(u'userId', u'==', self.user_id)
        # self.doc_watch_2 = doc_ref.on_snapshot(self.on_snapshot_1)

        # [DEBUG ONLY]
        print("Waiting for messages")
Esempio n. 3
0
def main() -> None:
    try:
        args = Args()

        # Connect to the database
        fireo.connection(client=Client(
            project=args.instance,
            credentials=AnonymousCredentials(),
        ))

        run_remote_search(args.query, args.sort_by, args.first)
        run_local_search(args.query, args.local_index_glob, args.sort_by,
                         args.first)
    except Exception as e:
        log.error("=============================================")
        log.error("\n\n" + traceback.format_exc())
        log.error("=============================================")
        log.error("\n\n" + str(e) + "\n")
        log.error("=============================================")
        sys.exit(1)
Esempio n. 4
0
from telegram.ext import PicklePersistence, Updater, CallbackQueryHandler

# Local imports
from cinnabot.base import Start, About, Help
from cinnabot.claims import Claims
from cinnabot.feedback import Feedback
# from cinnabot.laundry import Laundry
from cinnabot.resources import Resources
from cinnabot.spaces import Spaces
from cinnabot.travel import PublicBus, NUSBus, NUSMap
from google.cloud.firestore import Client
from google.auth.credentials import AnonymousCredentials

# Initialize a backend with a firestore client
firestore = Client(
    project='usc-website-206715',
    credentials=AnonymousCredentials(),
)

# Initialize to check that all requirements defined in utils.py have been met.
FEATURES = [
    Start(),
    About(),
    Help(),
    Claims(),
    Feedback(),
    # Laundry(),
    Resources(),
    Spaces(database=firestore),
    # PublicBus(),
    NUSBus(),
    NUSMap(),
Esempio n. 5
0
from concurrent.futures import ThreadPoolExecutor, as_completed
from copy import deepcopy, copy
from operator import itemgetter
from typing import TypeVar, Optional, Union, Type, List, Dict, Iterable, Callable

from google.cloud.firestore import Client, CollectionReference, Query, DocumentSnapshot

# Need environment variable GOOGLE_APPLICATION_CREDENTIALS set to path of the the service account key (json file)
_DB = Client()
# All models imported from FirestoreDocument are of type FirestoreDocChild
# noinspection PyTypeChecker
_FirestoreDocChild = TypeVar("_FirestoreDocChild", bound="FirestoreDocument")
# Used to map collection to model
_REFERENCE: Dict[str, callable] = dict()


class FirestoreCIError(Exception):

    def __init__(self, message):
        super().__init__(message)


class FirestoreQuery:
    LESS_THAN = "<"
    LESS_THAN_OR_EQUAL = "<="
    EQUAL = "=="
    GREATER_THAN_OR_EQUAL = ">="
    GREATER_THAN = ">"
    ARRAY_CONTAINS = "array_contains"
    IN = "in"
    ARRAY_CONTAINS_ANY = "array_contains_any"
Esempio n. 6
0
        elif len(date_fields) == 3:
            # dd/mm/yy
            day = datetime.strptime(day_str,
                                    "%d/%m/%y")  # %y for last 2 digits of year
        else:
            raise ValueError

        return day


if __name__ == "__main__":
    from datetime import datetime, timedelta
    from google.cloud.firestore import Client

    # Initialize a backend with a firestore client
    firestore = Client(project='usc-website-206715')
    spaces = Spaces(database=firestore)

    # Test event querying (Actually this block can go in Spaces.spaces)
    now = datetime.now()
    today = datetime(now.year, now.month, now.day)  # reset time to midnight
    tomorrow = today + timedelta(days=1)

    events = spaces._events_between(today, tomorrow)

    for event in events:
        # Each "event" is a dictionary following the schema of documents in firestore
        print(80 * '=')
        print(event['name'])
        print(80 * '-')
        print('- Venue:', event['venueName'])
Esempio n. 7
0
def main():
    client = Client()

    for collection in client.collections():
        zap_collection(collection)
Esempio n. 8
0
 def __init__(self, project_name: str):
     self._project_name: str = project_name
     self._client = Client(project=self._project_name)
Esempio n. 9
0
import os

from google.cloud.firestore import Client

client = Client(project=os.getenv('PROJECT_ID'))