private Connection CreateConnectionAndWireOnLocalCandidate(PeerClient remoteClient, string remoteUserId)
        {
            Connection Con = CreateConnection.Invoke(remoteClient);

            Con.OnLocalCandidate += (Connection, Candidate) => {
                try
                {
                    Client.Publish(new PublishArgs(RemoteUserChannel(remoteUserId), Candidate.ToJson(), CandidateTag)
                    {
                        OnSuccess = (PublishSuccessArgs) =>
                        {
                            Log.Info("Published candidate to remote peer.");
                        },
                        OnFailure = (e) =>
                        {
                            Log.Error("Could not publish candidate to remote peer.", e.Exception);
                        }
                    });
                }
                catch (Exception ex)
                {
                    Log.Error("Could not publish candidate to remote peer.");
                }
            };

            return(Con);
        }
Exemple #2
0
        public async Task <bool> QueryPeerTipAsync(PeerId recipientPeerId)
        {
            try
            {
                PeerClient.SendMessage(new MessageDto(
                                           new LatestDeltaHashRequest().ToProtocolMessage(PeerId, CorrelationId.GenerateCorrelationId()),
                                           recipientPeerId
                                           ));

                using (CancellationTokenProvider.CancellationTokenSource)
                {
                    await QueryTipResponseMessageStreamer
                    .FirstAsync(a => a != null &&
                                a.PeerId.PublicKey.SequenceEqual(recipientPeerId.PublicKey) &&
                                a.PeerId.Ip.SequenceEqual(recipientPeerId.Ip))
                    .ToTask(CancellationTokenProvider.CancellationTokenSource.Token)
                    .ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException)
            {
                return(false);
            }
            catch (Exception e)
            {
                Logger.Error(e, nameof(QueryPeerTipAsync));
                return(false);
            }

            return(true);
        }
Exemple #3
0
        public static async Task MainAsync(string[] args)
        {
            Options options = Argument.Parse <Options>(args);

            if (options.IsValid())
            {
                FileHash       hash    = FileHash.Parse(options.Hash);
                NetworkAddress address = new NetworkAddress(options.Host, Int32.Parse(options.Port));

                using (PeerClient client = new PeerClient())
                {
                    Notification notification = null;
                    PeerSession  session      = await client.ConnectAsync(hash, address);

                    Console.WriteLine($"Hash: {hash}");
                    Console.WriteLine($"Peer: {session.Peer}");
                    Console.WriteLine();

                    switch (options.Command)
                    {
                    case "download":
                        session.Download(options.Destination);
                        break;
                    }

                    while (notification?.Type != NotificationType.DataCompleted)
                    {
                        notification = await session.NextAsync();

                        Console.WriteLine(notification);
                    }
                }
            }
        }
Exemple #4
0
        private static void ConnectToPeer(string[] args)
        {
            if (args.Length < 2 || string.IsNullOrEmpty(args[0]) || string.IsNullOrEmpty(args[1]))
            {
                throw new ArgumentException($"You need to fill the ip and port of the peer");
            }

            client = new PeerClient(args[0], int.Parse(args[1]));
        }
Exemple #5
0
 public override void Reconnect(PeerClient remoteClient, Connection connection)
 {
     try
     {
         ClientExtensions.ReconnectRemoteClient(Client, remoteClient, connection);
     }
     catch (Exception e)
     {
     }
 }
Exemple #6
0
        public void Start()
        {
            Task.Run(() =>
            {
                PeerServer pserver = new PeerServer();
                pserver.Start();
            });

            PeerClient pclient = new PeerClient();

            Console.WriteLine("Skriv ønskede fil");
            String fileName           = Console.ReadLine();
            List <FileEndPoint> files = pclient.Search(fileName);

            if (files.Count > 0)
            {
                // take the first
                pclient.Download(fileName, files[0], fileName);
            }
        }
        public async Task <IPeerDeltaHistoryResponse> DeltaHistoryAsync(PeerId recipientPeerId, uint height = 1, uint range = 1024)
        {
            IPeerDeltaHistoryResponse history;

            try
            {
                PeerClient.SendMessage(new MessageDto(
                                           new DeltaHistoryRequest
                {
                    Range  = range,
                    Height = height
                }.ToProtocolMessage(PeerId, CorrelationId.GenerateCorrelationId()),
                                           recipientPeerId
                                           ));

                using (CancellationTokenProvider.CancellationTokenSource)
                {
                    history = await DeltaHistoryResponseMessageStreamer
                              .FirstAsync(a => a != null &&
                                          a.PeerId.PublicKey.SequenceEqual(recipientPeerId.PublicKey) &&
                                          a.PeerId.Ip.SequenceEqual(recipientPeerId.Ip))
                              .ToTask(CancellationTokenProvider.CancellationTokenSource.Token)
                              .ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException)
            {
                return(null);
            }
            catch (Exception e)
            {
                Logger.Error(e, nameof(DeltaHistoryAsync));
                return(null);
            }

            return(history);
        }
Exemple #8
0
 public abstract void Reconnect(PeerClient remoteClient, Connection connection);
 public override void Reconnect(PeerClient remoteClient, Connection connection)
 {
     throw new NotImplementedException();
 }
Exemple #10
0
        private Connection Connection(PeerClient remoteClient)
        {
            string peerName = "Unknown";

            FM.WebSync.Record r;
            if (remoteClient.BoundRecords != null && remoteClient.BoundRecords.TryGetValue("userName", out r))
            {
                if (!String.IsNullOrEmpty(r.ValueJson))
                {
                    peerName = r.ValueJson.Trim('"');
                }
            }

            // Create remote media to manage the remote audio/video tracks.
            RemoteMedia remoteMedia = null;

#if __IOS__
            Utilities.DispatchSync(() =>
            {
                remoteMedia = new RemoteMedia(false, false, null);
            });
#else
            FM.IceLink.Android.Utility.DispatchToMainThread(() =>
            {
                remoteMedia = new RemoteMedia(Android.App.Application.Context, false, false, null);
            }, true);
#endif

            // Initialize the audio/video streams for the connection with the
            // local media outputs (sender) and the remote media inputs (receiver).
            AudioStream audioStream = null;
            VideoStream videoStream = null;
            if (LocalCameraMedia != null)
            {
                audioStream = new AudioStream(LocalCameraMedia, remoteMedia)
                {
                    LocalSend    = EnableAudioSend,
                    LocalReceive = EnableAudioReceive
                };

                videoStream = new VideoStream(LocalCameraMedia, remoteMedia)
                {
                    LocalSend    = EnableVideoSend,
                    LocalReceive = EnableVideoReceive
                };
            }

            if (LocalScreenMedia != null)
            {
                audioStream = new AudioStream(LocalScreenMedia, remoteMedia)
                {
                    LocalSend    = EnableAudioSend,
                    LocalReceive = EnableAudioReceive
                };

                videoStream = new VideoStream(LocalScreenMedia, remoteMedia)
                {
                    LocalSend    = EnableVideoSend,
                    LocalReceive = EnableVideoReceive
                };
            }

            // Initialize the connection with the streams.
            Connection connection = new Connection(new Stream[] { audioStream, videoStream });

            // Provide STUN/TURN servers to assist with NAT traversal.
            try
            {
                var items = JsonConvert.DeserializeObject <List <LoginModel.LoginIceServer> >(Settings.IceLinkServers);
                List <IceServer> servers = new List <IceServer>();
                foreach (var item in items)
                {
                    if (string.IsNullOrEmpty(item.sPassword) || string.IsNullOrEmpty(item.sUser))
                    {
                        servers.Add(new IceServer(item.sServer));
                    }
                    else
                    {
                        servers.Add(new IceServer(item.sServer, item.sUser, item.sPassword));
                    }
                }
                _iceServers = servers.ToArray();
            }
            catch (Exception e)
            {
                _iceServers = new[]
                {
                    //new IceServer("stun:turn.v3.icelink.fm:3478?transport=udp"),
                    //new IceServer("stun:turn.v3.icelink.fm:80?transport=udp", "*****@*****.**", "Meditocicelink1!")

                    //otros servidores de icelink
                    //new IceServer("stun:turn.frozenmountain.com:3478?transport=udp"),
                    new IceServer("turn:turn.frozenmountain.com:80?transport=udp", "test", "pa55w0rd!"),

                    //NB: url "turn:turn.icelink.fm:443" implies that the relay server supports both TCP and UDP
                    //if you want to restrict the network protocol, use "turn:turn.icelink.fm:443?transport=udp"
                    //or "turn:turn.icelink.fm:443?transport=tcp". For further info, refer to RFC 7065 3.1 URI Scheme Syntax
                    //new IceServer("turn:turn.frozenmountain.com:80?transport=udp", "test", "pa55w0rd!"),
                    //new IceServer("turns:turn.frozenmountain.com:443", "test", "pa55w0rd!")
                };
            }


            connection.IceServers = _iceServers;


            // Add the remote view to the layout.
            var remoteView = remoteMedia.View;
            if (remoteView != null)
            {
                LayoutManager.AddRemoteView(remoteMedia.Id, new FMView(remoteMedia.View));
            }

            connection.OnStateChange += (c) =>
            {
                if (c.State == ConnectionState.Connected)
                {
                    OnPeerJoined(peerName);
                }
                // Remove the remote view from the layout.
                else if (c.State == ConnectionState.Closing || c.State == ConnectionState.Failing)
                {
                    var layoutManager = LayoutManager;
                    if (layoutManager != null)
                    {
                        layoutManager.RemoveRemoteView(remoteMedia.Id);
                    }
                    RemoteMedias.Remove(remoteMedia);
                    remoteMedia.Destroy();
                }
                else if (c.State == ConnectionState.Failed)
                {
                    OnPeerLeft(peerName);
                    if (!SIGNAL_MANUALLY)
                    {
                        _signalling.Reconnect(remoteClient, c);
                    }
                }
            };

            // Track the remote media in a collection.
            RemoteMedias.Add(remoteMedia);

            connection.LocalDtlsCertificate = _certificate;

            return(connection);
        }