Skip to content

Commit

Permalink
feat(http): support send to http service (default is clippingkk)
Browse files Browse the repository at this point in the history
  • Loading branch information
AnnatarHe committed Dec 22, 2021
1 parent 624ccb9 commit bc87b0d
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 23 deletions.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ download latest version from [release page](https://github.com/clippingkk/cli/re

## Usage

### Parse

```bash
ck-cli parse -i /path/to/My Clippings.txt -o /path/output.json
cat My Clippings.txt | ck-cli -o /path/output.json
Expand Down Expand Up @@ -43,6 +45,26 @@ cat ./core/clippings_en.txt | ck-cli parse | jq .[].title | sort | uniq
# "凤凰项目 一个IT运维的传奇故事"
# "论法的精神"
```
### Compose with ClippingKK Http Service

you can pass cli token to local config

```bash
ck-cli --token "COPY FROM https://clippingkk.annatarhe.com" login
cat ~/.ck-cli.toml
```

You can also just parse file and put it to server with token for once:

```bash
ck-cli parse --input /path/to/My Clippings.txt --output http
```

the `http` in `output` is magic word and it will send parsed clippings to server.

you can manually define where should it send and the http request headers by edit config in `~/.ck-cli.toml`

If you want integration with CI service, you can set config as secret. and to do something you want

## Contributing

Expand Down
43 changes: 38 additions & 5 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,60 @@ use std::fs;
use std::path::Path;
use std::path::PathBuf;

#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Clone)]
pub struct CKConfig {
pub http: Option<CKConfigHttp>,
}

#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Clone)]
pub struct CKConfigHttp {
pub endpoint: Option<String>,
pub headers: Option<HashMap<String, String>>,
}

impl CKConfig {
pub fn update_token(self, new_token: &String) -> Result<CKConfig, Box<dyn Error>> {
let http_endpoint: String;
let mut http_headers: HashMap<String, String>;

if let Some(h) = self.http {
http_endpoint = h.endpoint.unwrap_or(CK_ENDPOINT.to_string());
http_headers = h.headers.unwrap_or(HashMap::new());
} else {
http_endpoint = CK_ENDPOINT.to_string();
http_headers = HashMap::new();
}

let mut token_val = String::from("X-CLI ");
token_val.push_str(new_token);

http_headers.insert(String::from("Authorization"), token_val.clone());

let new_config = CKConfig {
http: Some(CKConfigHttp {
endpoint: Some(http_endpoint),
headers: Some(http_headers),
}),
};

Ok(new_config)
}

pub fn save(self, file_path: &Path) -> Result<CKConfig, Box<dyn Error>> {
let empty_data = toml::to_string(&self)?;
fs::write(file_path, empty_data)?;
Ok(self)
}
}

fn create_empty_config(file_path: &Path) -> Result<CKConfig, Box<dyn Error>> {
let empty_config = CKConfig {
http: Some(CKConfigHttp {
endpoint: Some(CK_ENDPOINT.to_string()),
headers: None,
}),
};
let empty_data = toml::to_string(&empty_config)?;
fs::write(file_path, empty_data)?;
Ok(empty_config)
empty_config.save(file_path)
}

pub fn ensure_toml_config(config_path: &String) -> Result<CKConfig, Box<dyn Error>> {
Expand Down
3 changes: 2 additions & 1 deletion src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@ pub async fn sync_to_server(
.json(&payload)
.send()
.await?;
resp.text().await
let r = resp.error_for_status()?;
r.text().await
})
})
.buffer_unordered(PARALLEL_REQUESTS);
Expand Down
42 changes: 25 additions & 17 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ use std::io::prelude::*;
use std::process;
use tokio;
use tokio::signal;
mod auth;
mod config;
mod constants;
mod graphql;
mod http;
mod parser;
mod auth;

#[derive(Subcommand)]
enum Commands {
Expand All @@ -35,32 +35,40 @@ enum Commands {
struct CliCommands {
#[clap(short = 'c', long, default_value = "")]
config: String,
#[clap(short = 't', long, default_value = "")]
token: String,
#[clap(subcommand)]
command: Commands,
}

async fn main_fn() -> Result<(), Box<dyn std::error::Error>> {
let args = CliCommands::parse();
let ck_config = ensure_toml_config(&args.config)?;
let mut ck_config = ensure_toml_config(&args.config)?;
let mut p = dirs::home_dir().unwrap();
p.push(".ck-cli.toml");

match &args.command {
Commands::Login {} => {
// TODO: interactive
// 1: phone number / email
let auth_prompt_data = get_auth_from_prompt()?;
// 2: image verification
// 3: sms code check
// 4: receive auth response
// 5: save to local config
blue_ln!(" 💪 working on it")
if args.token.is_empty() {
e_red_ln!(" ❌ token not found \n visit https://clippingkk.annatarhe.com and login \n then navigate to your profile page and open `API Token` dialog. \n Copy it and paste to this cli.");
process::exit(255);
}
ck_config = ck_config.update_token(&args.token)?;
ck_config.save(&p.clone())?;

green_ln!(" ✅ logged. you can synchronize your `My Clippings.txt` by run command \n $ ck-cli parse --input /path/to/My Clippings.txt --output http")
}
Commands::Parse {
input,
output,
} => {
let mut input_data: String = String::new();
Commands::Parse { input, output } => {
let ckc = ck_config.clone();
let mut ckh = ckc.http.clone();
if !args.token.is_empty() {
ck_config = ck_config.update_token(&args.token)?;
let nc = ck_config.save(&p.clone())?;
ckh = nc.http;
}

if !input.eq("") {
let mut input_data: String = String::new();
if !input.is_empty() {
input_data = std::fs::read_to_string(input)?;
} else {
io::stdin().read_to_string(&mut input_data)?;
Expand All @@ -81,7 +89,7 @@ async fn main_fn() -> Result<(), Box<dyn std::error::Error>> {
if output.is_empty() {
io::stdout().write(out.as_bytes())?;
} else if output.starts_with("http") {
http::sync_to_server(&output, &ck_config.http, &result_obj).await?;
http::sync_to_server(&output, &ckh, &result_obj).await?;
} else {
std::fs::write(output, out)?;
}
Expand Down

0 comments on commit bc87b0d

Please sign in to comment.