Ejemplo n.º 1
0
def schema(event, context):
    create_todos = query.create_class({
        'name': 'todos'
    })

    create_all_todos = query.create_index({
        'name': 'all_todos',
        'source': TODOS
    })

    client.query(query.if_expr(
        query.exists(TODOS),
        query.get(TODOS),
        create_todos
    ))

    client.query(query.if_expr(
        query.exists(ALL_TODOS),
        query.get(ALL_TODOS),
        create_all_todos
    ))

    # create a response
    response = {
        "statusCode": 200
    }

    return response
Ejemplo n.º 2
0
    def test_create_role(self):
        self.admin_client.query(
            query.create_role({
                "name": "a_role",
                "privileges": {
                    "resource": query.collections(),
                    "actions": {
                        "read": True
                    }
                }
            }))

        self.assertTrue(
            self.admin_client.query(query.exists(query.role("a_role"))))
Ejemplo n.º 3
0
 def __init__(self, collection_name: str, model):
     """
     Each CRUD requires that:
     - Fauna client is connected to db
     - collection_name is created / exists
     - Collection is created / exists
     """
     self.collection_name = collection_name
     self.model = model
     self.client = FaunaClient(secret=settings.FAUNADB_SECRET)
     if not self.client.query(
             query.exists(query.database(
                 db_name=settings.FAUNADB_DBNAME, ))):
         self.database = self.client.query(
             query.create_database(db_params={
                 'name': settings.FAUNADB_DBNAME,
             }), )
     if not self.client.query(
             query.exists(
                 query.collection(collection_name=collection_name, ))):
         self.collection = self.client.query(
             query.create_collection(collection_params={
                 'name': collection_name,
             }), )
Ejemplo n.º 4
0
def donate(update, context):
    try:
        for message in config['message']['donate']:
            context.bot.send_message(chat_id=update.effective_chat.id,
                                     text=message)
        client.query(
            q.let(
                {'user': q.ref(q.collection(users), update.effective_chat.id)},
                q.if_(
                    q.exists(q.var('user')),
                    q.update(q.var('user'), {'data': {
                        'last_command': '',
                    }}), 'Success!')))
    except Exception as err:
        log_error(err)
Ejemplo n.º 5
0
def help_user(update, context):
    user = User(update.effective_chat.id)
    if str(user.chat_id) == str(os.getenv('ADMIN_CHAT_ID')):
        message = config['message']['help_admin']
    else:
        message = config['message']['help']
    context.bot.send_message(chat_id=user.chat_id, text=message)
    try:
        client.query(
            q.let({'user': q.ref(q.collection(users), user.chat_id)},
                  q.if_(
                      q.exists(q.var('user')),
                      q.update(q.var('user'), {'data': {
                          'last_command': '',
                      }}), 'Success!')))
    except Exception as err:
        log_error(err)
    def test_create_access_providers(self):
        providerName = 'provider_'
        issuerName = 'issuer_'
        jwksUri = 'https://xxx.auth0.com/somewhere'
        provider = self.admin_client.query(
            query.create_access_provider({
                "name": providerName,
                "issuer": issuerName,
                "jwks_uri": jwksUri
            }))
        self.assertTrue(
            self.admin_client.query(
                query.exists(query.access_provider(providerName))))
        self.assertEqual(provider["name"], providerName)
        self.assertEqual(provider["issuer"], issuerName)
        self.assertEqual(provider["jwks_uri"], jwksUri)

        #fails if already exists
        self.assertRaises(
            BadRequest, lambda: self.admin_client.query(
                query.create_access_provider({
                    "name": providerName,
                    "issuer": issuerName,
                    "jwks_uri": jwksUri
                })))

        #fails without issuer
        self.assertRaises(
            BadRequest, lambda: self.admin_client.query(
                query.create_access_provider({
                    "name": providerName,
                    "jwks_uri": jwksUri
                })))

        #fails with invalid uri
        jwksUri = 'https:/invalid-uri'
        self.assertRaises(
            BadRequest, lambda: self.admin_client.query(
                query.create_access_provider({
                    "name": providerName,
                    "issuer": issuerName,
                    "jwks_uri": jwksUri
                })))
