From 1dbab207ece88a47f92b951a83ef8d95dc40fe1c Mon Sep 17 00:00:00 2001 From: Ferris Tseng Date: Tue, 23 Feb 2021 23:26:48 -0500 Subject: migrate examples to separate crate --- ipfs-api-examples/Cargo.toml | 28 ++++++ ipfs-api-examples/examples/add_file.rs | 28 ++++++ ipfs-api-examples/examples/add_tar.rs | 69 ++++++++++++++ ipfs-api-examples/examples/bootstrap_default.rs | 62 ++++++++++++ ipfs-api-examples/examples/config.rs | 69 ++++++++++++++ ipfs-api-examples/examples/dag.rs | 46 +++++++++ ipfs-api-examples/examples/default_config.json | 121 ++++++++++++++++++++++++ ipfs-api-examples/examples/dns.rs | 43 +++++++++ ipfs-api-examples/examples/get_commands.rs | 47 +++++++++ ipfs-api-examples/examples/get_stats.rs | 63 ++++++++++++ ipfs-api-examples/examples/get_swarm.rs | 48 ++++++++++ ipfs-api-examples/examples/get_version.rs | 25 +++++ ipfs-api-examples/examples/log_tail.rs | 33 +++++++ ipfs-api-examples/examples/mfs.rs | 88 +++++++++++++++++ ipfs-api-examples/examples/ping_peer.rs | 70 ++++++++++++++ ipfs-api-examples/examples/pubsub.rs | 84 ++++++++++++++++ ipfs-api-examples/examples/replace_config.rs | 28 ++++++ ipfs-api-examples/examples/resolve_name.rs | 51 ++++++++++ ipfs-api-examples/src/lib.rs | 25 +++++ 19 files changed, 1028 insertions(+) create mode 100644 ipfs-api-examples/Cargo.toml create mode 100644 ipfs-api-examples/examples/add_file.rs create mode 100644 ipfs-api-examples/examples/add_tar.rs create mode 100644 ipfs-api-examples/examples/bootstrap_default.rs create mode 100644 ipfs-api-examples/examples/config.rs create mode 100644 ipfs-api-examples/examples/dag.rs create mode 100644 ipfs-api-examples/examples/default_config.json create mode 100644 ipfs-api-examples/examples/dns.rs create mode 100644 ipfs-api-examples/examples/get_commands.rs create mode 100644 ipfs-api-examples/examples/get_stats.rs create mode 100644 ipfs-api-examples/examples/get_swarm.rs create mode 100644 ipfs-api-examples/examples/get_version.rs create mode 100644 ipfs-api-examples/examples/log_tail.rs create mode 100644 ipfs-api-examples/examples/mfs.rs create mode 100644 ipfs-api-examples/examples/ping_peer.rs create mode 100644 ipfs-api-examples/examples/pubsub.rs create mode 100644 ipfs-api-examples/examples/replace_config.rs create mode 100644 ipfs-api-examples/examples/resolve_name.rs create mode 100644 ipfs-api-examples/src/lib.rs (limited to 'ipfs-api-examples') diff --git a/ipfs-api-examples/Cargo.toml b/ipfs-api-examples/Cargo.toml new file mode 100644 index 0000000..531dc53 --- /dev/null +++ b/ipfs-api-examples/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "ipfs-api-examples" +description = "Examples for IPFS HTTP API clients" +authors = ["Ferris Tseng "] +edition = "2018" +documentation = "https://docs.rs/ipfs-api" +repository = "https://github.com/ferristseng/rust-ipfs-api" +keywords = ["ipfs"] +categories = ["filesystem", "web-programming"] +version = "0.1.0" +readme = "../README.md" +license = "MIT OR Apache-2.0" + +[features] +default = ["with-hyper"] +with-hyper = ["ipfs-api-backend-hyper", "tokio-hyper", "tokio-hyper/macros", "tokio-hyper/rt-multi-thread"] +with-actix = ["ipfs-api-backend-actix", "tokio-actix", "actix-rt"] + +[dependencies] +actix-rt = { version = "1.1", optional = true } +futures = "0.3" +ipfs-api-backend-actix = { version = "0.1", path = "../ipfs-api-backend-actix", optional = true } +ipfs-api-backend-hyper = { version = "0.1", path = "../ipfs-api-backend-hyper", optional = true } +tar = "0.4" +tokio-actix = { package = "tokio", version = "1.0", features = ["time"], optional = true } +tokio-hyper = { package = "tokio", version = "1.2", features = ["time"], optional = true } +tokio-stream = { version = "0.1", features = ["time"] } +tracing-subscriber = { version = "0.2", features = ["fmt"] } diff --git a/ipfs-api-examples/examples/add_file.rs b/ipfs-api-examples/examples/add_file.rs new file mode 100644 index 0000000..fc0ab1e --- /dev/null +++ b/ipfs-api-examples/examples/add_file.rs @@ -0,0 +1,28 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use ipfs_api_examples::ipfs_api::{IpfsApi, IpfsClient}; +use std::fs::File; + +// Creates an Ipfs client, and adds this source file to Ipfs. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("note: this must be run in the root of the project repository"); + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + let file = File::open(file!()).expect("could not read source file"); + + match client.add(file).await { + Ok(file) => eprintln!("added file: {:?}", file), + Err(e) => eprintln!("error adding file: {}", e), + } +} diff --git a/ipfs-api-examples/examples/add_tar.rs b/ipfs-api-examples/examples/add_tar.rs new file mode 100644 index 0000000..0098ded --- /dev/null +++ b/ipfs-api-examples/examples/add_tar.rs @@ -0,0 +1,69 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use futures::TryStreamExt; +use ipfs_api_examples::ipfs_api::{IpfsApi, IpfsClient}; +use std::io::Cursor; +use tar::Builder; + +// Creates an Ipfs client, and adds this source file to Ipfs. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("note: this must be run in the root of the project repository"); + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + + // Create a in-memory tar file with this source file as its contents. + // + let mut buf = Vec::new(); + { + let mut builder = Builder::new(&mut buf); + + builder + .append_path(file!()) + .expect("failed to create tar file"); + builder.finish().expect("failed to create tar file"); + } + let cursor = Cursor::new(buf); + + // Write in-memory tar file to IPFS. + // + let file = match client.tar_add(cursor).await { + Ok(file) => { + eprintln!("added tar file: {:?}", file); + eprintln!(); + + file + } + Err(e) => { + eprintln!("error writing tar file: {}", e); + + return; + } + }; + + // Read tar file from IPFS. + // + match client + .tar_cat(&file.hash[..]) + .map_ok(|chunk| chunk.to_vec()) + .try_concat() + .await + { + Ok(tar) => { + println!("{}", String::from_utf8_lossy(&tar[..])); + } + Err(e) => { + eprintln!("error reading tar file: {}", e); + } + } +} diff --git a/ipfs-api-examples/examples/bootstrap_default.rs b/ipfs-api-examples/examples/bootstrap_default.rs new file mode 100644 index 0000000..f4d83fb --- /dev/null +++ b/ipfs-api-examples/examples/bootstrap_default.rs @@ -0,0 +1,62 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use ipfs_api_examples::ipfs_api::{IpfsApi, IpfsClient}; + +// Lists clients in bootstrap list, then adds the default list, then removes +// them, and readds them. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + + match client.bootstrap_list().await { + Ok(bootstrap) => { + eprintln!("current bootstrap peers:"); + for peer in bootstrap.peers { + eprintln!(" {}", peer); + } + eprintln!(); + } + Err(e) => { + eprintln!("error getting list of bootstrap peers: {}", e); + return; + } + } + + match client.bootstrap_rm_all().await { + Ok(drop) => { + eprintln!("dropped:"); + for peer in drop.peers { + eprintln!(" {}", peer); + } + eprintln!(); + } + Err(e) => { + eprintln!("error dropping bootstrap peers: {}", e); + return; + } + } + + match client.bootstrap_add_default().await { + Ok(add) => { + eprintln!("added:"); + for peer in add.peers { + eprintln!(" {}", peer); + } + eprintln!(); + } + Err(e) => { + eprintln!("error adding default peers: {}", e); + } + } +} diff --git a/ipfs-api-examples/examples/config.rs b/ipfs-api-examples/examples/config.rs new file mode 100644 index 0000000..a927a58 --- /dev/null +++ b/ipfs-api-examples/examples/config.rs @@ -0,0 +1,69 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use ipfs_api_examples::ipfs_api::{IpfsApi, IpfsClient}; + +// Creates an Ipfs client, read & set config values. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("note: this must be run in the root of the project repository"); + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + + //read a string + let response = client + .config_get_string("Identity.PeerID") + .await + .expect("Config read failed"); + + println!("Config: {}={}", response.key, response.value); + + //read a bool + let response = client + .config_get_bool("Datastore.HashOnRead") + .await + .expect("Config read failed"); + + println!("Config: {}={}", response.key, response.value); + + //read a stringified json + let response = client + .config_get_json("Mounts") + .await + .expect("Config read failed"); + + println!("Config: {}={}", response.key, response.value); + + //set a string value + let response = client + .config_set_string("Routing.Type", "dht") + .await + .expect("Config write failed"); + + println!("Config: {}={}", response.key, response.value); + + //set a boolean value + let response = client + .config_set_bool("Pubsub.DisableSigning", false) + .await + .expect("Config write failed"); + + println!("Config: {}={}", response.key, response.value); + + //set a json value + let response = client + .config_set_json("Discovery", r#"{"MDNS":{"Enabled":true,"Interval":10}}"#) + .await + .expect("Config write failed"); + + println!("Config: {}={}", response.key, response.value); +} diff --git a/ipfs-api-examples/examples/dag.rs b/ipfs-api-examples/examples/dag.rs new file mode 100644 index 0000000..be04cb9 --- /dev/null +++ b/ipfs-api-examples/examples/dag.rs @@ -0,0 +1,46 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use futures::TryStreamExt; +use ipfs_api_examples::ipfs_api::{IpfsApi, IpfsClient}; +use std::io::Cursor; + +// Creates an Ipfs client, and adds this dag object to Ipfs then fetch it back. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("note: this must be run in the root of the project repository"); + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + + let dag_node = Cursor::new(r#"{"hello":"world"}"#); + + let response = client + .dag_put(dag_node) + .await + .expect("error adding dag node"); + + let cid = response.cid.cid_string; + + match client + .dag_get(&cid) + .map_ok(|chunk| chunk.to_vec()) + .try_concat() + .await + { + Ok(bytes) => { + println!("{}", String::from_utf8_lossy(&bytes[..])); + } + Err(e) => { + eprintln!("error reading dag node: {}", e); + } + } +} diff --git a/ipfs-api-examples/examples/default_config.json b/ipfs-api-examples/examples/default_config.json new file mode 100644 index 0000000..89a87f4 --- /dev/null +++ b/ipfs-api-examples/examples/default_config.json @@ -0,0 +1,121 @@ +{ + "Identity": { + "PeerID": "QmVRF8ZnT1ootg5vSrzS4ws8W8NwzF5q5MUCzfNK6ZmYeH" + }, + "Datastore": { + "StorageMax": "10GB", + "StorageGCWatermark": 90, + "GCPeriod": "1h", + "Spec": { + "mounts": [ + { + "child": { + "path": "blocks", + "shardFunc": "/repo/flatfs/shard/v1/next-to-last/2", + "sync": true, + "type": "flatfs" + }, + "mountpoint": "/blocks", + "prefix": "flatfs.datastore", + "type": "measure" + }, + { + "child": { + "compression": "none", + "path": "datastore", + "type": "levelds" + }, + "mountpoint": "/", + "prefix": "leveldb.datastore", + "type": "measure" + } + ], + "type": "mount" + }, + "HashOnRead": false, + "BloomFilterSize": 0 + }, + "Addresses": { + "Swarm": [ + "/ip4/0.0.0.0/tcp/4001", + "/ip6/::/tcp/4001" + ], + "Announce": [], + "NoAnnounce": [], + "API": "/ip4/127.0.0.1/tcp/5001", + "Gateway": "/ip4/127.0.0.1/tcp/8080" + }, + "Mounts": { + "IPFS": "/ipfs", + "IPNS": "/ipns", + "FuseAllowOther": false + }, + "Discovery": { + "MDNS": { + "Enabled": true, + "Interval": 10 + } + }, + "Ipns": { + "RepublishPeriod": "", + "RecordLifetime": "", + "ResolveCacheSize": 128 + }, + "Bootstrap": [ + "/dnsaddr/bootstrap.libp2p.io/ipfs/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN", + "/dnsaddr/bootstrap.libp2p.io/ipfs/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa", + "/dnsaddr/bootstrap.libp2p.io/ipfs/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb", + "/dnsaddr/bootstrap.libp2p.io/ipfs/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt", + "/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ", + "/ip4/104.236.179.241/tcp/4001/ipfs/QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM", + "/ip4/128.199.219.111/tcp/4001/ipfs/QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu", + "/ip4/104.236.76.40/tcp/4001/ipfs/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64", + "/ip4/178.62.158.247/tcp/4001/ipfs/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd", + "/ip6/2604:a880:1:20::203:d001/tcp/4001/ipfs/QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM", + "/ip6/2400:6180:0:d0::151:6001/tcp/4001/ipfs/QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu", + "/ip6/2604:a880:800:10::4a:5001/tcp/4001/ipfs/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64", + "/ip6/2a03:b0c0:0:1010::23:1001/tcp/4001/ipfs/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd" + ], + "Gateway": { + "HTTPHeaders": { + "Access-Control-Allow-Headers": [ + "X-Requested-With", + "Range" + ], + "Access-Control-Allow-Methods": [ + "GET" + ], + "Access-Control-Allow-Origin": [ + "*" + ] + }, + "RootRedirect": "", + "Writable": false, + "PathPrefixes": [] + }, + "API": { + "HTTPHeaders": null + }, + "Swarm": { + "AddrFilters": null, + "DisableBandwidthMetrics": false, + "DisableNatPortMap": false, + "DisableRelay": false, + "EnableRelayHop": false, + "ConnMgr": { + "Type": "basic", + "LowWater": 600, + "HighWater": 900, + "GracePeriod": "20s" + } + }, + "Reprovider": { + "Interval": "12h", + "Strategy": "all" + }, + "Experimental": { + "FilestoreEnabled": false, + "ShardingEnabled": false, + "Libp2pStreamMounting": false + } +} diff --git a/ipfs-api-examples/examples/dns.rs b/ipfs-api-examples/examples/dns.rs new file mode 100644 index 0000000..ea2cf8d --- /dev/null +++ b/ipfs-api-examples/examples/dns.rs @@ -0,0 +1,43 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use ipfs_api_examples::ipfs_api::{IpfsApi, IpfsClient}; + +// Creates an Ipfs client, resolves ipfs.io, and lists the contents of it. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + + let dns = match client.dns("ipfs.io", true).await { + Ok(dns) => { + eprintln!("dns resolves to ({})", &dns.path); + eprintln!(); + + dns + } + Err(e) => { + eprintln!("error resolving dns: {}", e); + return; + } + }; + + match client.object_get(&dns.path[..]).await { + Ok(contents) => { + eprintln!("found contents:"); + for link in contents.links.iter() { + eprintln!("[{}] ({} bytes)", link.name, link.size); + } + } + Err(e) => eprintln!("error listing path: {}", e), + } +} diff --git a/ipfs-api-examples/examples/get_commands.rs b/ipfs-api-examples/examples/get_commands.rs new file mode 100644 index 0000000..ea5d350 --- /dev/null +++ b/ipfs-api-examples/examples/get_commands.rs @@ -0,0 +1,47 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use ipfs_api_examples::ipfs_api::{response, IpfsApi, IpfsClient}; + +fn print_recursive(indent: usize, cmd: &response::CommandsResponse) { + let cmd_indent = " ".repeat(indent * 4); + let opt_indent = " ".repeat((indent + 1) * 4); + + eprintln!("{}[{}]", cmd_indent, cmd.name); + + if cmd.options.len() > 0 { + eprintln!("{}* options:", cmd_indent); + for options in cmd.options.iter() { + eprintln!("{}{}", opt_indent, &options.names[..].join(", ")); + } + } + + if cmd.subcommands.len() > 0 { + eprintln!("{}- subcommands:", cmd_indent); + for subcommand in cmd.subcommands.iter() { + print_recursive(indent + 1, subcommand); + } + } +} + +// Creates an Ipfs client, and gets a list of available commands from the +// Ipfs server. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + + match client.commands().await { + Ok(commands) => print_recursive(0, &commands), + Err(e) => eprintln!("error getting commands: {}", e), + } +} diff --git a/ipfs-api-examples/examples/get_stats.rs b/ipfs-api-examples/examples/get_stats.rs new file mode 100644 index 0000000..f701329 --- /dev/null +++ b/ipfs-api-examples/examples/get_stats.rs @@ -0,0 +1,63 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use ipfs_api_examples::ipfs_api::{IpfsApi, IpfsClient}; + +// Creates an Ipfs client, and gets some stats about the Ipfs server. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + + match client.stats_bitswap().await { + Ok(bitswap_stats) => { + eprintln!("bitswap stats:"); + eprintln!(" blocks recv: {}", bitswap_stats.blocks_received); + eprintln!(" data recv: {}", bitswap_stats.data_received); + eprintln!(" blocks sent: {}", bitswap_stats.blocks_sent); + eprintln!(" data sent: {}", bitswap_stats.data_sent); + eprintln!( + " peers: {}", + bitswap_stats.peers.join("\n ") + ); + eprintln!( + " wantlist: {}", + bitswap_stats.wantlist.join("\n ") + ); + eprintln!(); + } + Err(e) => eprintln!("error getting bitswap stats: {}", e), + } + + match client.stats_bw().await { + Ok(bw_stats) => { + eprintln!("bandwidth stats:"); + eprintln!(" total in: {}", bw_stats.total_in); + eprintln!(" total out: {}", bw_stats.total_out); + eprintln!(" rate in: {}", bw_stats.rate_in); + eprintln!(" rate out: {}", bw_stats.rate_out); + eprintln!(); + } + Err(e) => eprintln!("error getting bandwidth stats: {}", e), + } + + match client.stats_repo().await { + Ok(repo_stats) => { + eprintln!("repo stats:"); + eprintln!(" num objs: {}", repo_stats.num_objects); + eprintln!(" repo size: {}", repo_stats.repo_size); + eprintln!(" repo path: {}", repo_stats.repo_path); + eprintln!(" version : {}", repo_stats.version); + } + Err(e) => eprintln!("error getting repo stats: {}", e), + } +} diff --git a/ipfs-api-examples/examples/get_swarm.rs b/ipfs-api-examples/examples/get_swarm.rs new file mode 100644 index 0000000..02ea599 --- /dev/null +++ b/ipfs-api-examples/examples/get_swarm.rs @@ -0,0 +1,48 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use ipfs_api_examples::ipfs_api::{IpfsApi, IpfsClient}; + +// Creates an Ipfs client, and gets information about your local address, and +// connected peers. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + + match client.swarm_addrs_local().await { + Ok(local) => { + eprintln!("your addrs:"); + for addr in local.strings { + eprintln!(" {}", addr); + } + eprintln!(); + } + Err(e) => eprintln!("error getting local swarm addresses: {}", e), + } + + match client.swarm_peers().await { + Ok(connected) => { + eprintln!("connected:"); + for peer in connected.peers { + let streams: Vec<&str> = peer.streams.iter().map(|s| &s.protocol[..]).collect(); + eprintln!(" addr: {}", peer.addr); + eprintln!(" peer: {}", peer.peer); + eprintln!(" latency: {}", peer.latency); + eprintln!(" muxer: {}", peer.muxer); + eprintln!(" streams: {}", streams.join(", ")); + eprintln!(); + } + } + Err(e) => eprintln!("error getting swarm peers: {}", e), + } +} diff --git a/ipfs-api-examples/examples/get_version.rs b/ipfs-api-examples/examples/get_version.rs new file mode 100644 index 0000000..adc6ee0 --- /dev/null +++ b/ipfs-api-examples/examples/get_version.rs @@ -0,0 +1,25 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use ipfs_api_examples::ipfs_api::{IpfsApi, IpfsClient}; + +// Creates an Ipfs client, and gets the version of the Ipfs server. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + + match client.version().await { + Ok(version) => eprintln!("version: {:?}", version.version), + Err(e) => eprintln!("error getting version: {}", e), + } +} diff --git a/ipfs-api-examples/examples/log_tail.rs b/ipfs-api-examples/examples/log_tail.rs new file mode 100644 index 0000000..c9bf309 --- /dev/null +++ b/ipfs-api-examples/examples/log_tail.rs @@ -0,0 +1,33 @@ +// Copyright 2019 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use futures::{future, TryStreamExt}; +use ipfs_api_examples::ipfs_api::{IpfsApi, IpfsClient}; + +// Tails the log of IPFS. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + + if let Err(e) = client + .log_tail() + .try_for_each(|line| { + println!("{}", line); + + future::ok(()) + }) + .await + { + eprintln!("error getting tail of log: {}", e); + } +} diff --git a/ipfs-api-examples/examples/mfs.rs b/ipfs-api-examples/examples/mfs.rs new file mode 100644 index 0000000..e644872 --- /dev/null +++ b/ipfs-api-examples/examples/mfs.rs @@ -0,0 +1,88 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use ipfs_api_examples::ipfs_api::{response, IpfsApi, IpfsClient}; +use std::fs::File; + +fn print_stat(stat: response::FilesStatResponse) { + eprintln!(" type : {}", stat.typ); + eprintln!(" hash : {}", stat.hash); + eprintln!(" size : {}", stat.size); + eprintln!(" cum. size: {}", stat.cumulative_size); + eprintln!(" blocks : {}", stat.blocks); + eprintln!(); +} + +// Creates an Ipfs client, and makes some calls to the Mfs Api. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("note: this must be run in the root of the project repository"); + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + + eprintln!("making /test..."); + eprintln!(); + + if let Err(e) = client.files_mkdir("/test", false).await { + eprintln!("error making /test: {}", e); + return; + } + + eprintln!("making dirs /test/does/not/exist/yet..."); + eprintln!(); + + if let Err(e) = client.files_mkdir("/test/does/not/exist/yet", true).await { + eprintln!("error making /test/does/not/exist/yet: {}", e); + return; + } + + eprintln!("getting status of /test/does..."); + eprintln!(); + + match client.files_stat("/test/does").await { + Ok(stat) => print_stat(stat), + Err(e) => { + eprintln!("error getting status of /test/does: {}", e); + return; + } + } + + eprintln!("writing source file to /test/mfs.rs"); + eprintln!(); + + let src = File::open(file!()).expect("could not read source file"); + + if let Err(e) = client.files_write("/test/mfs.rs", true, true, src).await { + eprintln!("error writing source file /test/mfs.rs: {}", e); + return; + } + + eprintln!("getting status of /test/mfs.rs..."); + eprintln!(); + + match client.files_stat("/test/mfs.rs").await { + Ok(stat) => print_stat(stat), + Err(e) => { + eprintln!("error getting status of /test/mfs.rs: {}", e); + return; + } + } + + eprintln!("removing /test..."); + eprintln!(); + + if let Err(e) = client.files_rm("/test", true).await { + eprintln!("error removing /test: {}", e); + } + + eprintln!("done!"); +} diff --git a/ipfs-api-examples/examples/ping_peer.rs b/ipfs-api-examples/examples/ping_peer.rs new file mode 100644 index 0000000..5c5de44 --- /dev/null +++ b/ipfs-api-examples/examples/ping_peer.rs @@ -0,0 +1,70 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use futures::{future, TryStreamExt}; +use ipfs_api_examples::ipfs_api::{response::PingResponse, IpfsApi, IpfsClient}; + +// Creates an Ipfs client, discovers a connected peer, and pings it using the +// streaming Api, and by collecting it into a collection. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + + eprintln!(); + eprintln!("discovering connected peers..."); + + let peer = match client.swarm_peers().await { + Ok(connected) => connected + .peers + .into_iter() + .next() + .expect("expected at least one peer"), + Err(e) => { + eprintln!("error getting connected peers: {}", e); + return; + } + }; + + eprintln!(); + eprintln!("discovered peer ({})", peer.peer); + eprintln!(); + eprintln!("streaming 10 pings..."); + + if let Err(e) = client + .ping(&peer.peer[..], Some(10)) + .try_for_each(|ping| { + eprintln!("{:?}", ping); + + future::ok(()) + }) + .await + { + eprintln!("error streaming pings: {}", e); + } + + eprintln!(); + eprintln!("gathering 15 pings..."); + + match client + .ping(&peer.peer[..], Some(15)) + .try_collect::>() + .await + { + Ok(pings) => { + for ping in pings.iter() { + eprintln!("got response ({:?}) at ({})...", ping.text, ping.time); + } + } + Err(e) => eprintln!("error collecting pings: {}", e), + } +} diff --git a/ipfs-api-examples/examples/pubsub.rs b/ipfs-api-examples/examples/pubsub.rs new file mode 100644 index 0000000..0311ed7 --- /dev/null +++ b/ipfs-api-examples/examples/pubsub.rs @@ -0,0 +1,84 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use futures::{future, select, FutureExt, StreamExt, TryStreamExt}; +use ipfs_api_examples::{ + ipfs_api::{IpfsApi, IpfsClient}, + tokio::time, +}; +use std::time::Duration; +use tokio_stream::wrappers::IntervalStream; + +static TOPIC: &'static str = "test"; + +fn get_client() -> IpfsClient { + eprintln!("connecting to localhost:5001..."); + + IpfsClient::default() +} + +// Creates an Ipfs client, and simultaneously publishes and reads from a pubsub +// topic. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("note: ipfs must be run with the --enable-pubsub-experiment flag"); + + let publish_client = get_client(); + + // This block will execute a repeating function that sends + // a message to the "test" topic. + // + let interval = time::interval(Duration::from_secs(1)); + let mut publish = IntervalStream::new(interval) + .then(|_| future::ok(())) // Coerce the stream into a TryStream + .try_for_each(|_| { + eprintln!(); + eprintln!("publishing message..."); + + publish_client + .pubsub_pub(TOPIC, "Hello World!") + .boxed_local() + }) + .boxed_local() + .fuse(); + + // This block will execute a future that suscribes to a topic, + // and reads any incoming messages. + // + let mut subscribe = { + let client = get_client(); + + client + .pubsub_sub(TOPIC, false) + .take(5) + .try_for_each(|msg| { + eprintln!(); + eprintln!("received ({:?})", msg); + + future::ok(()) + }) + .fuse() + }; + + eprintln!(); + eprintln!("publish messages to ({})...", TOPIC); + eprintln!("waiting for messages from ({})...", TOPIC); + + select! { + res = publish => if let Err(e) = res { + eprintln!("error publishing messages: {}", e); + }, + res = subscribe => match res { + Ok(_) => eprintln!("done reading messages..."), + Err(e) => eprintln!("error reading messages: {}", e) + }, + } +} diff --git a/ipfs-api-examples/examples/replace_config.rs b/ipfs-api-examples/examples/replace_config.rs new file mode 100644 index 0000000..41c2040 --- /dev/null +++ b/ipfs-api-examples/examples/replace_config.rs @@ -0,0 +1,28 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use ipfs_api_examples::ipfs_api::{IpfsApi, IpfsClient}; +use std::io::Cursor; + +// Creates an Ipfs client, and replaces the config file with the default one. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("note: this must be run in the root of the project repository"); + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + let default_config = include_str!("default_config.json"); + + match client.config_replace(Cursor::new(default_config)).await { + Ok(_) => eprintln!("replaced config file"), + Err(e) => eprintln!("error replacing config file: {}", e), + } +} diff --git a/ipfs-api-examples/examples/resolve_name.rs b/ipfs-api-examples/examples/resolve_name.rs new file mode 100644 index 0000000..ac0a0d5 --- /dev/null +++ b/ipfs-api-examples/examples/resolve_name.rs @@ -0,0 +1,51 @@ +// Copyright 2017 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use ipfs_api_examples::ipfs_api::{IpfsApi, IpfsClient}; + +const IPFS_IPNS: &str = "/ipns/ipfs.io"; + +// Creates an Ipfs client, and resolves the Ipfs domain name, and +// publishes a path to Ipns. +// +#[ipfs_api_examples::main] +async fn main() { + tracing_subscriber::fmt::init(); + + eprintln!("connecting to localhost:5001..."); + + let client = IpfsClient::default(); + + match client.name_resolve(Some(IPFS_IPNS), true, false).await { + Ok(resolved) => eprintln!("{} resolves to: {}", IPFS_IPNS, &resolved.path), + Err(e) => { + eprintln!("error resolving {}: {}", IPFS_IPNS, e); + return; + } + } + + let publish = match client.name_publish(IPFS_IPNS, true, None, None, None).await { + Ok(publish) => { + eprintln!("published {} to: /ipns/{}", IPFS_IPNS, &publish.name); + publish + } + Err(e) => { + eprintln!("error publishing name: {}", e); + return; + } + }; + + match client.name_resolve(Some(&publish.name), true, false).await { + Ok(resolved) => { + eprintln!("/ipns/{} resolves to: {}", &publish.name, &resolved.path); + } + Err(e) => { + eprintln!("error resolving name: {}", e); + } + } +} diff --git a/ipfs-api-examples/src/lib.rs b/ipfs-api-examples/src/lib.rs new file mode 100644 index 0000000..b3e8c42 --- /dev/null +++ b/ipfs-api-examples/src/lib.rs @@ -0,0 +1,25 @@ +// Copyright 2021 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +#[cfg(feature = "with-actix")] +pub use actix_rt::main; + +#[cfg(feature = "with-actix")] +pub use ipfs_api_backend_actix as ipfs_api; + +#[cfg(feature = "with-actix")] +pub use tokio_actix as tokio; // Compatibilty for actix-rt 1.0 + +#[cfg(feature = "with-hyper")] +pub use tokio::main; + +#[cfg(feature = "with-hyper")] +pub use ipfs_api_backend_hyper as ipfs_api; + +#[cfg(feature = "with-hyper")] +pub use tokio_hyper as tokio; -- cgit v1.2.3 From dd03b0edb4928894b64b85cc44a4984a721650c2 Mon Sep 17 00:00:00 2001 From: Ferris Tseng Date: Tue, 23 Feb 2021 23:44:34 -0500 Subject: fixing actix examples by upgrading to new rt --- ipfs-api-examples/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ipfs-api-examples') diff --git a/ipfs-api-examples/Cargo.toml b/ipfs-api-examples/Cargo.toml index 531dc53..d8c117e 100644 --- a/ipfs-api-examples/Cargo.toml +++ b/ipfs-api-examples/Cargo.toml @@ -17,7 +17,7 @@ with-hyper = ["ipfs-api-backend-hyper", "tokio-hyper", "tokio-hyp with-actix = ["ipfs-api-backend-actix", "tokio-actix", "actix-rt"] [dependencies] -actix-rt = { version = "1.1", optional = true } +actix-rt = { version = "2.0", optional = true } futures = "0.3" ipfs-api-backend-actix = { version = "0.1", path = "../ipfs-api-backend-actix", optional = true } ipfs-api-backend-hyper = { version = "0.1", path = "../ipfs-api-backend-hyper", optional = true } -- cgit v1.2.3 From 6430c7631a2efc497fc14595739b90e20957d293 Mon Sep 17 00:00:00 2001 From: Ferris Tseng Date: Sun, 4 Apr 2021 18:51:03 -0400 Subject: update examples --- ipfs-api-examples/Cargo.toml | 8 +++----- ipfs-api-examples/examples/pubsub.rs | 6 ++---- ipfs-api-examples/src/lib.rs | 6 ------ 3 files changed, 5 insertions(+), 15 deletions(-) (limited to 'ipfs-api-examples') diff --git a/ipfs-api-examples/Cargo.toml b/ipfs-api-examples/Cargo.toml index d8c117e..9e928eb 100644 --- a/ipfs-api-examples/Cargo.toml +++ b/ipfs-api-examples/Cargo.toml @@ -12,9 +12,8 @@ readme = "../README.md" license = "MIT OR Apache-2.0" [features] -default = ["with-hyper"] -with-hyper = ["ipfs-api-backend-hyper", "tokio-hyper", "tokio-hyper/macros", "tokio-hyper/rt-multi-thread"] -with-actix = ["ipfs-api-backend-actix", "tokio-actix", "actix-rt"] +with-hyper = ["ipfs-api-backend-hyper", "tokio/macros", "tokio/rt-multi-thread"] +with-actix = ["ipfs-api-backend-actix", "actix-rt"] [dependencies] actix-rt = { version = "2.0", optional = true } @@ -22,7 +21,6 @@ futures = "0.3" ipfs-api-backend-actix = { version = "0.1", path = "../ipfs-api-backend-actix", optional = true } ipfs-api-backend-hyper = { version = "0.1", path = "../ipfs-api-backend-hyper", optional = true } tar = "0.4" -tokio-actix = { package = "tokio", version = "1.0", features = ["time"], optional = true } -tokio-hyper = { package = "tokio", version = "1.2", features = ["time"], optional = true } +tokio = { version = "1.2", features = ["time"] } tokio-stream = { version = "0.1", features = ["time"] } tracing-subscriber = { version = "0.2", features = ["fmt"] } diff --git a/ipfs-api-examples/examples/pubsub.rs b/ipfs-api-examples/examples/pubsub.rs index 0311ed7..8944f3c 100644 --- a/ipfs-api-examples/examples/pubsub.rs +++ b/ipfs-api-examples/examples/pubsub.rs @@ -7,11 +7,9 @@ // use futures::{future, select, FutureExt, StreamExt, TryStreamExt}; -use ipfs_api_examples::{ - ipfs_api::{IpfsApi, IpfsClient}, - tokio::time, -}; +use ipfs_api_examples::ipfs_api::{IpfsApi, IpfsClient}; use std::time::Duration; +use tokio::time; use tokio_stream::wrappers::IntervalStream; static TOPIC: &'static str = "test"; diff --git a/ipfs-api-examples/src/lib.rs b/ipfs-api-examples/src/lib.rs index b3e8c42..71d3fb5 100644 --- a/ipfs-api-examples/src/lib.rs +++ b/ipfs-api-examples/src/lib.rs @@ -12,14 +12,8 @@ pub use actix_rt::main; #[cfg(feature = "with-actix")] pub use ipfs_api_backend_actix as ipfs_api; -#[cfg(feature = "with-actix")] -pub use tokio_actix as tokio; // Compatibilty for actix-rt 1.0 - #[cfg(feature = "with-hyper")] pub use tokio::main; #[cfg(feature = "with-hyper")] pub use ipfs_api_backend_hyper as ipfs_api; - -#[cfg(feature = "with-hyper")] -pub use tokio_hyper as tokio; -- cgit v1.2.3 From a1829b5b93531a6262ed779c4a58f94a1748737c Mon Sep 17 00:00:00 2001 From: Ferris Tseng Date: Sun, 4 Apr 2021 19:36:54 -0400 Subject: add default with-hyper again to fix build --- ipfs-api-examples/Cargo.toml | 1 + 1 file changed, 1 insertion(+) (limited to 'ipfs-api-examples') diff --git a/ipfs-api-examples/Cargo.toml b/ipfs-api-examples/Cargo.toml index 9e928eb..4f8a355 100644 --- a/ipfs-api-examples/Cargo.toml +++ b/ipfs-api-examples/Cargo.toml @@ -12,6 +12,7 @@ readme = "../README.md" license = "MIT OR Apache-2.0" [features] +default = ["with-hyper"] with-hyper = ["ipfs-api-backend-hyper", "tokio/macros", "tokio/rt-multi-thread"] with-actix = ["ipfs-api-backend-actix", "actix-rt"] -- cgit v1.2.3 From 7771a0db1374b43d2c7445f29566a5e0bd38cf22 Mon Sep 17 00:00:00 2001 From: Ferris Tseng Date: Sun, 4 Apr 2021 19:37:24 -0400 Subject: use tokio 1 instead of 1.2 --- ipfs-api-examples/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ipfs-api-examples') diff --git a/ipfs-api-examples/Cargo.toml b/ipfs-api-examples/Cargo.toml index 4f8a355..121df64 100644 --- a/ipfs-api-examples/Cargo.toml +++ b/ipfs-api-examples/Cargo.toml @@ -22,6 +22,6 @@ futures = "0.3" ipfs-api-backend-actix = { version = "0.1", path = "../ipfs-api-backend-actix", optional = true } ipfs-api-backend-hyper = { version = "0.1", path = "../ipfs-api-backend-hyper", optional = true } tar = "0.4" -tokio = { version = "1.2", features = ["time"] } +tokio = { version = "1", features = ["time"] } tokio-stream = { version = "0.1", features = ["time"] } tracing-subscriber = { version = "0.2", features = ["fmt"] } -- cgit v1.2.3