source: trunk/CrypP2P/P2PManager.cs @ 1545

Last change on this file since 1545 was 1545, checked in by Paul Lelgemann, 12 years ago

o CrypP2P: refactored P2PBase, removed race condition and unused code

File size: 7.7 KB
Line 
1/*
2   Copyright 2010 Paul Lelgemann, University of Duisburg-Essen
3
4   Licensed under the Apache License, Version 2.0 (the "License");
5   you may not use this file except in compliance with the License.
6   You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10   Unless required by applicable law or agreed to in writing, software
11   distributed under the License is distributed on an "AS IS" BASIS,
12   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   See the License for the specific language governing permissions and
14   limitations under the License.
15*/
16
17using System;
18using System.Windows.Forms;
19using Cryptool.P2P.Internal;
20using Cryptool.P2P.Worker;
21using Cryptool.PluginBase;
22using Cryptool.PluginBase.Miscellaneous;
23using Cryptool.Plugins.PeerToPeer.Internal;
24
25namespace Cryptool.P2P
26{
27    public sealed class P2PManager
28    {
29        #region Singleton
30
31        public static readonly P2PManager Instance = new P2PManager();
32
33        private P2PManager()
34        {
35            P2PBase = new P2PBase();
36
37            // Register events
38
39            // to forward event from overlay/dht MessageReceived-Event from P2PBase
40            P2PBase.OnP2PMessageReceived += OnP2PMessageReceived;
41
42            // Register exit event to terminate P2P connection without loosing data
43            // TODO check if this is correct, should be - but handler is not called (and application does not shut down), probably unrelated to this problem
44            Application.ApplicationExit += HandleDisconnectByApplicationShutdown;
45        }
46
47        #endregion
48
49        #region Variables
50
51        public P2PBase P2PBase { get; private set; }
52        public bool IsP2PConnecting { get; internal set; }
53
54        #endregion
55
56        #region Events
57
58        public static event GuiLogNotificationEventHandler OnGuiLogNotificationOccured;
59
60        public delegate void P2PConnectionStateChangeEventHandler(object sender, bool newState);
61        public static event P2PConnectionStateChangeEventHandler OnP2PConnectionStateChangeOccurred;
62
63        public event P2PBase.P2PMessageReceived OnPeerMessageReceived;
64
65        #endregion Events
66
67        internal void FireConnectionStatusChange()
68        {
69            if (OnP2PConnectionStateChangeOccurred != null)
70            {
71                OnP2PConnectionStateChangeOccurred(this, IsP2PConnected());
72            }
73        }
74
75        public bool IsP2PConnected()
76        {
77            return P2PBase.Started;
78        }
79
80        public string UserInfo()
81        {
82            if (!IsP2PConnected())
83            {
84                return null;
85            }
86
87            string userName;
88            var userInfo = P2PBase.GetPeerId(out userName);
89            return userInfo + " (" + userName + ")";
90        }
91
92        public void HandleConnectOnStartup()
93        {
94            if (P2PSettings.Default.ConnectOnStartup && IsReadyToConnect())
95            {
96                GuiLogMessage("Connect on startup enabled. Establishing connection...", NotificationLevel.Info);
97                new ConnectionWorker(P2PBase).Start();
98            }
99        }
100
101        private bool IsReadyToConnect()
102        {
103            if (String.IsNullOrEmpty(P2PSettings.Default.PeerName))
104            {
105                GuiLogMessage("Peer-to-peer not fully configured: username missing.", NotificationLevel.Error);
106                return false;
107            }
108
109            if (String.IsNullOrEmpty(P2PSettings.Default.PeerName))
110            {
111                GuiLogMessage("Peer-to-peer not fully configured: world name missing.", NotificationLevel.Error);
112                return false;
113            }
114
115            return true;
116        }
117
118        public PeerId GetPeerId(out string userName)
119        {
120            return P2PBase.GetPeerId(out userName);
121        }
122
123        // to forward event from overlay/dht MessageReceived-Event from P2PBase
124        private void OnP2PMessageReceived(PeerId sourceAddr, byte[] data)
125        {
126            if (OnPeerMessageReceived != null)
127                OnPeerMessageReceived(sourceAddr, data);
128        }
129
130        #region Framework methods
131
132        private void HandleDisconnectByApplicationShutdown(object sender, EventArgs e)
133        {
134            if (IsP2PConnected())
135            {
136                new ConnectionWorker(P2PBase).Start();
137            }
138        }
139
140        public void GuiLogMessage(string message, NotificationLevel logLevel)
141        {
142            EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, null, new GuiLogEventArgs(message, null, logLevel));
143        }
144
145        #endregion Framework methods
146
147        #region DHT operations
148
149        /// <summary>
150        /// Stores the given data in the DHT. This method will block until a response has been received.
151        ///
152        /// The underlying DHT is versionend. Store attempts will fail, if the latest version has not been retrieved before.
153        /// </summary>
154        /// <param name="key">key to write</param>
155        /// <param name="data">data to write</param>
156        /// <exception cref="NotConnectedException">Will be thrown if the P2P system is not connected</exception>
157        /// <returns>true if the store attempt was successful, false otherwise</returns>
158        public static bool Store(string key, byte[] data)
159        {
160            if (!Instance.IsP2PConnected())
161                throw new NotConnectedException();
162
163            return Instance.P2PBase.SynchStore(key, data);
164        }
165
166        /// <summary>
167        /// Stores the given data in the DHT. This method will block until a response has been received.
168        ///
169        /// The underlying DHT is versionend. Store attempts will fail, if the latest version has not been retrieved before.
170        /// </summary>
171        /// <param name="key">key to write</param>
172        /// <param name="data">data to write</param>
173        /// <exception cref="NotConnectedException">Will be thrown if the P2P system is not connected</exception>
174        /// <returns>true if the store attempt was successful, false otherwise</returns>
175        public static bool Store(string key, string data)
176        {
177            if (!Instance.IsP2PConnected())
178                throw new NotConnectedException();
179           
180            return Instance.P2PBase.SynchStore(key, data);
181        }
182
183        /// <summary>
184        /// Retrieves the latest version of a given in key from the DHT.
185        /// </summary>
186        /// <param name="key">key to retrieve</param>
187        /// <exception cref="NotConnectedException">Will be thrown if the P2P system is not connected</exception>
188        /// <returns>byte array containing the data</returns>
189        public static byte[] Retrieve(string key)
190        {
191            if (!Instance.IsP2PConnected())
192                throw new NotConnectedException();
193           
194            return Instance.P2PBase.SynchRetrieve(key);
195        }
196
197        /// <summary>
198        /// Removes a key and its data from the DHT.
199        ///
200        /// The underlying DHT is versionend. Remove attempts will fail, if the latest version has not been retrieved before.
201        /// </summary>
202        /// <param name="key">key to remove</param>
203        /// <exception cref="NotConnectedException">Will be thrown if the P2P system is not connected</exception>
204        /// <returns>bool determining wether the attempt was successful</returns>
205        public static bool Remove(string key)
206        {
207            if (!Instance.IsP2PConnected())
208                throw new NotConnectedException();
209
210            return Instance.P2PBase.SynchRemove(key);
211        }
212
213        #endregion DHT operations
214    }
215
216   
217}
Note: See TracBrowser for help on using the repository browser.