Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New compiled CLI tools + Clojure version #7

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
target/
.cpcache/
.nrepl-port
.DS_Store
out/
8 changes: 8 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright © 2023 <copyright holders>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 changes: 35 additions & 0 deletions README.org
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,42 @@

There is at least two versions of the backup format. I haven't invested in figuring out a detection mechanism so trial and error is the game :)

* New Version
Based on the original version, we have prepared a new version of the tool, that does all the decryption, decoding and saving to JSON, EDN or Markdown a breeze. Here's the CLI interface:

[[file:/img/cli.png]]

** Basic Use Cases
*** Export to a Markdown Folder
This will export your backed up notes into a folder, with each note being a separate Markdown file, ready to add to any proper notes program like Obsidian etc:

: java -jar decryptor.jar YOUR_BACKUP_FILE -f markdown -t output

You'll find your markdown in ~output/~ directory.

*** Export to JSON
Exports your notes to a json file for further processing:

: java -jar decryptor.jar YOUR_BACKUP_FILE -f json -t notes.json

*** Export to EDN
Exports your notes to a json file for further processing:

: java -jar decryptor.jar YOUR_BACKUP_FILE -f edn -t notes.edn

*** Print json (for piping or testing)
This is a default option, so all you need to do is:

: java -jar decryptor.jar YOUR_BACKUP_FILE

*** Only decrypt
This is the basic operation, in case our parsing doesn't work in some cases. You can pipe it to the scripts mentioned below or do your own thing with it:

: java -jar decryptor.jar YOUR_BACKUP_FILE -f decrypt

* Original Version
*** Usage
The old verision jar ca n be found in ~lib/~ and used as described.
: java -jar colornote-decrypt.jar PASSWORD OFFSET < INPUT_FILE > OUTPUT_FILE

If you use oracle's JRE (likely the case if you're on windows) you'll need to run the class file directly instead (send your thanks to the US for their silly encryption export restrictions... and to java for making it unbelivable hard to make a properly bundled program):
Expand Down
25 changes: 25 additions & 0 deletions build.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
(ns build
(:require [clojure.tools.build.api :as b]))

