From: <che...@us...> - 2008-02-16 11:21:12
|
Revision: 1368 http://mp-plugins.svn.sourceforge.net/mp-plugins/?rev=1368&view=rev Author: chef_koch Date: 2008-02-16 03:21:06 -0800 (Sat, 16 Feb 2008) Log Message: ----------- many code changes - phoneBook is now it's own class - improved the Listening method, which is called now ReceiveThread Modified Paths: -------------- trunk/plugins/FritzBox/FritzBox/FritzBox.cs trunk/plugins/FritzBox/FritzBox/FritzBox.csproj trunk/plugins/FritzBox/FritzBox/FritzBoxSetupFrom.cs trunk/plugins/FritzBox/FritzBox/Properties/Resources.Designer.cs Added Paths: ----------- trunk/plugins/FritzBox/FritzBox/PhoneBook.cs Removed Paths: ------------- trunk/plugins/FritzBox/FritzBox/FritzBoxWatch.cs Modified: trunk/plugins/FritzBox/FritzBox/FritzBox.cs =================================================================== --- trunk/plugins/FritzBox/FritzBox/FritzBox.cs 2008-02-15 23:57:37 UTC (rev 1367) +++ trunk/plugins/FritzBox/FritzBox/FritzBox.cs 2008-02-16 11:21:06 UTC (rev 1368) @@ -37,278 +37,156 @@ using MediaPortal.GUI.Library; using MediaPortal.Player; using MediaPortal.Util; +using System.Text; namespace FritzBox { - /* - * Things to do: - * - add more comments to code - * - split code more in methods/classes - */ [PluginIcons("FritzBox.FritzBox.png", "FritzBox.FritzBoxDisabled.png")] public class FritzBox : ISetupForm, IPlugin { + #region Private Fields + + /// <summary> + /// networkstream to receive data, sent by fritzbox + /// </summary> + private NetworkStream networkStream; + + /// <summary> + /// address for the connected fritzbox + /// </summary> + private string fritzBoxAddress; + + /// <summary> + /// port for the connected fritzbox + /// </summary> + private int fritzBoxPort; + + /// <summary> + /// indicates whether listing is enabled or not + /// </summary> + private bool stopThread; + + #endregion + #region Variables - public const string _version = "0.2.2.8"; + public const string _version = "0.2.2.9"; public static int _lastVersion = 0; - public static bool _extensiveLogging = false; + static bool _extensiveLogging = false; - private bool _fritzBoxDisabled = false; - List<CallAction> actionList = new List<CallAction>(); object tempNotify = null; // notify settings - private int _timeout = -1; // autoclose the dialog after the timeout expired - private bool _closeOnTimeout = false; - private bool _closeOnConnectionClosed = false; + int _timeout = -1; // autoclose the dialog after the timeout expired + bool _closeOnTimeout = false; + bool _closeOnConnectionClosed = false; - public static bool _filterMSNs = false; - public static List<String> _msnList = new List<String>(); + bool _filterMSNs = false; + List<String> _msnList = new List<String>(); - public static bool _showMsnOnHeading = false; + bool _showMsnOnHeading = false; + + private bool _usePhonebook = true; + private PhoneBook phoneBook; + int maxNotifies = 20; + int notifyCount = 0; + // media settings - private bool _stopMedia = true; // stop media when an event happend - private bool _resumeMedia = true; // resume media when notify is closed + bool _stopMedia = true; // stop media when an event happend + bool _resumeMedia = true; // resume media when notify is closed - private bool _showNotify = true; - private List<CallAction> notifyQueue = new List<CallAction>(); + bool _showNotify = true; + List<CallAction> notifyQueue = new List<CallAction>(); - // phonebook settings - public static bool _usePhonebook = true; - public static bool _showUnknownCaller = true; - public static bool _saveUnknownCaller = true; - - public static List<Caller> phonebook = new List<Caller>(); - #endregion - #region Constructors/Destructors + #region Constructors and Destructors + /// <summary> + /// constructor + /// </summary> public FritzBox() { + ReceivedData += new ReceivedDataEventHandler(FritzBox_ReceivedData); } + /// <summary> + /// Destructor. + /// </summary> + ~FritzBox() { } + #endregion - #region Settings + #region Public Events and Delegates - private void LoadSettings() - { - char[] charSeparators = new char[] { ';' }; + public delegate void ReceivedDataEventHandler(object sender, EventArgs e); + public event ReceivedDataEventHandler ReceivedData; - if (_extensiveLogging) - Log.Info("FRITZ!Box: LoadSettings"); + #endregion - using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) - { - _lastVersion = xmlreader.GetValueAsInt("fritzbox", "lastVersion", 0); + #region Private Functions/Methods - FritzBoxWatch.fritzBoxAddress = xmlreader.GetValueAsString("fritzbox", "address", "fritz.box"); - FritzBoxWatch.fritzBoxPort = xmlreader.GetValueAsInt("fritzbox", "port", 1012); - - _extensiveLogging = xmlreader.GetValueAsBool("fritzbox", "extensiveLogging", false); - - // notify settings - FritzBoxWatch.maxNotifies = xmlreader.GetValueAsInt("fritzbox", "maxNotifies", 20); - _closeOnTimeout = xmlreader.GetValueAsBool("fritzbox", "closeOnTimeout", false); - _timeout = xmlreader.GetValueAsInt("fritzbox", "timeout", 10); - _closeOnConnectionClosed = xmlreader.GetValueAsBool("fritzbox", "closeOnConnectionClosed", true); - - if ((!_closeOnTimeout) || (_timeout == 0)) - _timeout = -1; - - _filterMSNs = xmlreader.GetValueAsBool("fritzbox", "filterMSNs", false); - string strMSN = xmlreader.GetValueAsString("fritzbox", "MSN", ""); - _msnList.AddRange(strMSN.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)); - - if (_extensiveLogging) - Log.Debug("FRITZ!Box: MSNs loaded: {0}", strMSN); - - _showMsnOnHeading = xmlreader.GetValueAsBool("fritzbox", "showMsnOnHeading", false); - - // media settings - _stopMedia = xmlreader.GetValueAsBool("fritzbox", "stopMedia", true); - _resumeMedia = xmlreader.GetValueAsBool("fritzbox", "resumeMedia", true); - - // phonebook settings - _usePhonebook = xmlreader.GetValueAsBool("fritzbox", "usePhonebook", true); - _showUnknownCaller = xmlreader.GetValueAsBool("fritzbox", "showUnknownCaller", true); - _saveUnknownCaller = xmlreader.GetValueAsBool("fritzbox", "saveUnknownCaller", true); - - if (_extensiveLogging) - { - Log.Info("FRITZ!Box: closeOnTimeout = {0}", _closeOnTimeout.ToString()); - Log.Info("FRITZ!Box: timeout = {0}", _timeout.ToString()); - Log.Info("FRITZ!Box: showMsnOnHeading = {0}", _showMsnOnHeading.ToString()); - //Log.Info("FRITZ!Box: maxNotifies = {0}", FritzBoxWatch.maxNotifies.ToString()); - - Log.Info("FRITZ!Box: stopMedia = {0}", _stopMedia.ToString()); - Log.Info("FRITZ!Box: resumeMedia = {0}", _resumeMedia.ToString()); - - Log.Info("FRITZ!Box: usePhonebook = {0}", _usePhonebook.ToString()); - Log.Info("FRITZ!Box: showUnknownCaller = {0}", _showUnknownCaller.ToString()); - Log.Info("FRITZ!Box: saveUnknownCaller = {0}", _saveUnknownCaller.ToString()); - } - } - - LoadPhonebook(); - } - - private void SaveSettings() + private void ReceiveThread() { - if (_extensiveLogging) - Log.Info("FRITZ!Box: SaveSettings"); - - using (MediaPortal.Profile.Settings xmlwriter = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) + while (!stopThread) { - xmlwriter.SetValue("fritzbox", "lastVersion", _version.Replace(".", string.Empty)); + System.Threading.Thread.Sleep(100); + if (this.networkStream.DataAvailable) + if (ReceivedData != null) + ReceivedData(this, new EventArgs()); } - - SavePhonebook(); } - #endregion - - #region Phonebook - - public static void LoadPhonebook() + void FritzBox_ReceivedData(object sender, EventArgs e) { - if ((_lastVersion < 0220) && (!File.Exists(Config.GetFile(Config.Dir.Config, "fritzbox.xml")))) - { - UpdateTo0220(); - return; - } + byte[] myReadBuffer = new byte[1024]; + StringBuilder myCompleteMessage = new StringBuilder(); + int numberOfBytesRead = 0; - using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "fritzbox.xml"))) + // Incoming message may be larger than the buffer size. + do { - int countCaller = xmlreader.GetValueAsInt("phonebook", "count", 0); + numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length); - for (int i = 0; i < countCaller; i++) - { - Caller caller = new Caller(); - - caller.ID = xmlreader.GetValueAsString("phonebook", string.Format("callerID{0}", i.ToString()), ""); - caller.Name = xmlreader.GetValueAsString("phonebook", string.Format("name{0}", i.ToString()), ""); - caller.Show = xmlreader.GetValueAsBool("phonebook", string.Format("show{0}", i.ToString()), false); - - phonebook.Add(caller); - - if (_extensiveLogging) - Log.Debug("FRITZ!Box: caller loaded: {0} {1} {2}", caller.ID, caller.Name, caller.Show); - } + myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead)); } + while (networkStream.DataAvailable); + if (_extensiveLogging) - Log.Debug("FRITZ!Box: imported {0} callers", phonebook.Count.ToString()); + Log.Info("received data: {0}", myCompleteMessage.ToString()); + CallAction callAction = ParseAction(myCompleteMessage.ToString()); + if (_extensiveLogging) + callAction.WriteToLog(); + + OnCallAction(callAction); } - public static void SavePhonebook() + void OnStartExternal(Process proc, bool waitForExit) { - using (MediaPortal.Profile.Settings xmlwriter = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "fritzbox.xml"))) + if (waitForExit) { - xmlwriter.SetValue("phonebook", "count", phonebook.Count); - - for (int i = 0; i < phonebook.Count; i++) - { - Caller caller = phonebook[i]; - - xmlwriter.SetValue("phonebook", string.Format("callerID{0}", i.ToString()), caller.ID); - xmlwriter.SetValue("phonebook", string.Format("name{0}", i.ToString()), caller.Name); - xmlwriter.SetValueAsBool("phonebook", string.Format("show{0}", i.ToString()), caller.Show); - } + _showNotify = false; } - } - - public static void UpdateTo0220() - { - char[] charSeparators = new char[] { ';' }; - - using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) + else { - string[] strLCallerId = xmlreader.GetValueAsString("fritzbox", "phonebookCallerId", "").Split(charSeparators, StringSplitOptions.RemoveEmptyEntries); - string[] strLName = xmlreader.GetValueAsString("fritzbox", "phonebookName", "").Split(charSeparators, StringSplitOptions.RemoveEmptyEntries); - string[] strLShow = xmlreader.GetValueAsString("fritzbox", "phonebookShow", "").Split(charSeparators, StringSplitOptions.RemoveEmptyEntries); - - for (int i = 0; i <= strLCallerId.GetUpperBound(0); i++) - { - Caller caller = new Caller(strLCallerId[i], strLName[i], bool.Parse(strLShow[i])); - phonebook.Add(caller); - - if (_extensiveLogging) - Log.Debug("FRITZ!Box: caller loaded: {0} {1} {2}", caller.ID, caller.Name, caller.Show); - } + _showNotify = true; } } - - public static int ImportFritzBoxMonitor(string filepath) + void OnStopExternal(Process proc, bool waitForExit) { - try - { - int count = 0; + _showNotify = true; - // Create an instance of StreamReader to read from a file. - // The using statement also closes the StreamReader. - using (StreamReader sr = new StreamReader(filepath)) - { - string line; - // Read and display lines from the file until the end of - // the file is reached. - while ((line = sr.ReadLine()) != null) - { - if ( (count == 0) && line.Contains("sep=;") ) - continue; - if ( (count == 0) && line.Contains("Telefonnummer")) - continue; + //for (int i = 0; i < notifyQueue.Count; i++) + // OnFritzBoxEvent(notifyQueue[i]); - string[] ar = line.Split(char.Parse(";")); - - ar[0] = ar[0].TrimStart('!'); - ar[1] = ar[1].TrimStart('!'); - - Caller caller = new Caller(); - - caller.ID = ar[2]; - caller.Name = string.Format("{0} {1}", ar[0], ar[1]); - caller.Name = caller.Name.Trim(); - caller.Show = true; - - if (CallerExists(caller)) continue; - - phonebook.Add(caller); - count++; - } - } - - return count; - } - catch (Exception e) - { - // Let the user know what went wrong. - Log.Error("The file could not be read: {0}", e.Message); - return 0; - } + notifyQueue.Clear(); } - public static bool CallerExists(Caller caller) - { - for (int i = 0; i < phonebook.Count; i++) - { - if (phonebook[i].ID == caller.ID) - return true; - } - return false; - } - #endregion - - #region FritzBoxActions - - public void OnCallAction(CallAction callAction) + void OnCallAction(CallAction callAction) { - LogAction(callAction); - if (!_showNotify) { Log.Info("External process is running. Notify is queued and will be shown later."); @@ -319,7 +197,7 @@ switch (callAction.type) { case CallAction.CallType.Incoming: - callAction.caller = GetCallerFromPhonebook(callAction.caller); + callAction.caller = phoneBook.GetCaller(callAction.caller); OnIncomingCall(callAction); break; case CallAction.CallType.Outgoing: @@ -347,7 +225,7 @@ if (tempNotify != null) { Log.Info("yet another dialog is active. action is sent to queue."); - if (actionList.Count < FritzBoxWatch.maxNotifies - 1) + if (actionList.Count < maxNotifies - 1) actionList.Add(callAction); return; } @@ -356,7 +234,7 @@ string strHeading = String.Empty; string strImage = String.Empty; string strText = String.Empty; - + // Set Heading for NotifyDialog if (_showMsnOnHeading) strHeading = GUILocalizeStrings.Get(1023) + " on " + callAction.msn; // ???? Incoming call on @@ -365,7 +243,7 @@ // Set Image for NotifyDialog strImage = GetCallerImage(callAction.caller); - + // Set MessageText for NotifyDialog if (callAction.caller.ID == "") strText = GUILocalizeStrings.Get(2014); // 2014 = unknown @@ -375,7 +253,7 @@ strText = callAction.caller.Name; //config settings for dialog FINISHED - + //if msn is disabled, stop here if (!IsMsnEnabled(callAction.msn)) return; @@ -387,47 +265,143 @@ #endregion - #region Helper Methods + #region Settings - Caller GetCallerFromPhonebook(Caller caller) + private void LoadSettings() { - if (caller.ID == "") return caller; + char[] charSeparators = new char[] { ';' }; - if (phonebook.Count == 0) + if (_extensiveLogging) + Log.Info("FRITZ!Box: LoadSettings"); + + using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) { - Log.Info("Phonebook is empty. Caller is added to the phonebook."); - phonebook.Add(caller); - } - else - { - bool foundCaller = false; - for (int i = 0; i < phonebook.Count; i++) + _lastVersion = xmlreader.GetValueAsInt("fritzbox", "lastVersion", 0); + + fritzBoxAddress = xmlreader.GetValueAsString("fritzbox", "address", "fritz.box"); + fritzBoxPort = xmlreader.GetValueAsInt("fritzbox", "port", 1012); + + _extensiveLogging = xmlreader.GetValueAsBool("fritzbox", "extensiveLogging", false); + + // notify settings + maxNotifies = xmlreader.GetValueAsInt("fritzbox", "maxNotifies", 20); + _closeOnTimeout = xmlreader.GetValueAsBool("fritzbox", "closeOnTimeout", false); + _timeout = xmlreader.GetValueAsInt("fritzbox", "timeout", 10); + _closeOnConnectionClosed = xmlreader.GetValueAsBool("fritzbox", "closeOnConnectionClosed", true); + + if ((!_closeOnTimeout) || (_timeout == 0)) + _timeout = -1; + + _filterMSNs = xmlreader.GetValueAsBool("fritzbox", "filterMSNs", false); + string strMSN = xmlreader.GetValueAsString("fritzbox", "MSN", ""); + _msnList.AddRange(strMSN.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)); + + if (_extensiveLogging) + Log.Debug("FRITZ!Box: MSNs loaded: {0}", strMSN); + + _showMsnOnHeading = xmlreader.GetValueAsBool("fritzbox", "showMsnOnHeading", false); + + // media settings + _stopMedia = xmlreader.GetValueAsBool("fritzbox", "stopMedia", true); + _resumeMedia = xmlreader.GetValueAsBool("fritzbox", "resumeMedia", true); + + // phonebook settings + _usePhonebook = xmlreader.GetValueAsBool("fritzbox", "usePhonebook", true); + if (_usePhonebook) { - Caller tempCaller = phonebook[i]; - if (tempCaller.ID == caller.ID) - { - Log.Info("Caller is identified by phonebook as {0}.", tempCaller.Name); - caller = tempCaller; - foundCaller = true; - } - if (foundCaller) break; + phoneBook = new PhoneBook(); + phoneBook.LoadSettings(); } - if (!foundCaller) + if (_extensiveLogging) { - if (_showUnknownCaller) - caller.Show = true; - else - caller.Show = false; + Log.Info("FRITZ!Box: closeOnTimeout = {0}", _closeOnTimeout.ToString()); + Log.Info("FRITZ!Box: timeout = {0}", _timeout.ToString()); + Log.Info("FRITZ!Box: showMsnOnHeading = {0}", _showMsnOnHeading.ToString()); + //Log.Info("FRITZ!Box: maxNotifies = {0}", FritzBoxWatch.maxNotifies.ToString()); - if (FritzBox._saveUnknownCaller) - phonebook.Add(caller); + Log.Info("FRITZ!Box: stopMedia = {0}", _stopMedia.ToString()); + Log.Info("FRITZ!Box: resumeMedia = {0}", _resumeMedia.ToString()); + + Log.Info("FRITZ!Box: usePhonebook = {0}", _usePhonebook.ToString()); + if (_usePhonebook) + { + Log.Info("FRITZ!Box: showUnknownCaller = {0}", phoneBook.ShowUnknownCaller.ToString()); + Log.Info("FRITZ!Box: saveUnknownCaller = {0}", phoneBook.SaveUnknownCaller.ToString()); + } } } + } - return caller; + private void SaveSettings() + { + if (_extensiveLogging) + Log.Info("FRITZ!Box: SaveSettings"); + + using (MediaPortal.Profile.Settings xmlwriter = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) + { + xmlwriter.SetValue("fritzbox", "lastVersion", _version.Replace(".", string.Empty)); + } + + phoneBook.SaveSettings(); } + #endregion + + #region Helper Methods + + CallAction ParseAction(string dataStream) + { + string[] strList; // splitted data + + dataStream = dataStream.Replace("\n", ""); + if (FritzBox._extensiveLogging) + Log.Info("received data: {0}", dataStream); + strList = dataStream.Split(';'); + + // data-stream can be in following format: + // incoming calls: DateTime;RING;ConnectionID;CallerID;MSN;??POTS??; + // outgoing calls: DateTime;CALL;ConnectionID;??Nebenstelle??;MSN;CallerID;??POTS??; + // connection started: DateTime;CONNECT;ConnectionID;??Nebenstelle??;CallerID; + // connection closed: DateTime;DISCONNECT;ConnectionID;ConnectedTime; + + // DateTime format: + // 12.12.06 12:12:12 + // dd.MM.yy hh:mm:ss + + CallAction callAction = new CallAction(); + + // time when action happens + callAction.time = DateTime.Parse(strList[0]); + + // set the type of the callAction + switch (strList[1]) + { + case "RING": + callAction.type = CallAction.CallType.Incoming; + // sets the callerID + callAction.caller.ID = strList[3]; + callAction.msn = strList[4]; + break; + case "CALL": + callAction.type = CallAction.CallType.Outgoing; + // sets the callerID + callAction.caller.ID = strList[5]; + callAction.msn = strList[4]; + break; + case "CONNECT": + callAction.type = CallAction.CallType.ConnectionStarted; + // sets the callerID + callAction.caller.ID = strList[4]; + break; + case "DISCONNECT": + callAction.type = CallAction.CallType.ConnectionClosed; + break; + } + + return callAction; + } + string GetCallerImage(Caller caller) { if (caller.ID == "") @@ -490,7 +464,7 @@ void ShowNotify(string strHeading, string strImage, string strText) { - if (FritzBoxWatch.notifyCount >= FritzBoxWatch.maxNotifies) return; + if (notifyCount >= maxNotifies) return; //show dialog if (g_Player.Playing && !g_Player.Paused && _stopMedia) @@ -521,42 +495,21 @@ } } - public void LogAction(CallAction action) + bool TestConnection() { - Log.Info("CallAction Info:"); - Log.Info(" CallType: {0}", action.type.ToString()); - Log.Info(" Date: {0}", action.time.ToShortDateString()); - Log.Info(" Time: {0}", action.time.ToShortTimeString()); - if (_extensiveLogging) - { - Log.Info(" Caller: {0}", action.caller.ID); - Log.Info(" MSN: {0}", action.msn); - } - } + TcpClient TcpClient; - #endregion - - #region ExternalProcess Actions - - public void OnStartExternal(Process proc, bool waitForExit) - { - if (waitForExit) + try { - _showNotify = false; + TcpClient = new TcpClient(fritzBoxAddress, fritzBoxPort); } - else + catch (Exception) { - _showNotify = true; + return false; } - } - public void OnStopExternal(Process proc, bool waitForExit) - { - _showNotify = true; - //for (int i = 0; i < notifyQueue.Count; i++) - // OnFritzBoxEvent(notifyQueue[i]); - - notifyQueue.Clear(); + TcpClient.Close(); + return true; } #endregion @@ -574,13 +527,24 @@ LoadSettings(); Utils.OnStartExternal += new Utils.UtilEventHandler(OnStartExternal); - Utils.OnStopExternal += new Utils.UtilEventHandler(OnStopExternal); - - FritzBoxWatch.FritzBoxAction += new FritzBoxWatch.EventHandler(OnCallAction); - Thread FBWatchThread = new Thread(new ThreadStart(FritzBoxWatch.WatchThread)); - FBWatchThread.Priority = ThreadPriority.BelowNormal; - FBWatchThread.Name = "FRITZ!Box Monitoring"; - FBWatchThread.Start(); + Utils.OnStopExternal += new Utils.UtilEventHandler(OnStopExternal); + + TcpClient tcpClient; + // To get the calling informations, the port 1012 on the FRITZBox have to be opened. + // You can open the port with you phone by calling: #96*5* + // To close the port you can call: #96*4* + + // create a new connection to the FritzBox and listen to the TCP port + tcpClient = new TcpClient(fritzBoxAddress, fritzBoxPort); + + tcpClient.ReceiveBufferSize = 1; + networkStream = tcpClient.GetStream(); + + + Thread FBReceiveThread = new Thread(new ThreadStart(ReceiveThread)); + FBReceiveThread.Priority = ThreadPriority.BelowNormal; + FBReceiveThread.Name = "FRITZ!Box Monitoring"; + FBReceiveThread.Start(); } /// <summary> @@ -588,9 +552,11 @@ /// </summary> public void Stop() { - if (!_fritzBoxDisabled) - FritzBoxWatch.Stop(); + stopThread = true; + Utils.OnStartExternal -= new Utils.UtilEventHandler(OnStartExternal); + Utils.OnStopExternal -= new Utils.UtilEventHandler(OnStopExternal); + SaveSettings(); } Modified: trunk/plugins/FritzBox/FritzBox/FritzBox.csproj =================================================================== --- trunk/plugins/FritzBox/FritzBox/FritzBox.csproj 2008-02-15 23:57:37 UTC (rev 1367) +++ trunk/plugins/FritzBox/FritzBox/FritzBox.csproj 2008-02-16 11:21:06 UTC (rev 1368) @@ -78,7 +78,7 @@ <DependentUpon>FritzBoxSetupFrom.cs</DependentUpon> </Compile> <Compile Include="FritzBox.cs" /> - <Compile Include="FritzBoxWatch.cs" /> + <Compile Include="PhoneBook.cs" /> <Compile Include="Properties\Resources.Designer.cs"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> Modified: trunk/plugins/FritzBox/FritzBox/FritzBoxSetupFrom.cs =================================================================== --- trunk/plugins/FritzBox/FritzBox/FritzBoxSetupFrom.cs 2008-02-15 23:57:37 UTC (rev 1367) +++ trunk/plugins/FritzBox/FritzBox/FritzBoxSetupFrom.cs 2008-02-16 11:21:06 UTC (rev 1368) @@ -19,6 +19,8 @@ { public partial class FritzBoxSetupFrom : Form { + PhoneBook phoneBook; + public FritzBoxSetupFrom() { InitializeComponent(); @@ -66,14 +68,15 @@ // phonebook settings checkBoxUsePhonebook.Checked = xmlreader.GetValueAsBool("fritzbox", "usePhonebook", true); - checkBoxShowUnknownCaller.Checked = xmlreader.GetValueAsBool("fritzbox", "showUnknownCaller", true); - checkBoxSaveUnknownCaller.Checked = xmlreader.GetValueAsBool("fritzbox", "saveUnknownCaller", true); + phoneBook = new PhoneBook(); + phoneBook.LoadSettings(); + checkBoxShowUnknownCaller.Checked = phoneBook.ShowUnknownCaller; + checkBoxSaveUnknownCaller.Checked = phoneBook.SaveUnknownCaller; checkBoxShowUnknownCaller.Enabled = checkBoxUsePhonebook.Checked; checkBoxSaveUnknownCaller.Enabled = checkBoxUsePhonebook.Checked; } - FritzBox.LoadPhonebook(); RefreshDataGridView(); } @@ -111,12 +114,12 @@ // phonebook settings xmlwriter.SetValueAsBool("fritzbox", "usePhonebook", checkBoxUsePhonebook.Checked); - xmlwriter.SetValueAsBool("fritzbox", "showUnknownCaller", checkBoxShowUnknownCaller.Checked); - xmlwriter.SetValueAsBool("fritzbox", "saveUnknownCaller", checkBoxSaveUnknownCaller.Checked); + phoneBook.ShowUnknownCaller = checkBoxShowUnknownCaller.Checked; + phoneBook.SaveUnknownCaller = checkBoxSaveUnknownCaller.Checked; } SaveDataGridView(); - FritzBox.SavePhonebook(); + phoneBook.SaveSettings(); } @@ -327,7 +330,7 @@ { if (openFileDialog.ShowDialog() == DialogResult.OK) { - int count = FritzBox.ImportFritzBoxMonitor(openFileDialog.FileName); + int count = phoneBook.ImportFritzBoxMonitor(openFileDialog.FileName); RefreshDataGridView(); MessageBox.Show("Import done!\nAdded " + count.ToString() + " new CallerIDs to phonebook."); @@ -338,15 +341,15 @@ { dataGridView.Rows.Clear(); - for (int i = 0; i < FritzBox.phonebook.Count; i++) + for (int i = 0; i < phoneBook.Contacts.Count; i++) { - dataGridView.Rows.Add(FritzBox.phonebook[i].ID, FritzBox.phonebook[i].Name, FritzBox.phonebook[i].Show); + dataGridView.Rows.Add(phoneBook.Contacts[i].ID, phoneBook.Contacts[i].Name, phoneBook.Contacts[i].Show); } } private void SaveDataGridView() { - FritzBox.phonebook.Clear(); + phoneBook.Contacts.Clear(); for (int i = 0; i < dataGridView.RowCount - 1; i++) { @@ -356,7 +359,7 @@ caller.Name = dataGridView.Rows[i].Cells[1].Value.ToString(); caller.Show = bool.Parse(dataGridView.Rows[i].Cells[2].Value.ToString()); - FritzBox.phonebook.Add(caller); + phoneBook.Contacts.Add(caller); } } Deleted: trunk/plugins/FritzBox/FritzBox/FritzBoxWatch.cs =================================================================== --- trunk/plugins/FritzBox/FritzBox/FritzBoxWatch.cs 2008-02-15 23:57:37 UTC (rev 1367) +++ trunk/plugins/FritzBox/FritzBox/FritzBoxWatch.cs 2008-02-16 11:21:06 UTC (rev 1368) @@ -1,187 +0,0 @@ -#region Copyright (C) 2005-2007 Team MediaPortal - -/* - * Copyright (C) 2005-2007 Team MediaPortal - * http://www.team-mediaportal.com - * - * This Program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2, or (at your option) - * any later version. - * - * This Program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with GNU Make; see the file COPYING. If not, write to - * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. - * http://www.gnu.org/copyleft/gpl.html - * - */ - -#endregion - -using System; -using System.Windows.Forms; -using System.Collections; -using System.Drawing.Design; -using System.Net; -using System.Net.Sockets; -using System.Text; -using System.IO; -using System.ComponentModel; -using System.Security.Cryptography; -using System.Windows.Forms.Design; -using System.Threading; - -using MediaPortal.GUI.Library; -using MediaPortal.Configuration; - -namespace FritzBox -{ - /// <summary> - /// FritzBoxWatch class - /// </summary> - class FritzBoxWatch - { - public delegate void EventHandler(CallAction callAction); - public static event EventHandler FritzBoxAction = null; - - public static bool stopThread = false; - public static string fritzBoxAddress; // address for the connected fritzbox - public static int fritzBoxPort; // port for the connected fritzbox - public static int maxNotifies = 20; - public static int notifyCount = 0; - - static CallAction currentCallAction; - - public static void WatchThread() - { - try - { - TcpClient tcpClient; - char cChar = '\0'; // latest received byte of NetworkStream - string strLine = ""; // received data - - // To get the calling informations, the port 1012 on the FRITZBox have to be opened. - // You can open the port with you phone by calling: #96*5* - // To close the port you can call: #96*4* - - // create a new connection to the FritzBox and listen to the TCP port - tcpClient = new TcpClient(fritzBoxAddress, fritzBoxPort); - - tcpClient.ReceiveBufferSize = 1; - NetworkStream networkStream = tcpClient.GetStream(); - networkStream.ReadTimeout = 1000; - - while (!stopThread) - { - if (networkStream.DataAvailable) - { - cChar = (char)networkStream.ReadByte(); - strLine += cChar; - - } - if (cChar == '\n') - { - CallAction callAction = ParseAction(strLine); - currentCallAction = callAction; - Thread actionThread = new Thread(new ThreadStart(DoAction)); - actionThread.Name = "FRITZ!Box Monitoring"; - actionThread.Start(); - strLine = ""; - cChar = '\0'; - } - Thread.Sleep(1); - } - - } - catch (Exception ex) - { - Log.Error("error: {0}", ex); - return; - } - } - - static CallAction ParseAction(string dataStream) - { - string[] strList; // splitted data - - dataStream = dataStream.Replace("\n", ""); - if (FritzBox._extensiveLogging) - Log.Info("received data: {0}", dataStream); - strList = dataStream.Split(';'); - - // data-stream can be in following format: - // incoming calls: DateTime;RING;ConnectionID;CallerID;MSN;??POTS??; - // outgoing calls: DateTime;CALL;ConnectionID;??Nebenstelle??;MSN;CallerID;??POTS??; - // connection started: DateTime;CONNECT;ConnectionID;??Nebenstelle??;CallerID; - // connection closed: DateTime;DISCONNECT;ConnectionID;ConnectedTime; - - // DateTime format: - // 12.12.06 12:12:12 - // dd.MM.yy hh:mm:ss - - CallAction callAction = new CallAction(); - - // time when action happens - callAction.time = DateTime.Parse(strList[0]); - - // set the type of the callAction - switch (strList[1]) - { - case "RING": - callAction.type = CallAction.CallType.Incoming; - // sets the callerID - callAction.caller.ID = strList[3]; - callAction.msn = strList[4]; - break; - case "CALL": - callAction.type = CallAction.CallType.Outgoing; - // sets the callerID - callAction.caller.ID = strList[5]; - callAction.msn = strList[4]; - break; - case "CONNECT": - callAction.type = CallAction.CallType.ConnectionStarted; - // sets the callerID - callAction.caller.ID = strList[4]; - break; - case "DISCONNECT": - callAction.type = CallAction.CallType.ConnectionClosed; - break; - } - - return callAction; - } - - static void DoAction() - { - FritzBoxAction(currentCallAction); - } - - public static void Stop() - { - stopThread = true; - } - - public static bool Test() - { - TcpClient TcpClient; - - try - { - TcpClient = new TcpClient(fritzBoxAddress, fritzBoxPort); - } - catch (Exception) - { - return false; - } - - TcpClient.Close(); - return true; - } - } -} \ No newline at end of file Added: trunk/plugins/FritzBox/FritzBox/PhoneBook.cs =================================================================== --- trunk/plugins/FritzBox/FritzBox/PhoneBook.cs (rev 0) +++ trunk/plugins/FritzBox/FritzBox/PhoneBook.cs 2008-02-16 11:21:06 UTC (rev 1368) @@ -0,0 +1,269 @@ +#region Copyright (C) 2005-2007 Team MediaPortal + +/* + * Copyright (C) 2005-2007 Team MediaPortal + * http://www.team-mediaportal.com + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#endregion + +using System; +using System.Collections.Generic; +using System.Text; + + +using MediaPortal.Configuration; +using MediaPortal.Dialogs; +using MediaPortal.GUI.Library; +using MediaPortal.Player; +using MediaPortal.Util; +using System.Text; +using System.IO; + +namespace FritzBox +{ + public class PhoneBook + { + #region variables + + List<Caller> _contacts; + + // phonebook settings + bool _showUnknownCaller; + bool _saveUnknownCaller; + + bool _extensiveLogging; + + #endregion + + #region public properties + + public bool ShowUnknownCaller + { + get { return _showUnknownCaller; } + set { _showUnknownCaller = value; } + } + + public bool SaveUnknownCaller + { + get { return _saveUnknownCaller; } + set { _saveUnknownCaller = value; } + } + + public List<Caller> Contacts + { + get { return _contacts; } + set { _contacts = value; } + } + + #endregion + + #region private methods + + void UpdateTo0220() + { + char[] charSeparators = new char[] { ';' }; + + using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) + { + string[] strLCallerId = xmlreader.GetValueAsString("fritzbox", "phonebookCallerId", "").Split(charSeparators, StringSplitOptions.RemoveEmptyEntries); + string[] strLName = xmlreader.GetValueAsString("fritzbox", "phonebookName", "").Split(charSeparators, StringSplitOptions.RemoveEmptyEntries); + string[] strLShow = xmlreader.GetValueAsString("fritzbox", "phonebookShow", "").Split(charSeparators, StringSplitOptions.RemoveEmptyEntries); + + for (int i = 0; i <= strLCallerId.GetUpperBound(0); i++) + { + Caller caller = new Caller(strLCallerId[i], strLName[i], bool.Parse(strLShow[i])); + _contacts.Add(caller); + + if (_extensiveLogging) + Log.Debug("FRITZ!Box: caller loaded: {0} {1} {2}", caller.ID, caller.Name, caller.Show); + } + } + } + + #endregion + + #region public methods + + public void LoadSettings() + { + using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) + { + _extensiveLogging = xmlreader.GetValueAsBool("fritzbox", "extensiveLogging", false); + + _showUnknownCaller = xmlreader.GetValueAsBool("fritzbox", "showUnknownCaller", true); + _saveUnknownCaller = xmlreader.GetValueAsBool("fritzbox", "saveUnknownCaller", true); + } + + + _contacts = new List<Caller>(); + + if ((FritzBox._lastVersion < 0220) && (!File.Exists(Config.GetFile(Config.Dir.Config, "fritzbox.xml")))) + { + UpdateTo0220(); + return; + } + + using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "fritzbox.xml"))) + { + int countCaller = xmlreader.GetValueAsInt("phonebook", "count", 0); + + for (int i = 0; i < countCaller; i++) + { + Caller caller = new Caller(); + + caller.ID = xmlreader.GetValueAsString("phonebook", string.Format("callerID{0}", i.ToString()), ""); + caller.Name = xmlreader.GetValueAsString("phonebook", string.Format("name{0}", i.ToString()), ""); + caller.Show = xmlreader.GetValueAsBool("phonebook", string.Format("show{0}", i.ToString()), false); + + _contacts.Add(caller); + + if (_extensiveLogging) + Log.Debug("FRITZ!Box: caller loaded: {0} {1} {2}", caller.ID, caller.Name, caller.Show); + } + } + if (_extensiveLogging) + Log.Debug("FRITZ!Box: imported {0} callers", _contacts.Count.ToString()); + } + + public void SaveSettings() + { + using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) + { + xmlreader.SetValueAsBool("fritzbox", "showUnknownCaller", _showUnknownCaller); + xmlreader.SetValueAsBool("fritzbox", "saveUnknownCaller", _saveUnknownCaller); + } + + using (MediaPortal.Profile.Settings xmlwriter = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "fritzbox.xml"))) + { + xmlwriter.SetValue("phonebook", "count", _contacts.Count); + + for (int i = 0; i < _contacts.Count; i++) + { + Caller caller = _contacts[i]; + + xmlwriter.SetValue("phonebook", string.Format("callerID{0}", i.ToString()), caller.ID); + xmlwriter.SetValue("phonebook", string.Format("name{0}", i.ToString()), caller.Name); + xmlwriter.SetValueAsBool("phonebook", string.Format("show{0}", i.ToString()), caller.Show); + } + } + } + + + public int ImportFritzBoxMonitor(string filepath) + { + try + { + int count = 0; + + // Create an instance of StreamReader to read from a file. + // The using statement also closes the StreamReader. + using (StreamReader sr = new StreamReader(filepath)) + { + string line; + // Read and display lines from the file until the end of + // the file is reached. + while ((line = sr.ReadLine()) != null) + { + if ((count == 0) && line.Contains("sep=;")) + continue; + if ((count == 0) && line.Contains("Telefonnummer")) + continue; + + string[] ar = line.Split(char.Parse(";")); + + ar[0] = ar[0].TrimStart('!'); + ar[1] = ar[1].TrimStart('!'); + + Caller caller = new Caller(); + + caller.ID = ar[2]; + caller.Name = string.Format("{0} {1}", ar[0], ar[1]); + caller.Name = caller.Name.Trim(); + caller.Show = true; + + if (CallerExists(caller)) continue; + + _contacts.Add(caller); + count++; + } + } + + return count; + } + catch (Exception e) + { + // Let the user know what went wrong. + Log.Error("The file could not be read: {0}", e.Message); + return 0; + } + } + + public bool CallerExists(Caller caller) + { + for (int i = 0; i < _contacts.Count; i++) + { + if (_contacts[i].ID == caller.ID) + return true; + } + return false; + } + + public Caller GetCaller(Caller caller) + { + if (caller.ID == "") return caller; + + if (_contacts.Count == 0) + { + Log.Info("Phonebook is empty. Caller is added to the phonebook."); + _contacts.Add(caller); + } + else + { + bool foundCaller = false; + for (int i = 0; i < _contacts.Count; i++) + { + Caller tempCaller = _contacts[i]; + if (tempCaller.ID == caller.ID) + { + Log.Info("Caller is identified by phonebook as {0}.", tempCaller.Name); + caller = tempCaller; + foundCaller = true; + } + if (foundCaller) break; + } + + if (!foundCaller) + { + if (_showUnknownCaller) + caller.Show = true; + else + caller.Show = false; + + if (_saveUnknownCaller) + _contacts.Add(caller); + } + } + + return caller; + } + + #endregion + } +} Modified: trunk/plugins/FritzBox/FritzBox/Properties/Resources.Designer.cs =================================================================== --- trunk/plugins/FritzBox/FritzBox/Properties/Resources.Designer.cs 2008-02-15 23:57:37 UTC (rev 1367) +++ trunk/plugins/FritzBox/FritzBox/Properties/Resources.Designer.cs 2008-02-16 11:21:06 UTC (rev 1368) @@ -1,7 +1,7 @@ //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. -// Laufzeitversion:2.0.50727.1318 +// Laufzeitversion:2.0.50727.1433 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |