library.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. """Library models for file manager functionality."""
  2. from datetime import datetime
  3. from sqlalchemy import JSON, Boolean, DateTime, ForeignKey, Integer, Select, String, Text, func, select
  4. from sqlalchemy.orm import Mapped, mapped_column, relationship
  5. from backend.app.core.database import Base
  6. class LibraryFolder(Base):
  7. """Folder for organizing library files."""
  8. __tablename__ = "library_folders"
  9. id: Mapped[int] = mapped_column(primary_key=True)
  10. name: Mapped[str] = mapped_column(String(255))
  11. parent_id: Mapped[int | None] = mapped_column(ForeignKey("library_folders.id", ondelete="CASCADE"), nullable=True)
  12. # External folder flags (for folders that point to external paths)
  13. is_external: Mapped[bool] = mapped_column(Boolean, default=False)
  14. external_readonly: Mapped[bool] = mapped_column(Boolean, default=False)
  15. external_show_hidden: Mapped[bool] = mapped_column(Boolean, default=False)
  16. external_path: Mapped[str | None] = mapped_column(String(500), nullable=True)
  17. # Link to project or archive
  18. project_id: Mapped[int | None] = mapped_column(ForeignKey("projects.id", ondelete="SET NULL"), nullable=True)
  19. # use_alter breaks a dependency cycle in the schema, and is not about this
  20. # link being special: print_archives.library_file_id -> library_files,
  21. # library_files.folder_id -> library_folders, and this column back to
  22. # print_archives. Each is reasonable alone and together they are a loop
  23. # SQLAlchemy cannot topologically sort, so metadata.sorted_tables dropped
  24. # those edges, warned on every backup and restore, and could hand back an
  25. # order placing a child before its parent -- which once imported
  26. # library_files ahead of library_folders and killed a restore on a foreign
  27. # key violation. Marking ONE edge for ALTER removes it from the sort graph
  28. # and the other two order correctly. The constraint is still created and
  29. # still enforced: PostgreSQL emits it as ALTER TABLE ADD CONSTRAINT (as it
  30. # already does for every constraint on these three tables), and SQLite,
  31. # which reports no ALTER support, inlines it into CREATE TABLE as before.
  32. # It has to be named, because an unnamed constraint cannot be ALTERed in.
  33. archive_id: Mapped[int | None] = mapped_column(
  34. ForeignKey(
  35. "print_archives.id",
  36. ondelete="SET NULL",
  37. use_alter=True,
  38. name="fk_library_folders_archive_id",
  39. ),
  40. nullable=True,
  41. )
  42. # Timestamps
  43. created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
  44. updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
  45. # Real on-disk modification time of the directory this folder mirrors (#2680).
  46. # For external folders this is captured from ``os.stat().st_mtime`` on scan so
  47. # the tree's "sort by recent activity" matches ``ls -t`` instead of ordering by
  48. # the DB row's ``updated_at`` (which is the scan instant, identical for every
  49. # row of a bulk scan). Null for managed (internal) folders, which have no
  50. # meaningful directory mtime — callers fall back to ``updated_at``/``created_at``.
  51. fs_modified_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
  52. # Relationships
  53. parent: Mapped["LibraryFolder | None"] = relationship(
  54. "LibraryFolder",
  55. back_populates="children",
  56. remote_side="LibraryFolder.id",
  57. foreign_keys="LibraryFolder.parent_id",
  58. )
  59. children: Mapped[list["LibraryFolder"]] = relationship(
  60. "LibraryFolder",
  61. back_populates="parent",
  62. foreign_keys="LibraryFolder.parent_id",
  63. cascade="all, delete-orphan",
  64. )
  65. files: Mapped[list["LibraryFile"]] = relationship(
  66. back_populates="folder",
  67. cascade="all, delete-orphan",
  68. )
  69. project: Mapped["Project | None"] = relationship()
  70. archive: Mapped["PrintArchive | None"] = relationship()
  71. class FileVariantGroup(Base):
  72. """A set of library files that are the same job sliced for different printers.
  73. Members are peers, not a source/output hierarchy. The group answers one
  74. question — "which of these files goes to an H2S, and which to an H2C" — and
  75. both open features need that answer from opposite ends: the print queue
  76. picks the printer and needs the matching file (#671), the File Manager's
  77. print action has the printer already and needs the same match (#2570).
  78. The group deliberately stores no model information of its own. Each
  79. member's target model comes from its own ``file_metadata['sliced_for_model']``,
  80. parsed out of the 3MF, so a group can never disagree with the files it
  81. contains. It also carries no pointer to an unsliced source file: that is a
  82. display concern for the grouped File Manager listing, which is not built.
  83. Deleting a group ungroups its files rather than deleting them (the member
  84. side is ON DELETE SET NULL) — every member is independently printable.
  85. """
  86. __tablename__ = "file_variant_groups"
  87. id: Mapped[int] = mapped_column(primary_key=True)
  88. name: Mapped[str] = mapped_column(String(255))
  89. created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
  90. updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
  91. created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
  92. files: Mapped[list["LibraryFile"]] = relationship(
  93. back_populates="variant_group",
  94. order_by="LibraryFile.variant_position",
  95. )
  96. created_by: Mapped["User | None"] = relationship()
  97. class LibraryFile(Base):
  98. """File stored in the library."""
  99. __tablename__ = "library_files"
  100. id: Mapped[int] = mapped_column(primary_key=True)
  101. folder_id: Mapped[int | None] = mapped_column(ForeignKey("library_folders.id", ondelete="CASCADE"), nullable=True)
  102. project_id: Mapped[int | None] = mapped_column(ForeignKey("projects.id", ondelete="SET NULL"), nullable=True)
  103. # External file flag
  104. is_external: Mapped[bool] = mapped_column(Boolean, default=False)
  105. # File info
  106. filename: Mapped[str] = mapped_column(String(255)) # Original filename
  107. file_path: Mapped[str] = mapped_column(String(500)) # Storage path
  108. file_type: Mapped[str] = mapped_column(String(10)) # "3mf" or "gcode"
  109. file_size: Mapped[int] = mapped_column(Integer)
  110. file_hash: Mapped[str | None] = mapped_column(String(64)) # SHA256 for duplicate detection
  111. thumbnail_path: Mapped[str | None] = mapped_column(String(500))
  112. # Extracted metadata (from 3MF parser)
  113. file_metadata: Mapped[dict | None] = mapped_column(JSON)
  114. # Usage tracking
  115. print_count: Mapped[int] = mapped_column(Integer, default=0)
  116. last_printed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
  117. # User notes
  118. notes: Mapped[str | None] = mapped_column(Text, nullable=True)
  119. # Provenance — when the file was imported from an external source (e.g.
  120. # MakerWorld), ``source_type`` identifies the source and ``source_url`` is
  121. # the canonical public URL. Used for "already imported" detection and
  122. # "re-open on MakerWorld" affordances. Index on source_url so the
  123. # dedupe lookup is O(log N).
  124. source_type: Mapped[str | None] = mapped_column(String(32), nullable=True)
  125. source_url: Mapped[str | None] = mapped_column(String(512), nullable=True, index=True)
  126. # Variant grouping (#671 / #2570). A file belongs to at most one group of
  127. # "same job, sliced for a different printer" siblings. SET NULL on group
  128. # delete: ungrouping must never take the files with it. ``variant_position``
  129. # is the user's priority order within the group — when two printers are idle
  130. # at the same scheduler tick, the lowest position wins, so the pick is
  131. # reproducible instead of depending on which match the scheduler found first.
  132. variant_group_id: Mapped[int | None] = mapped_column(
  133. ForeignKey("file_variant_groups.id", ondelete="SET NULL"), nullable=True, index=True
  134. )
  135. variant_position: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
  136. # User's answer to "which printer is this for", for a file that does not say.
  137. # Files imported before Bambuddy parsed ``sliced_for_model`` — and raw .gcode —
  138. # declare nothing, and without this they could never be grouped. Deliberately
  139. # NOT written into ``file_metadata``: that holds what was parsed out of the
  140. # file, and a user's assertion must not become indistinguishable from it.
  141. variant_target_model: Mapped[str | None] = mapped_column(String(50), nullable=True)
  142. # User tracking (Issue #206)
  143. created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
  144. # Soft-delete / trash bin (Issue #1008). When non-null, the file is in the
  145. # trash and should not appear in normal listings. A background sweeper
  146. # hard-deletes rows whose deleted_at is older than the retention window.
  147. deleted_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, index=True)
  148. # Timestamps
  149. created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
  150. updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
  151. # Real on-disk modification time of the file (#2680). Captured from
  152. # ``os.stat().st_mtime`` for external files on scan so the file pane's date
  153. # sort and the folder tree's recursive "recent activity" bubble reflect the
  154. # actual filesystem mtime (``ls -t``) rather than the DB ``updated_at`` (the
  155. # scan instant, identical across a bulk scan). Null for managed uploads —
  156. # callers fall back to ``created_at``.
  157. fs_modified_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
  158. # Relationships
  159. folder: Mapped["LibraryFolder | None"] = relationship(back_populates="files")
  160. project: Mapped["Project | None"] = relationship()
  161. created_by: Mapped["User | None"] = relationship()
  162. variant_group: Mapped["FileVariantGroup | None"] = relationship(back_populates="files")
  163. # Tags (#1268). M2M via library_file_tags. Loaded explicitly via
  164. # ``selectinload`` in list_files so each row in the listing carries its
  165. # chip set without N+1 fetches.
  166. tags: Mapped[list["LibraryTag"]] = relationship(
  167. secondary="library_file_tags",
  168. back_populates="files",
  169. )
  170. @classmethod
  171. def active(cls) -> "Select[tuple[LibraryFile]]":
  172. """Select statement that excludes trashed (soft-deleted) files.
  173. Use this in place of ``select(LibraryFile)`` for any user-facing listing
  174. or lookup so trashed files don't leak into normal flows. Endpoints that
  175. specifically operate on trashed rows (trash list, restore, sweeper)
  176. must use ``select(LibraryFile)`` directly.
  177. """
  178. return select(cls).where(cls.deleted_at.is_(None))
  179. class LibraryTag(Base):
  180. """User-authored cross-cutting label for library files (#1268).
  181. Folders express hierarchy; tags express orthogonal attributes ("toy",
  182. "kid-safe", "petg-only"). Catalog is global (one tag set per install)
  183. — the multi-user "private tags" case is not in v1 scope. ``name_key``
  184. is ``LOWER(TRIM(name))`` so "Toys" / "toys" / " TOYS " all collide
  185. on the UNIQUE index and the route returns 409 instead of silently
  186. creating a duplicate.
  187. """
  188. __tablename__ = "library_tags"
  189. id: Mapped[int] = mapped_column(primary_key=True)
  190. name: Mapped[str] = mapped_column(String(64), nullable=False)
  191. name_key: Mapped[str] = mapped_column(String(64), nullable=False, unique=True, index=True)
  192. created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
  193. updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
  194. files: Mapped[list["LibraryFile"]] = relationship(
  195. secondary="library_file_tags",
  196. back_populates="tags",
  197. )
  198. class LibraryFileTag(Base):
  199. """Association between library files and tags (#1268).
  200. Composite PK so the same (file, tag) pair can't be inserted twice. Both
  201. sides ON DELETE CASCADE: deleting a tag drops every association row,
  202. deleting a file drops its tag links, and the catalog row survives so
  203. other files keep their chip.
  204. """
  205. __tablename__ = "library_file_tags"
  206. file_id: Mapped[int] = mapped_column(ForeignKey("library_files.id", ondelete="CASCADE"), primary_key=True)
  207. tag_id: Mapped[int] = mapped_column(ForeignKey("library_tags.id", ondelete="CASCADE"), primary_key=True)
  208. created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
  209. from backend.app.models.archive import PrintArchive # noqa: E402, F811
  210. from backend.app.models.project import Project # noqa: E402, F811
  211. from backend.app.models.user import User # noqa: E402, F811