foursquare.lisp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. (in-package :cl-user)
  2. (defpackage #:timeliner.foursquare
  3. (:use :cl #:timeliner.utils :cl-mongo)
  4. (:export
  5. #:*access-token*
  6. #:on-cron))
  7. (in-package #:timeliner.foursquare)
  8. (defvar *access-token*)
  9. (defun make-checkin-doc (checkin)
  10. (let* ((venue (gethash "venue" checkin))
  11. (location (and venue (gethash "location" venue))))
  12. (when venue
  13. (kv
  14. (kv :ts (local-time:unix-to-timestamp (gethash "createdAt" checkin)))
  15. (kv :type "checkin")
  16. (kv :title (format nil "~A~:[~;~:* (~A)~]~:[~;~:*: ~A~]"
  17. (gethash "name" venue)
  18. (gethash "address" location)
  19. (gethash "shout" checkin)))
  20. (kv :loc (kv (kv :type "Point") ; GeoJSON Point
  21. (kv :coordinates (list
  22. (gethash "lng" location)
  23. (gethash "lat" location)))))))))
  24. (defun load-checkins (from)
  25. (let ((checkins
  26. (gethash
  27. "checkins"
  28. (gethash
  29. "response"
  30. (yason:parse
  31. (flexi-streams:octets-to-string
  32. (drakma:http-request
  33. "https://api.foursquare.com/v2/users/self/checkins"
  34. :parameters
  35. (list
  36. (cons "oauth_token" *access-token*)
  37. (cons "limit" "250")
  38. (cons "sort" "oldestfirst")
  39. (cons "afterTimestamp" (if from
  40. (princ-to-string (1+ (local-time:timestamp-to-unix from)))
  41. "0"))
  42. (cons "v" "20140704")))
  43. :external-format :utf-8))))))
  44. (when checkins
  45. (loop for item in (gethash "items" checkins)
  46. for doc = (make-checkin-doc item)
  47. when doc collect doc))))
  48. (defun on-cron ()
  49. (handler-case
  50. (let* ((last-checkin (first (docs (db.sort "events" ($ "type" "checkin") :field "ts"
  51. :asc nil :limit 1))))
  52. (from (and last-checkin (ms->ts (cl-mongo::raw (get-element "ts" last-checkin)))))
  53. (checkins (load-checkins from)))
  54. (log:info "Got ~A checkins from ~A~%" (length checkins) from)
  55. (save-events checkins))
  56. (error (e) (log:error e))))