(def lib 'color-note-decryptor/decryptor)
(def version "1.0.0")
(def class-dir "target/classes")
(def basis (b/create-basis {:project "deps.edn"}))
(def jar-file (format "target/%s.jar" (name lib)))

(defn clean [_]
(b/delete {:path "target"}))

(defn uber [_]
(clean nil)
(b/copy-dir {:src-dirs ["src"]
:target-dir class-dir})
(b/compile-clj {:basis basis
:src-dirs ["src"]
:class-dir class-dir})
(b/uber {:class-dir class-dir
:uber-file jar-file
:basis basis
:main 'color-note-decryptor.decryptor}))


Binary file added decryptor.jar
Binary file not shown.
7 changes: 7 additions & 0 deletions deps.edn
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{:paths ["src"]
:deps {cheshire/cheshire {:mvn/version "5.11.0"}
org.clojure/tools.cli {:mvn/version "1.0.219"}
babashka/fs {:mvn/version "0.4.19"}
colornote-decrypt/colornote-decrypt {:local/root "lib/colornote-decrypt.jar"}}
:aliases {:build {:deps {io.github.clojure/tools.build {:git/tag "v0.9.4" :git/sha "76b78fe"}}
:ns-default build}}}
Binary file added img/cli.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
File renamed without changes.
217 changes: 217 additions & 0 deletions src/color_note_decryptor/decryptor.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
(ns color-note-decryptor.decryptor
(:gen-class)
(:require
[babashka.fs :as fs]
[cheshire.core :as json]
[clojure.string :as str]
[clojure.tools.cli :refer [parse-opts]])
(:import
ColorNoteBackupDecrypt
(java.io
ByteArrayOutputStream
FileInputStream)
(java.security
Security)
(org.bouncycastle.jce.provider
BouncyCastleProvider)))


(defn decrypt
"Runs the original decryptor from BouncyCastleProvider"
[{:keys [file offset password] :or {offset 28 password "0000"}}]
(println (format "Decrypting using password %s and offset %s..." password offset))
(Security/addProvider (BouncyCastleProvider.))
(let [instance (doto (ColorNoteBackupDecrypt.) (.init password))]
(with-open [raw-input (FileInputStream. file)
out-stream (ByteArrayOutputStream.)]
(.decrypt instance raw-input offset out-stream)
(-> out-stream .toString))))


(defn fixup
"Convert the output of decrypt to a vector of maps."
[s]
(let [pattern (re-pattern "\\{[^\\{\\}]*?\\}")]
(->> s
(re-seq pattern)
(mapv #(json/parse-string % keyword)))))


(defn ->edn
"Decrypt file, fixup and return as edn."
[opts]
(->> opts
decrypt
fixup))


(defn ->edn-file
[{:keys [target] :as opts}]
(->> opts
->edn
(spit target)))


(defn ->json
"Decrypt file, fixup and return as json string."
[opts]
(->> opts
->edn
json/encode))


(defn ->json-file
"Decrypt file and save as json under out-file."
[{:keys [target] :as opts}]
(->> opts
->json
(spit target)))


(defn make-front-matter
"Make YAML front-matter for markdown file."
[note]
(format "---\n%s---\n\n"
(str/join
(for [[k v] note
:when (not= "" v)]
(str (name k) ": " v "\n")))))


(defn fixup-note
"Fixup not map before saving to markdown. Removes extra keys, converts created dated to ISO."
[note]
(-> note
(select-keys [:title :created_date :tags])
(update :created_date #(str (java.time.Instant/ofEpochMilli %)))))


(defn note->md
"Convert one not map from fixup to markdown map with keys :filename and :text"
[note]
(let [fixed (fixup-note note)]
{:filename (str (:title note) ".md")
:text (str (make-front-matter fixed) (:note note))}))


(defn ->markdown
"Decrypt file, fixup and save all notes as separate markdown files under out-folder. Creates folder if it doesn't exist."
[{:keys [target] :as opts}]
(let [notes (->edn opts)
md-notes (map note->md notes)
cwd (fs/cwd)
out (str cwd "/" target)]
(when-not (fs/directory? out)
(fs/create-dir out))
(doseq [{:keys [filename text]} md-notes]
(spit (str out "/" (str/replace filename "/" "-")) text))))


(def allowed-formats #{:json :markdown :edn :decrypt})


(defmulti process (fn [{:keys [fmt target]}]
(let [res (cond
(empty? target) [:print fmt]
:else [:save fmt])]
(println res)
res) ))


(defmethod process [:print :json] [opts]
(-> opts ->json println))


(defmethod process [:print :edn] [opts]
(-> opts ->edn println))


(defmethod process [:save :json] [{:keys [target] :as opts}]
(->json-file opts)
(println target))


(defmethod process [:save :edn] [{:keys [target] :as opts}]
(->edn-file opts)
(println target))


(defmethod process [:save :markdown] [{:keys [target] :as opts}]
(->markdown opts)
(println target))

(defmethod process [:print :decrypt] [opts]
(-> opts decrypt println))

(defmethod process [:save :decrypt] [{:keys [target] :as opts}]
(->> opts decrypt (spit target))
(println target))


(def cli-opts
[["-f" "--format FORMAT" "Output format, defaults to json"
:id :fmt
:default :json
:validate [#(allowed-formats %) (str "Must be one of: " (str/join ", " allowed-formats))]
:parse-fn keyword]
["-t" "--target TARGET" "Output file (for json and edn) or folder"
:id :target]
["-p" "--password PASSWORD" "Optonal. A password to use for decryption, defaults to \"0000\""
:id :password
:default "0000"]
["-o" "--offset OFFSET" "Optional. Offset to use for decryption, defaults to 28"
:id :offset
:default 28
:parse-fn parse-long]])


(defn prepare-options
[& args]
(let [parsed (parse-opts args cli-opts)
{:keys [arguments options]} parsed
{:keys [fmt target offset password]} options
prepped {:file (first arguments)
:fmt fmt
:target target
:offset offset
:password password}]
(cond
(and (empty? arguments) (empty? target) (empty? fmt)) (assoc prepped :err :help)
(empty? arguments) (assoc prepped :err "No Color Notes backup file specified")
(and (= fmt :markdown) (nil? target)) (assoc prepped :err "You must specify a --target folder to save markdown files to.")
:else prepped)))

(def help-message "Decrypts Color Notes backup into either a json, edn or a folder with markdown files (one file for each note).

Basic usage (will print the decrypted json):
decryptor mynotes.backup

Available options:
--format -f - specify output format [json, edn, markdown, decrypt]
--targret -t - specify the output file (or folder if format is markdown)
--password -p - A password to use for decryption, defaults to \"0000\"
--offset -o - Offset to use for decryption, defaults to 28 ")

(defn help []
(println help-message))

(defn process-errors
[{:keys [err]}]
(when err
(if (= :help err) (help)
(println err))
(System/exit 1)))


(defn -main
[& args]
(when (empty? args)
(help)
(System/exit 0))
(let [options (apply prepare-options args)]
(process-errors options)
(process options)))