Skip to content

Instantly share code, notes, and snippets.

@Em-AK
Created February 24, 2021 16:29
Show Gist options
  • Save Em-AK/f195602db6722212f217b2fd4d4febd5 to your computer and use it in GitHub Desktop.
Save Em-AK/f195602db6722212f217b2fd4d4febd5 to your computer and use it in GitHub Desktop.
Get an alert when the bike is in stock with Babashka
#!/usr/bin/env bb
(require
'[babashka.pods :as pods]
'[babashka.curl :as curl]
'[cheshire.core :as json]
'[clojure.java.shell :refer [sh]])
(pods/load-pod 'retrogradeorbit/bootleg "0.1.9")
(require
'[pod.retrogradeorbit.bootleg.utils :as utils]
'[pod.retrogradeorbit.hickory.select :as s])
(def models
[{:name "GRVL-120 L"
:url "https://www.decathlon.fr/p/velo-gravel-triban-grvl-120/_/R-p-312397"
:sku "2962860"}
{:name "GRVL-RC520 L"
:url "https://www.decathlon.fr/p/velo-gravel-triban-rc520-gravel/_/R-p-302303"
:sku "2471309"}])
(defn in-stock? [s]
(= s "http://schema.org/InStock"))
(defn notify [message]
(sh "/usr/bin/notify-send" (str message)))
(defn check-stock [model]
(let [response (curl/get (:url model))]
(if (zero? (:exit response))
(let [content-str (->> (utils/convert-to (:body response) :hickory-seq)
(filter map?)
first
(s/select
(s/and
(s/tag :script)
(s/attr :type #(= % "application/ld+json"))))
(filter #(re-find #"product" (str (:content %))))
first
:content
first)
model-in-stock? (-> content-str
(json/parse-string true)
:offers
(->> (filter #(= (:sku model) (:sku %))))
first
:availability
in-stock?)]
(println (:name model) "in stock:" model-in-stock?)
(when model-in-stock?
(notify (str (:name model) " IN STOCK!")))
model-in-stock?)
(do (println "Error:" (:err response))
(System/exit 1)))))
(doall
(for [model models]
(check-stock model)))
(System/exit 0)
# env is needed for notify-send to work when triggered from a cron job
*/5 * * * * DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus /home/emak/bin/check.clj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment