photo-store.lisp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 id, name, cover_id from albums where id = ?" album-id)
  45. (when name
  46. (let ((photos (iter (for (id path title w h)
  47. 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"
  48. on-database db
  49. with-parameters (album-id))
  50. (collect (list (cons :id id)
  51. (cons :src (concatenate 'string *photo-storage-url* path))
  52. (cons :title title)
  53. (cons :w w) (cons :h h))))))
  54. (list (cons :id album-id)
  55. (cons :title name)
  56. (cons :cover (find cover-id photos :key (agetter :id)))
  57. (cons :photos photos)))))))
  58. (defun db-load-albums ()
  59. (with-db (db)
  60. (iter (for (id title cover-path cover-w cover-h)
  61. 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)
  62. (collect (list (cons :id id)
  63. (cons :title title)
  64. (cons :cover (list (cons :src (concatenate 'string
  65. *photo-storage-url* cover-path))
  66. (cons :w cover-w)
  67. (cons :h cover-h))))))))
  68. (defun dirname (directory)
  69. (car (last (pathname-directory directory))))
  70. (defun guess-album-title (directory photos)
  71. (declare (ignore photos))
  72. (dirname directory))
  73. (defvar *album-path-format*
  74. '(:year "/" :year "-" (:month 2) "-" (:day 2) "-" :name "/"))
  75. (defun guess-album-path (directory photos)
  76. (let ((from (reduce #'local-time:timestamp-minimum photos :key (agetter :created-at)))
  77. (format (sublis `((:name . ,(dirname directory)))
  78. *album-path-format*)))
  79. (local-time:format-timestring nil from :format format)))
  80. (defun middle (seq)
  81. (elt seq (floor (length seq) 2)))
  82. (defun imagep (path)
  83. (equal (string-downcase (pathname-type path)) "jpg"))
  84. (defun directory-images (directory)
  85. (remove-if-not 'imagep (uiop:directory-files directory)))
  86. (defun photo-item (info)
  87. `((:src . ,(map-path (aget :path info)))
  88. (:path . ,(namestring (aget :path info)))
  89. (:title . ,(aget :name info))
  90. (:w . ,(first (aget :dim info)))
  91. (:h . ,(second (aget :dim info)))))
  92. (defun load-album (directory)
  93. (let ((photos (mapcar 'load-photo-info (directory-images directory))))
  94. (when photos
  95. `((:title . ,(guess-album-title directory photos))
  96. (:cover . ,(photo-item (middle photos)))
  97. (:dest . ,(guess-album-path directory photos))
  98. (:photos . ,(mapcar 'photo-item photos))))))
  99. (defun fs-load-albums (directory)
  100. (delete nil (list* (load-album directory)
  101. (loop for subdir in (uiop:subdirectories directory)
  102. append (fs-load-albums subdir)))))
  103. (defvar *path-url-mapping* nil "alist of path-2-url mapping")
  104. (defun map-path (path)
  105. (loop for (base-path . base-url) in *path-url-mapping*
  106. for rel-path = (uiop:subpathp path base-path)
  107. when rel-path do (return (concatenate 'string base-url (namestring rel-path)))
  108. finally (error "Can't map path ~S" path)))
  109. (defun other-images (directory images)
  110. (remove-if #'(lambda (img) (member img images :test #'equal))
  111. (directory-images directory)))
  112. (defun directories (files)
  113. (delete-duplicates (mapcar #'uiop:pathname-directory-pathname files) :test #'equal))
  114. (defun move-file-to (file dest)
  115. (let ((destpath (uiop:make-pathname* :defaults file :directory (pathname-directory dest))))
  116. (when (probe-file destpath)
  117. (error "File ~S exists" destpath))
  118. (uiop:rename-file-overwriting-target file destpath)
  119. destpath))
  120. (defun move-images-with-folders (files dest &optional after-move-func)
  121. (labels ((move (files dest)
  122. (dolist (f files)
  123. (funcall after-move-func (move-file-to f dest)))))
  124. (let ((dirs (directories files)))
  125. (unless after-move-func (setf after-move-func #'identity))
  126. (ensure-directories-exist dest)
  127. (move files dest)
  128. ;; Move all non-image files from original folders if no images left there.
  129. ;; Do not call after-move-func on them
  130. (setf after-move-func #'identity)
  131. (dolist (dir dirs)
  132. (unless (other-images dir files)
  133. (move (uiop:directory-files dir) dest)
  134. (ignore-errors (uiop:delete-empty-directory dir)))))))
  135. (defun import-album (name dest paths)
  136. (let (added-photos
  137. (files (remove-if-not #'(lambda (p) (uiop:subpathp p *incoming-path*))
  138. (mapcar #'probe-file paths))))
  139. (when files
  140. (with-db (db)
  141. (sqlite:with-transaction db
  142. (labels ((handle-moved (path)
  143. (let ((info (load-photo-info path)))
  144. (push (cons (db/add-photo db info) (aget :name info)) added-photos)
  145. (log:info "Moved" (aget :path info)))))
  146. (move-images-with-folders files dest #'handle-moved)
  147. (let ((album-id (db/add-album db name nil (car (middle added-photos)))))
  148. (loop for (photo-id . name) in (reverse added-photos)
  149. for idx from 1
  150. do (db/add-album-photo db album-id photo-id name idx))
  151. album-id)))))))
  152. (restas:define-route main ("")
  153. (asdf:system-relative-pathname :photo-store "index.html"))
  154. (restas:define-route incoming ("incoming/")
  155. (asdf:system-relative-pathname :photo-store "incoming.html"))
  156. ;; Assets file path
  157. (defparameter *assets-path*
  158. (asdf:system-relative-pathname :photo-store "assets/"))
  159. (restas:define-route assets/css ("css/:file" :content-type "text/css")
  160. (merge-pathnames file *assets-path*))
  161. (restas:define-route assets/js ("js/:file" :content-type "application/x-javascript")
  162. (merge-pathnames file *assets-path*))
  163. (defun json (object)
  164. (json:encode-json-to-string object))
  165. (defvar *incoming-path* nil "Path for incoming photos")
  166. (restas:define-route api/incoming ("api/incoming/"
  167. :content-type "application/json")
  168. (json (fs-load-albums *incoming-path*)))
  169. (restas:define-route api/incoming-import ("api/incoming/import/"
  170. :method :post
  171. :content-type "application/json")
  172. (let* ((album (json:decode-json-from-string (hunchentoot:raw-post-data :external-format :utf-8)))
  173. (name (aget :name album))
  174. (dest (aget :dest album))
  175. (paths (aget :paths album)))
  176. (if (uiop:relative-pathname-p dest)
  177. (let ((new-id (import-album name (uiop:merge-pathnames* dest *photo-storage-path*) paths)))
  178. (json (db-load-album new-id)))
  179. 400)))
  180. (restas:define-route api/albums ("api/albums/"
  181. :content-type "application/json")
  182. (json (db-load-albums)))
  183. (restas:define-route api/album ("api/albums/:album-id/"
  184. :content-type "application/json")
  185. (:sift-variables (album-id 'integer))
  186. (json (db-load-album album-id)))
  187. (defvar *photo-storage-path* nil "Destination storage path")
  188. (defun start (&key (address "0.0.0.0") (port 8800))
  189. (restas:start '#:photo-store :address address :port port))