Browse Source

Add model function and route to do text search over links

Getty Ritter 1 year ago
parent
commit
521c4005aa
2 changed files with 34 additions and 0 deletions
  1. 18 0
      lc/app.py
  2. 16 0
      lc/model.py

+ 18 - 0
lc/app.py

@@ -235,6 +235,24 @@ class GetTaggedLinks(Endpoint):
         )
 
 
+@endpoint("/u/<string:user>/search/<string:needle>")
+class GetStringSearch(Endpoint):
+    def html(self, user: str, needle: str):
+        u = m.User.by_slug(user)
+        pg = int(flask.request.args.get("page", 1))
+        links, pages = u.get_string_search(needle=needle, as_user=self.user, page=pg)
+        tags = u.get_tags()
+        linklist = v.LinkList(links=links, pages=pages, tags=tags, user=user)
+        return render(
+            "main",
+            v.Page(
+                title=f"search for '{needle}'",
+                content=render("linklist", linklist),
+                user=self.user,
+            ),
+        )
+
+
 @endpoint("/u/<string:user>/import")
 class PinboardImport(Endpoint):
     def html(self, user: str):

+ 16 - 0
lc/model.py

@@ -179,6 +179,22 @@ class User(Model):
         )
         return sorted((t.tag.to_view() for t in query), key=lambda t: t.name,)
 
+    def get_string_search(
+        self, needle: str, as_user: Optional["User"], page: int
+    ) -> Tuple[List[v.Link], v.Pagination]:
+        """
+        Find all links that contain the string `needle` somewhere in their URL or title
+        """
+        query = Link.select().where(
+            (Link.user == self)
+            & ((self == as_user) | (Link.private == False))
+            & (Link.name.contains(needle) | Link.description.contains(needle))
+        )
+        links = query.order_by(-Link.created).paginate(page, c.app.per_page)
+        link_views = [l.to_view(as_user) for l in links]
+        pagination = v.Pagination.from_total(page, query.count())
+        return link_views, pagination
+
 
 class Link(Model):
     """