photo-store.lisp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. (in-package #:photo-store)
  2. (use-package :iter)
  3. (eval-when (:compile-toplevel :load-toplevel :execute)
  4. (restas::register-pkgmodule-traits 'photo-store)
  5. (restas:reconnect-all-routes))
  6. ;; photos: id | album_id | filename | size | taken | width | height | lat | lon
  7. ;; albums: id | parent_id | path | date | name | description | cover_id | accessibility
  8. (defvar *db-path* "db.sqlite" "SQLite database path")
  9. (defmacro with-db ((db) &body body)
  10. `(sqlite:with-open-database (,db *db-path* :busy-timeout 10)
  11. (sqlite:execute-non-query ,db "PRAGMA foreign_keys = ON")
  12. ,@body))
  13. (defun db-init ()
  14. (with-db (db)
  15. (sqlite:execute-non-query db "create table if not exists photos (id INTEGER PRIMARY KEY, path, size, taken, width, height, lat, lon)")
  16. (sqlite:execute-non-query db "create table if not exists albums (id INTEGER PRIMARY KEY, name, description, cover_id REFERENCES photos)")
  17. (sqlite:execute-non-query db "create table if not exists album_photos (album_id REFERENCES albums NOT NULL, photo_id REFERENCES photos NOT NULL, description, idx, hidden)")))
  18. (defun db/add-photo (db info)
  19. (let* ((path (namestring (uiop:subpathp (aget :path info) *photo-storage-path*)))
  20. (size (aget :length info))
  21. (taken (local-time:timestamp-to-unix (aget :created-at info)))
  22. (dim (aget :dim info))
  23. (w (first dim)) (h (second dim))
  24. (loc (aget :location info))
  25. (lat (and loc (geo:latitude-deg loc)))
  26. (lon (and loc (geo:longitude-deg loc))))
  27. (sqlite:execute-non-query
  28. db "insert into photos (path, size, taken, width, height, lat, lon) values (?, ?, ?, ?, ?, ?, ?)"
  29. path size taken w h lat lon)
  30. (sqlite:last-insert-rowid db)))
  31. (defun db/add-album (db name &optional description cover-id)
  32. (sqlite:execute-non-query
  33. db "insert into albums (name, description, cover_id) values (?, ?, ?)"
  34. name description cover-id)
  35. (sqlite:last-insert-rowid db))
  36. (defun db/add-album-photo (db album-id photo-id &optional description idx hidden)
  37. (sqlite:execute-non-query
  38. db "insert into album_photos (album_id, photo_id, description, idx, hidden) values (?, ?, ?, ?, ?)"
  39. album-id photo-id description idx hidden))
  40. (defvar *photo-storage-url* nil "base url for photo storage")
  41. (defun db-load-album (album-id)
  42. (with-db (db)
  43. (multiple-value-bind (name cover-id)
  44. (sqlite:execute-one-row-m-v db "select name, cover_id from albums where id = ?" album-id)
  45. (let ((photos (iter (for (id path title w h)
  46. in-sqlite-query "select p.id, p.path, ap.description, p.width, p.height from photos p inner join album_photos ap on ap.photo_id = p.id where ap.album_id = ? order by ap.idx"
  47. on-database db
  48. with-parameters (album-id))
  49. (collect (list (cons :id id)
  50. (cons :src (concatenate 'string *photo-storage-url* path))
  51. (cons :title title)
  52. (cons :w w) (cons :h h))))))
  53. (list (cons :title name)
  54. (cons :cover (find cover-id photos :key (agetter :id)))
  55. (cons :photos photos))))))
  56. (defun db-load-albums ()
  57. (with-db (db)
  58. (iter (for (id title cover-path cover-w cover-h)
  59. in-sqlite-query "select a.id, a.name, c.path, c.width, c.height from albums a inner join photos c on a.cover_id=c.id order by c.taken" on-database db)
  60. (collect (list (cons :id id)
  61. (cons :title title)
  62. (cons :cover (list (cons :src (concatenate 'string
  63. *photo-storage-url* cover-path))
  64. (cons :w cover-w)
  65. (cons :h cover-h))))))))
  66. (defun dirname (directory)
  67. (car (last (pathname-directory directory))))
  68. (defun guess-album-title (directory photos)
  69. (declare (ignore photos))
  70. (dirname directory))
  71. (defvar *album-path-format*
  72. '(:year "/" :year "-" (:month 2) "-" (:day 2) "-" :name "/"))
  73. (defun guess-album-path (directory photos)
  74. (let ((from (reduce #'local-time:timestamp-minimum photos :key (agetter :created-at)))
  75. (format (sublis `((:name . ,(dirname directory)))
  76. *album-path-format*)))
  77. (local-time:format-timestring nil from :format format)))
  78. (defun middle (seq)
  79. (elt seq (/ (length seq) 2)))
  80. (defun imagep (path)
  81. (equal (string-downcase (pathname-type path)) "jpg"))
  82. (defun directory-images (directory)
  83. (remove-if-not 'imagep (uiop:directory-files directory)))
  84. (defun load-album (directory)
  85. (let ((photos (mapcar 'load-photo-info (directory-images directory))))
  86. (when photos
  87. (list (cons :title (guess-album-title directory photos))
  88. (cons :path directory)
  89. (cons :cover (middle photos))
  90. (cons :photos photos)))))
  91. (defun load-albums-from-dir (directory)
  92. (remove-if #'null (list* (load-album directory)
  93. (loop for subdir in (uiop:subdirectories directory)
  94. append (load-albums-from-dir subdir)))))
  95. (defvar *path-url-mapping* nil "alist of path-2-url mapping")
  96. (defun map-path (path)
  97. (loop for (base-path . base-url) in *path-url-mapping*
  98. for rel-path = (uiop:subpathp path base-path)
  99. when rel-path do (return (concatenate 'string base-url (namestring rel-path)))
  100. finally (error "Can't map path ~S" path)))
  101. (defun photo-item (info &optional incoming)
  102. `((:src . ,(map-path (aget :path info)))
  103. ,@(when incoming (list (cons :path (namestring (aget :path info)))))
  104. (:w . ,(first (aget :dim info)))
  105. (:h . ,(second (aget :dim info)))))
  106. (defun album-item (album &optional incoming)
  107. `((:title . ,(aget :title album))
  108. (:cover . ,(photo-item (aget :cover album)))
  109. ,@(when incoming (list (cons :path (namestring (aget :path album)))
  110. (cons :dest (guess-album-path (aget :path album)
  111. (aget :photos album)))))
  112. (:photos . ,(mapcar #'(lambda (p) (photo-item p incoming)) (aget :photos album)))))
  113. (defun other-images (directory images)
  114. (remove-if #'(lambda (img) (member img images :test #'equal))
  115. (directory-images directory)))
  116. (defun directories (files)
  117. (delete-duplicates (mapcar #'uiop:pathname-directory-pathname files) :test #'equal))
  118. (defun move-file-to (file dest)
  119. (let ((destpath (uiop:make-pathname* :defaults file :directory (pathname-directory dest))))
  120. (when (probe-file destpath)
  121. (error "File ~S exists" destpath))
  122. (uiop:rename-file-overwriting-target file destpath)
  123. destpath))
  124. (defun move-images-with-folders (files dest &optional after-move-func)
  125. (labels ((move (files dest)
  126. (dolist (f files)
  127. (funcall after-move-func (move-file-to f dest)))))
  128. (let ((dirs (directories files)))
  129. (unless after-move-func (setf after-move-func #'identity))
  130. (ensure-directories-exist dest)
  131. (move files dest)
  132. ;; Move all non-image files from original folders if no images left there.
  133. ;; Do not call after-move-func on them
  134. (setf after-move-func #'identity)
  135. (dolist (dir dirs)
  136. (unless (other-images dir files)
  137. (move (uiop:directory-files dir) dest)
  138. (ignore-errors (uiop:delete-empty-directory dir)))))))
  139. (defun import-album (name dest paths)
  140. (let (added-photos
  141. (files (remove-if-not #'(lambda (p) (uiop:subpathp p *incoming-path*))
  142. (mapcar #'probe-file paths))))
  143. (when files
  144. (with-db (db)
  145. (sqlite:with-transaction db
  146. (labels ((handle-moved (path)
  147. (let ((info (load-photo-info path)))
  148. (push (cons (db/add-photo db info) (aget :name info)) added-photos)
  149. (log:info "Moved" (aget :path info)))))
  150. (move-images-with-folders files dest #'handle-moved)
  151. (let ((album-id (db/add-album db name nil (car (middle added-photos)))))
  152. (loop for (photo-id . name) in (reverse added-photos)
  153. for idx from 1
  154. do (db/add-album-photo db album-id photo-id name idx))
  155. album-id)))))))
  156. (restas:define-route main ("")
  157. (asdf:system-relative-pathname :photo-store "index.html"))
  158. (restas:define-route incoming ("incoming/")
  159. (asdf:system-relative-pathname :photo-store "incoming.html"))
  160. ;; Assets file path
  161. (defparameter *assets-path*
  162. (asdf:system-relative-pathname :photo-store "assets/"))
  163. (restas:define-route assets/css ("css/:file" :content-type "text/css")
  164. (merge-pathnames file *assets-path*))
  165. (restas:define-route assets/js ("js/:file" :content-type "application/x-javascript")
  166. (merge-pathnames file *assets-path*))
  167. (defun json (object)
  168. (json:encode-json-to-string object))
  169. (defvar *incoming-path* nil "Path for incoming photos")
  170. (restas:define-route api/incoming ("api/incoming/"
  171. :content-type "application/json")
  172. (json (mapcar #'(lambda (a) (album-item a t)) (load-albums-from-dir *incoming-path*))))
  173. (restas:define-route api/albums ("api/albums/"
  174. :content-type "application/json")
  175. (json (db-load-albums)))
  176. (restas:define-route api/album ("api/albums/:album-id/"
  177. :content-type "application/json")
  178. (:sift-variables (album-id 'integer))
  179. (json (db-load-album album-id)))
  180. (defvar *photo-storage-path* nil "Destination storage path")
  181. (defun start (&key (address "0.0.0.0") (port 8800))
  182. (restas:start '#:photo-store :address address :port port))