Example #1
0
    def call_query_collection(
        self,
        collection_id: str,
        collection_view_id: str,
        search: str = "",
        type: str = "table",
        aggregate: list = None,
        aggregations: list = None,
        filter: dict = None,
        filter_operator: str = "and",
        sort: list = [],
        calendar_by: str = "",
        group_by: str = "",
    ):
        # TODO: No idea what this is.

        if aggregate and aggregations:
            raise ValueError(
                "Use either `aggregate` or `aggregations` (old vs new format)"
            )

        aggregate = to_list(aggregate or [])
        aggregations = aggregations or []
        filter = to_list(filter or {})
        sort = to_list(sort or [])

        data = {
            "collectionId": collection_id,
            "collectionViewId": collection_view_id,
            "loader": {
                "limit": 100,
                "loadContentCover": True,
                "searchQuery": search,
                "userLocale": "en",
                "userTimeZone": str(get_localzone()),
                "type": type,
            },
            "query": {
                "aggregate": aggregate,
                "aggregations": aggregations,
                "filter": {
                    "filters": filter,
                    "filter_operator": filter_operator,
                },
                "sort": sort,
            },
        }
        data = self._client.post("queryCollection", data).json()
        self.store_record_map(data)

        return data["result"]
Example #2
0
    def convert_person(cls, value, **_):
        users = []

        for user in to_list(value):
            users += [["‣", [["u", extract_id(user)]]], [","]]

        return users[:-1]
Example #3
0
    def convert_relation(cls, value, block, **_):
        pages = []

        for page in to_list(value):
            if isinstance(page, str):
                page = block._client.get_block(page)
            pages += [["‣", [["p", page.id]]], [","]]

        return pages[:-1]
Example #4
0
    def convert_file(cls, value, **_):
        files = []

        for url in to_list(value):
            url = remove_signed_prefix_as_needed(url)
            name = url.split("/")[-1]
            files += [[name, [["a", url]]], [","]]

        return files[:-1]
Example #5
0
    def _ensure_type(cls, name: str, value, types):
        types = to_list(types)

        for t in types:
            if isinstance(value, t):
                break
        else:
            types = [t.__name__ for t in types]
            msg = f"Value type passed to prop '{name}' must be one of {types}."
            raise TypeError(msg)
Example #6
0
    def convert_select(cls, value, prop, block, **_):
        value = to_list(value)
        if value == [None]:
            return value

        options = prop["options"] = prop.get("options", [])
        valid_options = [[p["value"].lower() for p in options]]
        colors = [
            "default",
            "gray",
            "brown",
            "orange",
            "yellow",
            "green",
            "blue",
            "purple",
            "pink",
            "red",
        ]

        schema_needs_update = False
        for i, v in enumerate(value):
            value[i] = v = v.replace(",", "")
            v_key = v.lower()

            if v_key not in valid_options:
                schema_needs_update = True
                valid_options.append(v_key)
                options.append({
                    "id": str(uuid1()),
                    "value": v,
                    "color": choice(colors)
                })

        value = [[",".join(value)]]

        if schema_needs_update:
            schema = block.collection.get("schema")
            schema[prop["id"]] = prop
            block.collection.set("schema", schema)

        return value
Example #7
0
    def submit_transaction(self,
                           operations: Union[list, dict],
                           update_last_edited: bool = True):
        """
        Submit list of operations in atomic transaction block.


        Arguments
        ---------
        operations : list or dict
            List of operations to submit.

        update_last_edited : bool, optional
            Whether or not to automatically update last edited records.
            Defaults to True.
        """
        if not operations:
            return

        operations = to_list(operations)

        if update_last_edited:
            updated_blocks = set(
                [op["id"] for op in operations if op["table"] == "block"])
            operations += [
                operation_update_last_edited(self.current_user.id, block_id)
                for block_id in updated_blocks
            ]

        if self.in_transaction():
            # TODO: fix that stuff, shouldn't look like that
            ops = getattr(self, "_transaction_operations") + operations
            setattr(self, "_transaction_operations", ops)

        else:
            self.post("submitTransaction", data={"operations": operations})
            for operation in operations:
                operation["record_id"] = operation.pop("id")
                self._store.run_local_operation(**operation)
Example #8
0
    def call_get_record_values(self, **kwargs):
        """
        Call the server's getRecordValues endpoint
        to update the local record store.
        The keyword arguments map table names into lists
        of (or singular) record IDs to load for that table.
        Use True to refresh all known records for that table.
        """
        requests = []

        for table, ids in kwargs.items():
            # TODO: ids can be `True` and if it is then we take every
            #       key from collection_view into consideration, is it OK?
            if ids is True:
                ids = self._values.get(table, {}).keys()
            ids = to_list(ids)

            # if we're in a transaction, add the requested IDs
            # to a queue to refresh when the transaction completes
            if self._client.in_transaction():
                records = self._records_to_refresh.get(table, []) + ids
                self._records_to_refresh[table] = list(set(records))
                continue

            requests += [{"table": table, "id": extract_id(i)} for i in ids]

        if requests:
            logger.debug(f"Calling 'getRecordValues' endpoint for requests: {requests}")
            data = {"requests": requests}
            data = self._client.post("getRecordValues", data).json()
            results = data["results"]

            for request, result in zip(requests, results):
                self._update_record(
                    table=request["table"],
                    record_id=request["id"],
                    value=result.get("value"),
                    role=result.get("role"),
                )