Ejemplo n.º 7
0
    def test_create_key(self):
        self.admin_client.query(
            query.create_database({"name": "database_for_key_test"}))

        resource = self.admin_client.query(
            query.create_key({
                "database":
                query.database("database_for_key_test"),
                "role":
                "server"
            }))

        new_client = self.admin_client.new_session_client(
            secret=resource["secret"])

        new_client.query(
            query.create_collection({"name": "collection_for_test"}))

        self.assertTrue(
            new_client.query(
                query.exists(query.collection("collection_for_test"))))
Ejemplo n.º 8
0
def create_database(scheme, domain, port, secret, db_name):
    #
    # Create an admin client. This is the client we will use to create the database.
    #
    # If you are using the the FaunaDB-Cloud you will need to replace the value of the
    # 'secret' in the command below with your "secret".
    #
    adminClient = FaunaClient(secret=secret,
                              domain=domain,
                              scheme=scheme,
                              port=port)
    print("Connected to FaunaDB as admin!")

    #
    # The code below creates the Database that will be used for this example. Please note that
    # the existence of the database is evaluated, deleted if it exists and recreated with a single
    # call to the Fauna DB.
    #
    res = adminClient.query(
        q.if_(q.exists(q.database(db_name)), [
            q.delete(q.database(db_name)),
            q.create_database({"name": db_name})
        ], q.create_database({"name": db_name})))
    print('DB {0} created: {1}'.format(db_name, res))

    #
    # Create a key specific to the database we just created. We will use this to
    # create a new client we will use in the remainder of the examples.
    #
    res = adminClient.query(
        q.select(["secret"],
                 q.create_key({
                     "database": q.database(db_name),
                     "role": "server"
                 })))
    print('DB {0} secret: {1}'.format(db_name, res))

    return res
Ejemplo n.º 9
0
    def record(self, data: Data) -> QueryResult:
        """In one query, updates existing topic document with data 
           if document already exists, else create a new document.

        Parameters
        ----------
        data : Data
            Parsed message from the MQTT broker.

        Returns
        -------
        QueryResult
            See src.types.QueryResult for its signature.
        """
        topic = q.match(self.index, data.get("topic", ""))
        update_record = q.update(q.select(["ref"], q.get(topic)),
                                 {"data": data})
        create_record = q.create(self.collection, {"data": data})
        result = self.db.query(
            q.let(
                {"topic_exists": q.exists(topic)},
                q.if_(q.var("topic_exists"), update_record, create_record),
            ))
        return result
Ejemplo n.º 10
0
    def test_create_collection(self):
        self._q(query.create_collection({"name": "collection_for_test"}))

        self.assertTrue(
            self._q(query.exists(query.collection("collection_for_test"))))
Ejemplo n.º 11
0
 def test_delete(self):
     ref = self._create()["ref"]
     self._q(query.delete(ref))
     self.assertFalse(self._q(query.exists(ref)))
Ejemplo n.º 12
0
 def test_foreach(self):
     refs = [self._create()["ref"], self._create()["ref"]]
     self._q(query.foreach(query.delete, refs))
     for ref in refs:
         self.assertFalse(self._q(query.exists(ref)))
