82 lines
2.3 KiB
Python
82 lines
2.3 KiB
Python
from sqlmodel import select, Session
|
|
from pydantic import BaseModel
|
|
from typing import List, Optional
|
|
|
|
import arcology.html as html
|
|
import arcology.roam as roam
|
|
from arcology.parse import *
|
|
|
|
import itertools
|
|
|
|
from dataclasses import dataclass
|
|
|
|
@dataclass
|
|
class Page():
|
|
file_path: str
|
|
root_node: roam.Node
|
|
title: str
|
|
|
|
nodes: Optional[List[roam.Node]]
|
|
backlinks: Optional[List[roam.Link]]
|
|
outlinks: Optional[List[roam.Link]]
|
|
|
|
html: Optional[str]
|
|
backlink_html: Optional[str]
|
|
|
|
@classmethod
|
|
def from_file(cls, path: str):
|
|
keyed_path = print_sexp(path)
|
|
|
|
with Session(roam.engine) as session:
|
|
# top "root" node has level=0
|
|
q = select(roam.Node) \
|
|
.where(roam.Node.level==0) \
|
|
.where(roam.Node.file_ref==keyed_path)
|
|
root_node = session.exec(q).first()
|
|
title = root_node.title if root_node else ""
|
|
|
|
# get all the nodes on the page, and their IDs
|
|
q = select(roam.Node) \
|
|
.where(roam.Node.file_ref==keyed_path)
|
|
nodes = session.exec(q).all()
|
|
node_ids = [node.id for node in nodes]
|
|
|
|
# collect links to all nodes on page
|
|
outlinks = next(itertools.chain([node.outlinks for node in nodes]))
|
|
# collect links *from* all nodes on page
|
|
backlinks = next(itertools.chain([node.backlinks for node in nodes]))
|
|
# (ref:backlink_instantiation)
|
|
|
|
# bundle it together
|
|
return Page(
|
|
file_path=path,
|
|
title=title,
|
|
root_node=root_node,
|
|
|
|
backlinks=backlinks,
|
|
outlinks=outlinks,
|
|
nodes=nodes,
|
|
|
|
html='',
|
|
backlink_html='',
|
|
)
|
|
|
|
def make_backlinks_org(self):
|
|
if self.backlinks is None:
|
|
return ''
|
|
|
|
def to_org(link: roam.Link): # (ref:backlinks_to_org_fn)
|
|
return \
|
|
"""
|
|
* [[{path}][{title}]]
|
|
""".format(
|
|
path=link.source.file_ref,
|
|
title=link.source.title
|
|
)
|
|
|
|
return '\n'.join([ to_org(link) for link in self.backlinks ])
|
|
|
|
def load_html(self):
|
|
self.html = html.gen_html(self.file_path)
|
|
self.backlink_html = html.gen_html_text(self.make_backlinks_org())
|