dhyan/main.clj
2022-06-18 18:26:53 +10:00

58 lines
2.4 KiB
Clojure

(ns dhynan.main
(:require [clojure.java.shell :refer [sh]]
[cheshire.core :as json]
[babashka.curl :as curl])
(:import (javax.crypto Mac)
(javax.crypto.spec SecretKeySpec)))
(defn generate-token
[api-secret]
(let [encoder (java.util.Base64/getEncoder)
header-raw (->> (json/encode {"alg" "HS512" "typ" "JWT"})
.getBytes
(.encodeToString encoder))
; TODO can't figure out how to apply this with an anon function
header (clojure.string/replace header-raw "=" "")
date (-> (sh "date" "-u" "+%s")
:out
(clojure.string/replace "\n" ""))
payload-raw (->> (json/encode {"iat" date})
.getBytes
(.encodeToString encoder))
; TODO can't figure out how to apply this with an anon function
payload (clojure.string/replace payload-raw "=" "")
algo "HmacSHA512"
mac (Mac/getInstance algo)]
(.init mac (SecretKeySpec. (.getBytes api-secret) algo))
(let [sig (->> (.doFinal mac (.getBytes (str header "." payload)))
(.encodeToString encoder))
signature (-> sig
; TODO should do url encode here
(clojure.string/replace "/" "_")
(clojure.string/replace "=" "")
(clojure.string/replace "+" "-"))]
(str header "." payload "." signature))))
(let [token (generate-token (System/getenv secret-token))
data (-> (curl/get "http://links.mossnet.lan/api/v1/links?searchtags=music" {:headers {"Authorization" (str "Bearer " token)}})
(:body)
(json/parse-string true))
; filter to bandcamp (and maybe others?)
filtered-data (mapv (filter (fn [x] (contains? "bandcamp" (get x :url)))) data)]
filtered-data)
(comment
(println "somestring")
(.getBytes (str {"iat" (sh "date" "-u" "+%s")}))
(def signature (-> (Mac/getInstance "HmacSHA256")
(.init (SecretKeySpec. (.getBytes "test secret") "HmacSHA256"))
(.doFinal (.getBytes (str "header.payload" ) "UTF-8"))))
(def sig
(let [algo "HmacSHA256"
mac (Mac/getInstance algo)]
(.init mac (SecretKeySpec. (.getBytes "test secret") algo))
(str (.doFinal mac (.getBytes "header.payload" "UTF-8")))))
(println sig)
(str {"alg" "HS512" "typ" "JWT"}))