Ejemplo n.º 13
0
def _define_match_set(query_filter: sql.Filter) -> QueryExpression:
    field_name = query_filter.column.name
    comparison_value = query_filter.value
    index_name_for_collection = functools.partial(index_name,
                                                  query_filter.table_name)
    convert_to_collection_ref_set = functools.partial(convert_to_ref_set,
                                                      query_filter.table_name)

    get_info_indexes_with_references = lambda collection_name, field_name: q.map_(
        q.lambda_("info_index_ref", q.get(q.var("info_index_ref"))),
        q.paginate(
            q.match(
                q.index(
                    index_name(
                        "information_schema_indexes_",
                        column_name="name_",
                        index_type=IndexType.TERM,
                    )),
                index_name(
                    collection_name,
                    column_name=field_name,
                    index_type=IndexType.REF,
                ),
            ), ),
    )

    index_name_for_field = functools.partial(index_name_for_collection,
                                             field_name)
    equality_range = q.range(
        q.match(q.index(index_name_for_field(IndexType.VALUE))),
        [comparison_value],
        [comparison_value],
    )

    if query_filter.checks_whether_equal:
        if field_name == "ref":
            assert isinstance(comparison_value, str)
            return q.singleton(
                q.ref(q.collection(query_filter.table_name), comparison_value))

        return q.let(
            {
                "ref_index":
                q.index(index_name_for_field(IndexType.REF)),
                "term_index":
                q.index(index_name_for_field(IndexType.TERM)),
                "info_indexes":
                get_info_indexes_with_references(query_filter.table_name,
                                                 field_name),
                "comparison_value":
                comparison_value,
            },
            q.if_(
                q.exists(q.var("ref_index")),
                q.match(
                    q.var("ref_index"),
                    get_foreign_key_ref(
                        q.var("comparison_value"),
                        # Assumes that there is only one reference per foreign key
                        # and that it refers to the associated collection's ID field
                        # (e.g. {'associated_table': 'id'}).
                        # This is enforced via NotSupported errors when creating collections.
                        q.select([0, DATA, "referred_table_"],
                                 q.var("info_indexes")),
                    ),
                ),
                q.if_(
                    q.exists(q.var("term_index")),
                    q.match(
                        q.var("term_index"),
                        q.var("comparison_value"),
                    ),
                    convert_to_collection_ref_set(equality_range),
                ),
            ),
        )

    # In the building of Filter objects from SQL tokens, we enforce the convention
    # of <column name> <operator> <value> for WHERE clauses, so we build the FQL queries
    # assuming that '>' means 'column value greater than literal value'. I can't think
    # of a good way to centralize the knowledge of this convention across
    # all query translation, so I'm leaving this note as a warning.
    if query_filter.checks_whether_greater_than:
        inclusive_comparison_range = q.range(
            q.match(q.index(index_name_for_field(IndexType.VALUE))),
            [comparison_value],
            [],
        )
        return convert_to_collection_ref_set(
            q.difference(inclusive_comparison_range, equality_range))

    if query_filter.checks_whether_greater_than_or_equal:
        inclusive_comparison_range = q.range(
            q.match(q.index(index_name_for_field(IndexType.VALUE))),
            [comparison_value],
            [],
        )
        return convert_to_collection_ref_set(inclusive_comparison_range)

    if query_filter.checks_whether_less_than:
        inclusive_comparison_range = q.range(
            q.match(q.index(index_name_for_field(IndexType.VALUE))),
            [],
            [comparison_value],
        )
        return convert_to_collection_ref_set(
            q.difference(inclusive_comparison_range, equality_range))

    if query_filter.checks_whether_less_than_or_equal:
        inclusive_comparison_range = q.range(
            q.match(q.index(index_name_for_field(IndexType.VALUE))),
            [],
            [comparison_value],
        )
        return convert_to_collection_ref_set(inclusive_comparison_range)

    raise exceptions.NotSupportedError(
        f"Unsupported comparison {query_filter.comparison} was received.")
Ejemplo n.º 14
0
  def test_create_function(self):
    self._q(query.create_function({"name": "a_function", "body": query.query(lambda x: x)}))

    self.assertTrue(self._q(query.exists(query.function("a_function"))))
Ejemplo n.º 15
0
  def test_create_database(self):
    self.admin_client.query(query.create_database({"name": "database_for_test"}))

    self.assertTrue(self.admin_client.query(query.exists(query.database("database_for_test"))))
Ejemplo n.º 16
0
def create_indexes(client):
    indexes = [{
        "name": "user_by_email",
        "source": q.collection("users"),
        "terms": [{
            "field": ["data", "email"]
        }],
    }, {
        "name": "products_search_by_name",
        "source": {
            "collection": q.collection('products'),
            "fields": {
                "wordparts":
                q.query(lambda product: wordPartsGenerator(
                    q.select(['data', 'name'], product)))
            }
        },
        "terms": [{
            "binding": 'wordparts'
        }],
    }, {
        "name": "products_search_by_category",
        "source": q.collection('products'),
        "terms": [{
            "field": ["data", "categories"]
        }],
    }, {
        "name": "products_sort_by_name_asc",
        "source": q.collection('products'),
        "terms": [{
            "field": ["ref"]
        }],
        "values": [
            {
                "field": ["data", "name"]
            },
            {
                "field": ["ref"]
            },
        ]
    }, {
        "name": "products_sort_by_price_asc",
        "source": q.collection('products'),
        "terms": [{
            "field": ["ref"]
        }],
        "values": [
            {
                "field": ["data", "price"]
            },
            {
                "field": ["ref"]
            },
        ]
    }, {
        "name":
        "products_sort_by_price_desc",
        "source":
        q.collection('products'),
        "terms": [{
            "field": ["ref"]
        }],
        "values": [
            {
                "field": ["data", "price"],
                "reverse": True
            },
            {
                "field": ["ref"]
            },
        ]
    }, {
        "name":
        "products_sort_by_created_asc",
        "source":
        q.collection('products'),
        "values": [
            {
                "field": ["data", "createdAt"]
            },
            {
                "field": ["ref"]
            },
        ]
    }]

    client.query(
        q.map_(
            lambda index: q.if_(q.exists(q.index(q.select(["name"], index))),
                                True, q.create_index(index)), indexes))
Ejemplo n.º 17
0
def callback_handler_func(update: Update, context: CallbackContext):
    user = User(update.effective_chat.id)
    callback_message = update.callback_query.message.reply_markup.inline_keyboard[
        0][0].callback_data

    [command, payload] = callback_message.split(sep='=')

    if command == 'subscribe':
        user.subscribe_to_anime(payload)
    elif command == 'unsubscribe':
        user.unsubscribe_from_anime(payload)
    elif command == 'getlatest':
        try:
            anime_info = scraper.get_anime_info(payload)

            latest_episode_download_link = shorten(
                scraper.get_download_link(anime_info['latest_episode_link'],
                                          resolution=user.resolution))
            markup = [[
                InlineKeyboardButton(text='Download',
                                     url=latest_episode_download_link)
            ]]
            context.bot.send_message(chat_id=user.chat_id,
                                     text=anime_info['latest_episode_title'],
                                     reply_markup=InlineKeyboardMarkup(markup))
        except CannotDownloadAnimeException as err:
            log_error(err)
            context.bot.send_message(chat_id=user.chat_id,
                                     text="Sorry," + payload +
                                     "could not be downloaded at this "
                                     "time!")
            context.bot.send_message(chat_id=os.getenv('ADMIN_CHAT_ID'),
                                     text='A user tried to download ' +
                                     payload + "but could not due to error: " +
                                     str(err))
            return
        except Exception as err:
            log_error(err)
            return
        else:
            # check if anime is in our anime registry
            try:
                anime_from_db = client.query(
                    q.if_(
                        q.exists(
                            q.match(q.index(anime_by_id),
                                    anime_info['anime_id'])),
                        q.let(
                            {
                                'anime':
                                q.get(
                                    q.match(q.index(anime_by_id),
                                            anime_info['anime_id']))
                            },
                            q.if_(
                                q.gt(
                                    anime_info['number_of_episodes'],
                                    q.select(['data', 'episodes'],
                                             q.var('anime'))), q.var('anime'),
                                None)), None))
            except errors.NotFound:
                anime_from_db = None
            if anime_from_db is not None:
                send_update_to_subscribed_users(
                    anime_from_db,
                    download_links={
                        user.resolution: latest_episode_download_link
                    },
                    anime_info=anime_info)
    elif command == 'set_resolution':
        try:
            new_res = Resolution(payload)
            user.resolution = new_res
            context.bot.send_message(
                chat_id=user.chat_id,
                text=
                f'Your desired resolution has been set to {new_res.value}({resolutions[new_res]}).\nThis resolution will be used for your future /subscribe and /latest commands.'
            )
        except ValueError:
            context.bot.send_message(chat_id=user.chat_id,
                                     text='Unidentified resolution level!')
            context.bot.send_message(chat_id=os.getenv('ADMIN_CHAT_ID'),
                                     text='Unidentified resolution level!')
    else:
        pass
 def test_exists(self):
     self.assertJson(query.exists(query.collection("widget")),
                     '{"exists":{"collection":"widget"}}')
     self.assertJson(query.exists(query.collection("widget"), ts=123),
                     '{"exists":{"collection":"widget"},"ts":123}')
Ejemplo n.º 19
0
    def subscribe_to_anime(self, anime_link: str):
        try:
            # create a new anime document
            anime_info = anime_alarm.utils.GGAScraper().get_anime_info(
                anime_link)

            print(anime_info['anime_id'])

            result = client.query(
                q.let(
                    {
                        'user_anime_list':
                        q.select(['data', 'animes_watching'],
                                 q.get(q.ref(q.collection(users),
                                             self.chat_id))),
                    },
                    q.if_(
                        # check if this anime exists in the db
                        q.exists(
                            q.match(q.index(anime_by_id),
                                    anime_info['anime_id'])),

                        # if it exists...
                        q.let(
                            {
                                'anime_ref':
                                q.select(
                                    'ref',
                                    q.get(
                                        q.match(q.index(anime_by_id),
                                                anime_info['anime_id'])))
                            },
                            q.if_(
                                # check if user has subscribed to this anime already
                                q.contains_value(q.var('anime_ref'),
                                                 q.var('user_anime_list')),
                                'This anime is already on your watch list!',
                                q.do(
                                    q.update(
                                        q.ref(q.collection(users),
                                              self.chat_id),
                                        {
                                            'data': {
                                                'animes_watching':
                                                q.append(
                                                    q.var('user_anime_list'),
                                                    [q.var('anime_ref')])
                                            }
                                        }),
                                    q.update(
                                        q.var('anime_ref'), {
                                            'data': {
                                                'followers':
                                                q.add(
                                                    q.select([
                                                        'data', 'followers'
                                                    ], q.get(
                                                        q.var('anime_ref'))),
                                                    1)
                                            }
                                        }),
                                ))),
                        q.let(
                            {'new_anime_id': q.new_id()},
                            q.do(
                                # create new anime document
                                q.create(
                                    q.ref(q.collection(animes),
                                          q.var('new_anime_id')),
                                    {
                                        'data': {
                                            'title':
                                            anime_info['title'],
                                            'followers':
                                            1,
                                            'link':
                                            anime_link,
                                            'anime_id':
                                            anime_info['anime_id'],
                                            'anime_alias':
                                            anime_info['anime_alias'],
                                            'episodes':
                                            anime_info['number_of_episodes'],
                                            'last_episode': {
                                                'link':
                                                anime_info[
                                                    'latest_episode_link'],
                                                'title':
                                                anime_info[
                                                    'latest_episode_title'],
                                            },
                                        }
                                    }),
                                # add to user's list of subscribed animes
                                q.update(
                                    q.ref(q.collection(users), self.chat_id), {
                                        'data': {
                                            'animes_watching':
                                            q.append(
                                                q.var('user_anime_list'), [
                                                    q.ref(
                                                        q.collection(animes),
                                                        q.var('new_anime_id'))
                                                ])
                                        }
                                    }),
                            )))))

            if isinstance(result, str):
                updater.bot.send_message(chat_id=self.chat_id, text=result)
            else:
                updater.bot.send_message(
                    chat_id=self.chat_id,
                    text='You are now listening for updates on ' +
                    anime_info['title'])
        except Exception as err:
            log_error(err)