|
| 1 | +using Common.Logging; |
| 2 | +using Newtonsoft.Json; |
| 3 | +using Newtonsoft.Json.Linq; |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.IO; |
| 7 | +using System.Linq; |
| 8 | +using System.Text; |
| 9 | +using System.Threading; |
| 10 | +using System.Threading.Tasks; |
| 11 | + |
| 12 | +namespace Ipfs.Api |
| 13 | +{ |
| 14 | + |
| 15 | + /// <summary> |
| 16 | + /// Allows you to publish messages to a given topic, and also to |
| 17 | + /// subscribe to new messages on a given topic. |
| 18 | + /// </summary> |
| 19 | + /// <remarks> |
| 20 | + /// This API is accessed via the <see cref="IpfsClient.PubSub"/> property. |
| 21 | + /// <para> |
| 22 | + /// This is an experimental feature. It is not intended in its current state |
| 23 | + /// to be used in a production environment. |
| 24 | + /// </para> |
| 25 | + /// <para> |
| 26 | + /// To use, the daemon must be run with '--enable-pubsub-experiment'. |
| 27 | + /// </para> |
| 28 | + /// </remarks> |
| 29 | + /// <seealso href="https://github.com/ipfs/interface-ipfs-core/blob/master/SPEC/PUBSUB.md">PUBSUB API</seealso> |
| 30 | + public class PubSubApi |
| 31 | + { |
| 32 | + static ILog log = LogManager.GetLogger<PubSubApi>(); |
| 33 | + |
| 34 | + IpfsClient ipfs; |
| 35 | + |
| 36 | + internal PubSubApi(IpfsClient ipfs) |
| 37 | + { |
| 38 | + this.ipfs = ipfs; |
| 39 | + } |
| 40 | + |
| 41 | + /// <summary> |
| 42 | + /// Get the subscribed topics. |
| 43 | + /// </summary> |
| 44 | + /// <returns> |
| 45 | + /// A sequence of <see cref="string"/> for each topic. |
| 46 | + /// </returns> |
| 47 | + public async Task<IEnumerable<string>> SubscribedTopicsAsync() |
| 48 | + { |
| 49 | + var json = await ipfs.DoCommandAsync("pubsub/ls"); |
| 50 | + var result = JObject.Parse(json); |
| 51 | + var strings = result["Strings"] as JArray; |
| 52 | + if (strings == null) return new string[0]; |
| 53 | + return strings.Select(s => (string)s); |
| 54 | + } |
| 55 | + |
| 56 | + /// <summary> |
| 57 | + /// Get the peers that are pubsubing with us. |
| 58 | + /// </summary> |
| 59 | + /// <returns> |
| 60 | + /// A sequence of <see cref="string"/> for each peer ID. |
| 61 | + /// </returns> |
| 62 | + public async Task<IEnumerable<string>> PeersAsync() |
| 63 | + { |
| 64 | + var json = await ipfs.DoCommandAsync("pubsub/peers"); |
| 65 | + var result = JObject.Parse(json); |
| 66 | + var strings = result["Strings"] as JArray; |
| 67 | + if (strings == null) return new string[0]; |
| 68 | + return strings.Select(s => (string)s); |
| 69 | + } |
| 70 | + |
| 71 | + /// <summary> |
| 72 | + /// Publish a message to a given topic. |
| 73 | + /// </summary> |
| 74 | + /// <param name="topic"> |
| 75 | + /// The topic name. |
| 76 | + /// </param> |
| 77 | + /// <param name="message"> |
| 78 | + /// The message to publish. |
| 79 | + /// </param> |
| 80 | + public async Task Publish(string topic, string message) |
| 81 | + { |
| 82 | + var _ = await ipfs.PostCommandAsync("pubsub/pub", topic, "arg=" + message); |
| 83 | + return; |
| 84 | + } |
| 85 | + |
| 86 | + /// <summary> |
| 87 | + /// Subscribe to messages on a given topic. |
| 88 | + /// </summary> |
| 89 | + /// <param name="topic"> |
| 90 | + /// The topic name. |
| 91 | + /// </param> |
| 92 | + /// <param name="handler"> |
| 93 | + /// The action to perform when a <see cref="PublishedMessage"/> is received. |
| 94 | + /// </param> |
| 95 | + /// <param name="cancellationToken"> |
| 96 | + /// Is used to stop the topic listener. When cancelled, the <see cref="OperationCanceledException"/> |
| 97 | + /// is <b>NOT</b> raised. |
| 98 | + /// </param> |
| 99 | + /// <returns> |
| 100 | + /// After the topic listener is register with the IPFS server. |
| 101 | + /// </returns> |
| 102 | + /// <remarks> |
| 103 | + /// The <paramref name="handler"/> is invoked on the topic listener thread. |
| 104 | + /// </remarks> |
| 105 | + public async Task Subscribe(string topic, Action<PublishedMessage> handler, CancellationToken cancellationToken = default(CancellationToken)) |
| 106 | + { |
| 107 | + var messageStream = await ipfs.PostDownloadAsync("pubsub/sub", topic); |
| 108 | +#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed |
| 109 | + Task.Run(() => ProcessMessages(topic, handler, messageStream, cancellationToken)); |
| 110 | +#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed |
| 111 | + return; |
| 112 | + } |
| 113 | + |
| 114 | + void ProcessMessages(string topic, Action<PublishedMessage> handler, Stream stream, CancellationToken ct) |
| 115 | + { |
| 116 | + log.DebugFormat("Start listening for '{0}' messages", topic); |
| 117 | + using (var sr = new StreamReader(stream)) |
| 118 | + { |
| 119 | + while (!sr.EndOfStream && !ct.IsCancellationRequested) |
| 120 | + { |
| 121 | + var json = sr.ReadLine(); |
| 122 | + if (log.IsDebugEnabled) |
| 123 | + log.DebugFormat("PubSub message {0}", json); |
| 124 | + if (json != "{}" && !ct.IsCancellationRequested) |
| 125 | + { |
| 126 | + handler(new PublishedMessage(json)); |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + log.DebugFormat("Stop listening for '{0}' messages", topic); |
| 131 | + } |
| 132 | + |
| 133 | + } |
| 134 | + |
| 135 | +} |
0 commit comments