Skip to content

Instantly share code, notes, and snippets.

@anolivetree
Created February 21, 2018 03:24
Show Gist options
  • Save anolivetree/e176a5d0c0f2add2d07814c675c95f0d to your computer and use it in GitHub Desktop.
Save anolivetree/e176a5d0c0f2add2d07814c675c95f0d to your computer and use it in GitHub Desktop.
kibelaに投稿するプログラム
; 使い方
; (def session (make-session))
; (signin session "チーム名" "ユーザー名" "パスワード") ; チーム名は、xxx.kibe.laのxxxの部分
; (post-wiki session "タイトル" "中身" "カテゴリ")
(ns kibela.core
(:require [net.cgrand.enlive-html :as html])
(:require [clj-http.cookies])
(:require [clj-http.client :as http])
(:import java.net.URL)
(:require [clojure.data.json :as json])
)
(defn signin-url [team-name] (str "https://" team-name ".kibe.la/signin"))
(defn new-wiki-url [team-name] (str "https://" team-name ".kibe.la/wikis/new"))
(defn post-wiki-url [team-name] (str "https://" team-name ".kibe.la/wikis"))
(defn origin-url [team-name] (str "https://" team-name ".kibe.la"))
(defn make-session []
(atom {:cookie-store (clj-http.cookies/cookie-store)
:team-name nil}))
(defn- assoc-email-pass [m user pass]
(-> m
(assoc "user[email]" user)
(assoc "user[password]" pass)))
(defn signin [s team-name user password]
(let [resp (http/get (signin-url team-name) {:cookie-store (:cookie-store @s)})
res (html/html-snippet (:body resp))
inputs (html/select res [:form :input])
formvalues (into {} (map (fn [m] (let [attr (:attrs m)]
(vector (:name attr) (:value attr)))) inputs))
form-params (assoc-email-pass formvalues
user
password)]
(reset! s (assoc @s :team-name team-name))
;(println formvalues)
;(println form-params)
;(println (:team-name @s))
;(println (:cookie-store @s))
(http/post (signin-url team-name)
{:form-params form-params
:cookie-policy :standard
:cookie-store (:cookie-store @s)})))
;; wiki生成用のjsonを返す。categoryが無い場合は、""またはnilを指定。
(defn create-wiki-json [title content category]
(let [cat
(if (seq category)
[{:name category :id 0}] ; id:0にすると、無い場合は自動生成される
[])]
(json/write-str {:wiki {:title title :content content :board_ids [1] :categories cat}})))
(defn post-wiki [s title content category]
(let [;; wikiの新規作成ページにアクセスして、CSRF-Tokenを取得する。
resp (http/get (new-wiki-url (:team-name @s))
{
:cookie-policy :standard
:cookie-store (:cookie-store @s)})
metas (html/html-snippet (resp :body))
csrf-token (get-in (first (html/select metas [[:meta (html/attr= :name "csrf-token")]])) [:attrs :content])
json (create-wiki-json title content category)
]
(http/post (post-wiki-url (:team-name @s))
{:cookie-store (:cookie-store @s)
:headers {"X-Requested-With" "XMLHttpRequest"
"Origin" (origin-url (:team-name @s))
"X-CSRF-Token" csrf-token}
:content-type :json
:accept :json
:body json})))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment