示例#1
0
文件: maps.py 项目: Joss/notion-py
 def api2py(x, client=None):
     x = x or [[""]]
     if markdown:
         x = notion_to_markdown(x)
     kwargs = {}
     if "client" in signature(api_to_python).parameters:
         kwargs["client"] = client
     return api_to_python(x, **kwargs)
示例#2
0
文件: basic.py 项目: Joss/notion-py
    def _convert_notion_to_python(self, val, prop):
        # TODO: REWRITE THIS MONSTROSITY !!

        if prop["type"] in ["title", "text"]:
            for i, part in enumerate(val):
                if len(part) == 2:
                    for format in part[1]:
                        if "p" in format:
                            page = self._client.get_block(format[1])
                            val[i] = [
                                "[" + page.icon + " " + page.title + "](" +
                                page.get_browseable_url() + ")"
                            ]

            val = notion_to_markdown(val) if val else ""
        if prop["type"] in ["number"]:
            if val is not None:
                val = val[0][0]
                if "." in val:
                    val = float(val)
                else:
                    val = int(val)
        if prop["type"] in ["select"]:
            val = val[0][0] if val else None
        if prop["type"] in ["multi_select"]:
            val = [v.strip() for v in val[0][0].split(",")] if val else []
        if prop["type"] in ["person"]:
            val = ([
                self._client.get_user(item[1][0][1]) for item in val
                if item[0] == "‣"
            ] if val else [])
        if prop["type"] in ["email", "phone_number", "url"]:
            val = val[0][0] if val else ""
        if prop["type"] in ["date"]:
            val = NotionDate.from_notion(val)
        if prop["type"] in ["file"]:
            val = ([
                add_signed_prefix_as_needed(item[1][0][1], client=self._client)
                for item in val if item[0] != ","
            ] if val else [])
        if prop["type"] in ["checkbox"]:
            val = val[0][0] == "Yes" if val else False
        if prop["type"] in ["relation"]:
            val = ([
                self._client.get_block(item[1][0][1]) for item in val
                if item[0] == "‣"
            ] if val else [])
        if prop["type"] in ["created_time", "last_edited_time"]:
            val = self.get(prop["type"])
            val = datetime.utcfromtimestamp(val / 1000)
        if prop["type"] in ["created_by", "last_edited_by"]:
            val = self.get(prop["type"])
            val = self._client.get_user(val)

        return val
示例#3
0
    def convert_title(cls, value, block, **_):
        for i, part in enumerate(value):
            if len(part) == 2:
                for fmt in part[1]:
                    if "p" in fmt:
                        page = block._client.get_block(fmt[1])
                        title = f"{page.icon} {page.title}"
                        address = page.get_browseable_url()
                        value[i] = f"[{title}]({address})"

        return notion_to_markdown(value) if value else ""
示例#4
0
def __preprocess_notion_links(ctx: Context, b: block.TextBlock) -> str:
    config = ctx["config"]
    chunks = b.get("properties.title")

    if chunks is None or len(chunks) == 0:
        return ""

    for chunk in chunks:
        # For the chunks that have formatting
        if len(chunk) > 1:
            # Each chunk can have multiple modifiers
            for modifier in chunk[1]:
                # Only process Notion page links.
                # Replace Notion link formatting with a regular
                # Markdown link formatting and invoke Noton Py's
                # formatting function.
                if modifier[0] == "p":
                    page_id = modifier[1]
                    page = __get_linked_page(ctx["page"], page_id)
                    modifier[0] = "a"
                    modifier[1] = __linked_page_url(config, page)
                    chunk[0] = page.title

    return notion_to_markdown(chunks)
示例#5
0
    def get_markdown_from_block(self, block, is_page_root=False):
        # print('traverse', type(block), block)
        if isinstance(block, notion.collection.CollectionRowBlock):
            if is_page_root:
                # if we are on the page root, traverse the subpage
                return "\n\n".join([
                    md for md in [
                        self.get_markdown_from_block(child)
                        for child in block.children
                    ] if md is not None
                ])
            else:
                # otherwise, just link to the page
                contains_row = self.context.contains_row(block)
                if not contains_row:
                    return ""

                block_url = self.context.get_block_url(block)

                return "[%s](%s)" % (get_decorated_row_title(block), block_url)

        elif isinstance(block, notion.block.TextBlock):
            return block.title
        elif isinstance(block, notion.block.HeaderBlock):
            return "# " + block.title
        elif isinstance(block, notion.block.SubheaderBlock):
            return "## " + block.title
        elif block.type == "sub_sub_header":
            return "### " + notion_to_markdown(
                block._get_record_data()["properties"]["title"])
        elif isinstance(block, notion.block.BulletedListBlock):
            row = "- " + block.title
            subrows = self.indent_children(block.children)
            return row + "\n" + subrows
        elif isinstance(block, notion.block.NumberedListBlock):
            row = "1. " + block.title
            subrows = self.indent_children(block.children)
            return row + "\n" + subrows
        elif isinstance(block, notion.block.ColumnListBlock):
            subsections = "\n".join([
                self.get_markdown_from_block(child) for child in block.children
            ])
            return (
                '<section class="columnSplit" style="display:flex;">%s</section>'
                % subsections)
        elif isinstance(block, notion.block.ColumnBlock):
            return '<section style="flex: %s; padding: 0.5em">\n%s\n\n</section>' % (
                block.column_ratio,
                "\n\n".join(
                    self.get_markdown_from_block(child)
                    for child in block.children),
            )
        elif isinstance(block, notion.block.ImageBlock):
            raw_source = notion_to_markdown(
                block._get_record_data()["properties"]["source"])
            return "![%s](%s)" % (
                block.caption if block.caption != None else "",
                block.source,
            )
        elif isinstance(block, notion.block.CodeBlock):
            code_source = block.title
            code_language = block.language if block.language != "Plain Text" else ""
            return "```%s\n%s\n```" % (code_language, code_source)
        elif isinstance(block, notion.block.QuoteBlock):
            quote_body = block.title
            return "> " + "\n> ".join(quote_body.split("\n"))
        elif isinstance(block, notion.block.TodoBlock):
            row = "[%s] %s" % ("x" if block.checked else " ", block.title)
            subrows = self.indent_children(block.children)
            return row + "\n" + subrows
        elif isinstance(block, notion.block.DividerBlock):
            return "---\n"
        elif isinstance(block, notion.block.CollectionViewBlock):
            # TODO handle these if they are tables
            pass
        else:
            print("encountered unknown block type")
            print(type(block), block, block._get_record_data())
            return str(block)