VivoxVoiceModule.cs 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.IO;
  29. using System.Net;
  30. using System.Text;
  31. using System.Xml;
  32. using System.Collections;
  33. using System.Collections.Generic;
  34. using System.Reflection;
  35. using System.Threading;
  36. using OpenMetaverse;
  37. using log4net;
  38. using Nini.Config;
  39. using Nwc.XmlRpc;
  40. using OpenSim.Framework;
  41. using OpenSim.Framework.Capabilities;
  42. using OpenSim.Framework.Servers;
  43. using OpenSim.Framework.Servers.HttpServer;
  44. using OpenSim.Region.Framework.Interfaces;
  45. using OpenSim.Region.Framework.Scenes;
  46. using Caps = OpenSim.Framework.Capabilities.Caps;
  47. namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice
  48. {
  49. public class VivoxVoiceModule : ISharedRegionModule
  50. {
  51. // channel distance model values
  52. public const int CHAN_DIST_NONE = 0; // no attenuation
  53. public const int CHAN_DIST_INVERSE = 1; // inverse distance attenuation
  54. public const int CHAN_DIST_LINEAR = 2; // linear attenuation
  55. public const int CHAN_DIST_EXPONENT = 3; // exponential attenuation
  56. public const int CHAN_DIST_DEFAULT = CHAN_DIST_LINEAR;
  57. // channel type values
  58. public static readonly string CHAN_TYPE_POSITIONAL = "positional";
  59. public static readonly string CHAN_TYPE_CHANNEL = "channel";
  60. public static readonly string CHAN_TYPE_DEFAULT = CHAN_TYPE_POSITIONAL;
  61. // channel mode values
  62. public static readonly string CHAN_MODE_OPEN = "open";
  63. public static readonly string CHAN_MODE_LECTURE = "lecture";
  64. public static readonly string CHAN_MODE_PRESENTATION = "presentation";
  65. public static readonly string CHAN_MODE_AUDITORIUM = "auditorium";
  66. public static readonly string CHAN_MODE_DEFAULT = CHAN_MODE_OPEN;
  67. // unconstrained default values
  68. public const double CHAN_ROLL_OFF_DEFAULT = 2.0; // rate of attenuation
  69. public const double CHAN_ROLL_OFF_MIN = 1.0;
  70. public const double CHAN_ROLL_OFF_MAX = 4.0;
  71. public const int CHAN_MAX_RANGE_DEFAULT = 80; // distance at which channel is silent
  72. public const int CHAN_MAX_RANGE_MIN = 0;
  73. public const int CHAN_MAX_RANGE_MAX = 160;
  74. public const int CHAN_CLAMPING_DISTANCE_DEFAULT = 10; // distance before attenuation applies
  75. public const int CHAN_CLAMPING_DISTANCE_MIN = 0;
  76. public const int CHAN_CLAMPING_DISTANCE_MAX = 160;
  77. // Infrastructure
  78. private static readonly ILog m_log =
  79. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  80. private static readonly Object vlock = new Object();
  81. // Capability strings
  82. private static readonly string m_parcelVoiceInfoRequestPath = "0107/";
  83. private static readonly string m_provisionVoiceAccountRequestPath = "0108/";
  84. private static readonly string m_chatSessionRequestPath = "0109/";
  85. // Control info, e.g. vivox server, admin user, admin password
  86. private static bool m_pluginEnabled = false;
  87. private static bool m_adminConnected = false;
  88. private static string m_vivoxServer;
  89. private static string m_vivoxSipUri;
  90. private static string m_vivoxVoiceAccountApi;
  91. private static string m_vivoxAdminUser;
  92. private static string m_vivoxAdminPassword;
  93. private static string m_authToken = String.Empty;
  94. private static int m_vivoxChannelDistanceModel;
  95. private static double m_vivoxChannelRollOff;
  96. private static int m_vivoxChannelMaximumRange;
  97. private static string m_vivoxChannelMode;
  98. private static string m_vivoxChannelType;
  99. private static int m_vivoxChannelClampingDistance;
  100. private static Dictionary<string,string> m_parents = new Dictionary<string,string>();
  101. private static bool m_dumpXml;
  102. private IConfig m_config;
  103. public void Initialise(IConfigSource config)
  104. {
  105. m_config = config.Configs["VivoxVoice"];
  106. if (null == m_config)
  107. return;
  108. if (!m_config.GetBoolean("enabled", false))
  109. return;
  110. try
  111. {
  112. // retrieve configuration variables
  113. m_vivoxServer = m_config.GetString("vivox_server", String.Empty);
  114. m_vivoxSipUri = m_config.GetString("vivox_sip_uri", String.Empty);
  115. m_vivoxAdminUser = m_config.GetString("vivox_admin_user", String.Empty);
  116. m_vivoxAdminPassword = m_config.GetString("vivox_admin_password", String.Empty);
  117. m_vivoxChannelDistanceModel = m_config.GetInt("vivox_channel_distance_model", CHAN_DIST_DEFAULT);
  118. m_vivoxChannelRollOff = m_config.GetDouble("vivox_channel_roll_off", CHAN_ROLL_OFF_DEFAULT);
  119. m_vivoxChannelMaximumRange = m_config.GetInt("vivox_channel_max_range", CHAN_MAX_RANGE_DEFAULT);
  120. m_vivoxChannelMode = m_config.GetString("vivox_channel_mode", CHAN_MODE_DEFAULT).ToLower();
  121. m_vivoxChannelType = m_config.GetString("vivox_channel_type", CHAN_TYPE_DEFAULT).ToLower();
  122. m_vivoxChannelClampingDistance = m_config.GetInt("vivox_channel_clamping_distance",
  123. CHAN_CLAMPING_DISTANCE_DEFAULT);
  124. m_dumpXml = m_config.GetBoolean("dump_xml", false);
  125. // Validate against constraints and default if necessary
  126. if (m_vivoxChannelRollOff < CHAN_ROLL_OFF_MIN || m_vivoxChannelRollOff > CHAN_ROLL_OFF_MAX)
  127. {
  128. m_log.WarnFormat("[VivoxVoice] Invalid value for roll off ({0}), reset to {1}.",
  129. m_vivoxChannelRollOff, CHAN_ROLL_OFF_DEFAULT);
  130. m_vivoxChannelRollOff = CHAN_ROLL_OFF_DEFAULT;
  131. }
  132. if (m_vivoxChannelMaximumRange < CHAN_MAX_RANGE_MIN || m_vivoxChannelMaximumRange > CHAN_MAX_RANGE_MAX)
  133. {
  134. m_log.WarnFormat("[VivoxVoice] Invalid value for maximum range ({0}), reset to {1}.",
  135. m_vivoxChannelMaximumRange, CHAN_MAX_RANGE_DEFAULT);
  136. m_vivoxChannelMaximumRange = CHAN_MAX_RANGE_DEFAULT;
  137. }
  138. if (m_vivoxChannelClampingDistance < CHAN_CLAMPING_DISTANCE_MIN ||
  139. m_vivoxChannelClampingDistance > CHAN_CLAMPING_DISTANCE_MAX)
  140. {
  141. m_log.WarnFormat("[VivoxVoice] Invalid value for clamping distance ({0}), reset to {1}.",
  142. m_vivoxChannelClampingDistance, CHAN_CLAMPING_DISTANCE_DEFAULT);
  143. m_vivoxChannelClampingDistance = CHAN_CLAMPING_DISTANCE_DEFAULT;
  144. }
  145. switch (m_vivoxChannelMode)
  146. {
  147. case "open" : break;
  148. case "lecture" : break;
  149. case "presentation" : break;
  150. case "auditorium" : break;
  151. default :
  152. m_log.WarnFormat("[VivoxVoice] Invalid value for channel mode ({0}), reset to {1}.",
  153. m_vivoxChannelMode, CHAN_MODE_DEFAULT);
  154. m_vivoxChannelMode = CHAN_MODE_DEFAULT;
  155. break;
  156. }
  157. switch (m_vivoxChannelType)
  158. {
  159. case "positional" : break;
  160. case "channel" : break;
  161. default :
  162. m_log.WarnFormat("[VivoxVoice] Invalid value for channel type ({0}), reset to {1}.",
  163. m_vivoxChannelType, CHAN_TYPE_DEFAULT);
  164. m_vivoxChannelType = CHAN_TYPE_DEFAULT;
  165. break;
  166. }
  167. m_vivoxVoiceAccountApi = String.Format("http://{0}/api2", m_vivoxServer);
  168. // Admin interface required values
  169. if (String.IsNullOrEmpty(m_vivoxServer) ||
  170. String.IsNullOrEmpty(m_vivoxSipUri) ||
  171. String.IsNullOrEmpty(m_vivoxAdminUser) ||
  172. String.IsNullOrEmpty(m_vivoxAdminPassword))
  173. {
  174. m_log.Error("[VivoxVoice] plugin mis-configured");
  175. m_log.Info("[VivoxVoice] plugin disabled: incomplete configuration");
  176. return;
  177. }
  178. m_log.InfoFormat("[VivoxVoice] using vivox server {0}", m_vivoxServer);
  179. // Get admin rights and cleanup any residual channel definition
  180. DoAdminLogin();
  181. m_pluginEnabled = true;
  182. m_log.Info("[VivoxVoice] plugin enabled");
  183. }
  184. catch (Exception e)
  185. {
  186. m_log.ErrorFormat("[VivoxVoice] plugin initialization failed: {0}", e.Message);
  187. m_log.DebugFormat("[VivoxVoice] plugin initialization failed: {0}", e.ToString());
  188. return;
  189. }
  190. }
  191. // Called to indicate that the module has been added to the region
  192. public void AddRegion(Scene scene)
  193. {
  194. if (m_pluginEnabled)
  195. {
  196. lock (vlock)
  197. {
  198. string channelId;
  199. string sceneUUID = scene.RegionInfo.RegionID.ToString();
  200. string sceneName = scene.RegionInfo.RegionName;
  201. // Make sure that all local channels are deleted.
  202. // So we have to search for the children, and then do an
  203. // iteration over the set of chidren identified.
  204. // This assumes that there is just one directory per
  205. // region.
  206. if (VivoxTryGetDirectory(sceneUUID + "D", out channelId))
  207. {
  208. m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}",
  209. sceneName, sceneUUID, channelId);
  210. XmlElement children = VivoxListChildren(channelId);
  211. string count;
  212. if (XmlFind(children, "response.level0.channel-search.count", out count))
  213. {
  214. int cnum = Convert.ToInt32(count);
  215. for (int i = 0; i < cnum; i++)
  216. {
  217. string id;
  218. if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id))
  219. {
  220. if (!IsOK(VivoxDeleteChannel(channelId, id)))
  221. m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id);
  222. }
  223. }
  224. }
  225. }
  226. else
  227. {
  228. if (!VivoxTryCreateDirectory(sceneUUID + "D", sceneName, out channelId))
  229. {
  230. m_log.WarnFormat("[VivoxVoice] Create failed <{0}:{1}:{2}>",
  231. "*", sceneUUID, sceneName);
  232. channelId = String.Empty;
  233. }
  234. }
  235. // Create a dictionary entry unconditionally. This eliminates the
  236. // need to check for a parent in the core code. The end result is
  237. // the same, if the parent table entry is an empty string, then
  238. // region channels will be created as first-level channels.
  239. lock (m_parents)
  240. if (m_parents.ContainsKey(sceneUUID))
  241. {
  242. RemoveRegion(scene);
  243. m_parents.Add(sceneUUID, channelId);
  244. }
  245. else
  246. {
  247. m_parents.Add(sceneUUID, channelId);
  248. }
  249. }
  250. // we need to capture scene in an anonymous method
  251. // here as we need it later in the callbacks
  252. scene.EventManager.OnRegisterCaps += delegate(UUID agentID, Caps caps)
  253. {
  254. OnRegisterCaps(scene, agentID, caps);
  255. };
  256. }
  257. }
  258. // Called to indicate that all loadable modules have now been added
  259. public void RegionLoaded(Scene scene)
  260. {
  261. // Do nothing.
  262. }
  263. // Called to indicate that the region is going away.
  264. public void RemoveRegion(Scene scene)
  265. {
  266. if (m_pluginEnabled)
  267. {
  268. lock (vlock)
  269. {
  270. string channelId;
  271. string sceneUUID = scene.RegionInfo.RegionID.ToString();
  272. string sceneName = scene.RegionInfo.RegionName;
  273. // Make sure that all local channels are deleted.
  274. // So we have to search for the children, and then do an
  275. // iteration over the set of chidren identified.
  276. // This assumes that there is just one directory per
  277. // region.
  278. if (VivoxTryGetDirectory(sceneUUID + "D", out channelId))
  279. {
  280. m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}",
  281. sceneName, sceneUUID, channelId);
  282. XmlElement children = VivoxListChildren(channelId);
  283. string count;
  284. if (XmlFind(children, "response.level0.channel-search.count", out count))
  285. {
  286. int cnum = Convert.ToInt32(count);
  287. for (int i = 0; i < cnum; i++)
  288. {
  289. string id;
  290. if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id))
  291. {
  292. if (!IsOK(VivoxDeleteChannel(channelId, id)))
  293. m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id);
  294. }
  295. }
  296. }
  297. }
  298. if (!IsOK(VivoxDeleteChannel(null, channelId)))
  299. m_log.WarnFormat("[VivoxVoice] Parent channel delete failed {0}:{1}:{2}", sceneName, sceneUUID, channelId);
  300. // Remove the channel umbrella entry
  301. lock (m_parents)
  302. {
  303. if (m_parents.ContainsKey(sceneUUID))
  304. {
  305. m_parents.Remove(sceneUUID);
  306. }
  307. }
  308. }
  309. }
  310. }
  311. public void PostInitialise()
  312. {
  313. // Do nothing.
  314. }
  315. public void Close()
  316. {
  317. if (m_pluginEnabled)
  318. VivoxLogout();
  319. }
  320. public Type ReplaceableInterface
  321. {
  322. get { return null; }
  323. }
  324. public string Name
  325. {
  326. get { return "VivoxVoiceModule"; }
  327. }
  328. public bool IsSharedModule
  329. {
  330. get { return true; }
  331. }
  332. // <summary>
  333. // OnRegisterCaps is invoked via the scene.EventManager
  334. // everytime OpenSim hands out capabilities to a client
  335. // (login, region crossing). We contribute two capabilities to
  336. // the set of capabilities handed back to the client:
  337. // ProvisionVoiceAccountRequest and ParcelVoiceInfoRequest.
  338. //
  339. // ProvisionVoiceAccountRequest allows the client to obtain
  340. // the voice account credentials for the avatar it is
  341. // controlling (e.g., user name, password, etc).
  342. //
  343. // ParcelVoiceInfoRequest is invoked whenever the client
  344. // changes from one region or parcel to another.
  345. //
  346. // Note that OnRegisterCaps is called here via a closure
  347. // delegate containing the scene of the respective region (see
  348. // Initialise()).
  349. // </summary>
  350. public void OnRegisterCaps(Scene scene, UUID agentID, Caps caps)
  351. {
  352. m_log.DebugFormat("[VivoxVoice] OnRegisterCaps: agentID {0} caps {1}", agentID, caps);
  353. string capsBase = "/CAPS/" + caps.CapsObjectPath;
  354. caps.RegisterHandler("ProvisionVoiceAccountRequest",
  355. new RestStreamHandler("POST", capsBase + m_provisionVoiceAccountRequestPath,
  356. delegate(string request, string path, string param,
  357. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  358. {
  359. return ProvisionVoiceAccountRequest(scene, request, path, param,
  360. agentID, caps);
  361. }));
  362. caps.RegisterHandler("ParcelVoiceInfoRequest",
  363. new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath,
  364. delegate(string request, string path, string param,
  365. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  366. {
  367. return ParcelVoiceInfoRequest(scene, request, path, param,
  368. agentID, caps);
  369. }));
  370. caps.RegisterHandler("ChatSessionRequest",
  371. new RestStreamHandler("POST", capsBase + m_chatSessionRequestPath,
  372. delegate(string request, string path, string param,
  373. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  374. {
  375. return ChatSessionRequest(scene, request, path, param,
  376. agentID, caps);
  377. }));
  378. }
  379. /// <summary>
  380. /// Callback for a client request for Voice Account Details
  381. /// </summary>
  382. /// <param name="scene">current scene object of the client</param>
  383. /// <param name="request"></param>
  384. /// <param name="path"></param>
  385. /// <param name="param"></param>
  386. /// <param name="agentID"></param>
  387. /// <param name="caps"></param>
  388. /// <returns></returns>
  389. public string ProvisionVoiceAccountRequest(Scene scene, string request, string path, string param,
  390. UUID agentID, Caps caps)
  391. {
  392. try
  393. {
  394. ScenePresence avatar = null;
  395. string avatarName = null;
  396. if (scene == null) throw new Exception("[VivoxVoice][PROVISIONVOICE] Invalid scene");
  397. avatar = scene.GetScenePresence(agentID);
  398. while (avatar == null)
  399. {
  400. Thread.Sleep(100);
  401. avatar = scene.GetScenePresence(agentID);
  402. }
  403. avatarName = avatar.Name;
  404. m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: scene = {0}, agentID = {1}", scene, agentID);
  405. m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}",
  406. request, path, param);
  407. XmlElement resp;
  408. bool retry = false;
  409. string agentname = "x" + Convert.ToBase64String(agentID.GetBytes());
  410. string password = new UUID(Guid.NewGuid()).ToString().Replace('-','Z').Substring(0,16);
  411. string code = String.Empty;
  412. agentname = agentname.Replace('+', '-').Replace('/', '_');
  413. do
  414. {
  415. resp = VivoxGetAccountInfo(agentname);
  416. if (XmlFind(resp, "response.level0.status", out code))
  417. {
  418. if (code != "OK")
  419. {
  420. if (XmlFind(resp, "response.level0.body.code", out code))
  421. {
  422. // If the request was recognized, then this should be set to something
  423. switch (code)
  424. {
  425. case "201" : // Account expired
  426. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : expired credentials",
  427. avatarName);
  428. m_adminConnected = false;
  429. retry = DoAdminLogin();
  430. break;
  431. case "202" : // Missing credentials
  432. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : missing credentials",
  433. avatarName);
  434. break;
  435. case "212" : // Not authorized
  436. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : not authorized",
  437. avatarName);
  438. break;
  439. case "300" : // Required parameter missing
  440. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : parameter missing",
  441. avatarName);
  442. break;
  443. case "403" : // Account does not exist
  444. resp = VivoxCreateAccount(agentname,password);
  445. // Note: This REALLY MUST BE status. Create Account does not return code.
  446. if (XmlFind(resp, "response.level0.status", out code))
  447. {
  448. switch (code)
  449. {
  450. case "201" : // Account expired
  451. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : expired credentials",
  452. avatarName);
  453. m_adminConnected = false;
  454. retry = DoAdminLogin();
  455. break;
  456. case "202" : // Missing credentials
  457. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : missing credentials",
  458. avatarName);
  459. break;
  460. case "212" : // Not authorized
  461. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : not authorized",
  462. avatarName);
  463. break;
  464. case "300" : // Required parameter missing
  465. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : parameter missing",
  466. avatarName);
  467. break;
  468. case "400" : // Create failed
  469. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : create failed",
  470. avatarName);
  471. break;
  472. }
  473. }
  474. break;
  475. case "404" : // Failed to retrieve account
  476. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : retrieve failed");
  477. // [AMW] Sleep and retry for a fixed period? Or just abandon?
  478. break;
  479. }
  480. }
  481. }
  482. }
  483. } while (retry);
  484. if (code != "OK")
  485. {
  486. m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: Get Account Request failed for \"{0}\"", avatarName);
  487. throw new Exception("Unable to execute request");
  488. }
  489. // Unconditionally change the password on each request
  490. VivoxPassword(agentname, password);
  491. LLSDVoiceAccountResponse voiceAccountResponse =
  492. new LLSDVoiceAccountResponse(agentname, password, m_vivoxSipUri, m_vivoxVoiceAccountApi);
  493. string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse);
  494. m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: avatar \"{0}\": {1}", avatarName, r);
  495. return r;
  496. }
  497. catch (Exception e)
  498. {
  499. m_log.ErrorFormat("[VivoxVoice][PROVISIONVOICE]: : {0}, retry later", e.Message);
  500. m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: : {0} failed", e.ToString());
  501. return "<llsd><undef /></llsd>";
  502. }
  503. }
  504. /// <summary>
  505. /// Callback for a client request for ParcelVoiceInfo
  506. /// </summary>
  507. /// <param name="scene">current scene object of the client</param>
  508. /// <param name="request"></param>
  509. /// <param name="path"></param>
  510. /// <param name="param"></param>
  511. /// <param name="agentID"></param>
  512. /// <param name="caps"></param>
  513. /// <returns></returns>
  514. public string ParcelVoiceInfoRequest(Scene scene, string request, string path, string param,
  515. UUID agentID, Caps caps)
  516. {
  517. ScenePresence avatar = scene.GetScenePresence(agentID);
  518. string avatarName = avatar.Name;
  519. // - check whether we have a region channel in our cache
  520. // - if not:
  521. // create it and cache it
  522. // - send it to the client
  523. // - send channel_uri: as "sip:regionID@m_sipDomain"
  524. try
  525. {
  526. LLSDParcelVoiceInfoResponse parcelVoiceInfo;
  527. string channel_uri;
  528. if (null == scene.LandChannel)
  529. throw new Exception(String.Format("region \"{0}\": avatar \"{1}\": land data not yet available",
  530. scene.RegionInfo.RegionName, avatarName));
  531. // get channel_uri: check first whether estate
  532. // settings allow voice, then whether parcel allows
  533. // voice, if all do retrieve or obtain the parcel
  534. // voice channel
  535. LandData land = scene.GetLandData(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y);
  536. m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": request: {4}, path: {5}, param: {6}",
  537. scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, request, path, param);
  538. // m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: avatar \"{0}\": location: {1} {2} {3}",
  539. // avatarName, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, avatar.AbsolutePosition.Z);
  540. // TODO: EstateSettings don't seem to get propagated...
  541. if (!scene.RegionInfo.EstateSettings.AllowVoice)
  542. {
  543. m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": voice not enabled in estate settings",
  544. scene.RegionInfo.RegionName);
  545. channel_uri = String.Empty;
  546. }
  547. if ((land.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0)
  548. {
  549. m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": voice not enabled for parcel",
  550. scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName);
  551. channel_uri = String.Empty;
  552. }
  553. else
  554. {
  555. channel_uri = RegionGetOrCreateChannel(scene, land);
  556. }
  557. // fill in our response to the client
  558. Hashtable creds = new Hashtable();
  559. creds["channel_uri"] = channel_uri;
  560. parcelVoiceInfo = new LLSDParcelVoiceInfoResponse(scene.RegionInfo.RegionName, land.LocalID, creds);
  561. string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo);
  562. m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": {4}",
  563. scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, r);
  564. return r;
  565. }
  566. catch (Exception e)
  567. {
  568. m_log.ErrorFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2}, retry later",
  569. scene.RegionInfo.RegionName, avatarName, e.Message);
  570. m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2} failed",
  571. scene.RegionInfo.RegionName, avatarName, e.ToString());
  572. return "<llsd><undef /></llsd>";
  573. }
  574. }
  575. /// <summary>
  576. /// Callback for a client request for a private chat channel
  577. /// </summary>
  578. /// <param name="scene">current scene object of the client</param>
  579. /// <param name="request"></param>
  580. /// <param name="path"></param>
  581. /// <param name="param"></param>
  582. /// <param name="agentID"></param>
  583. /// <param name="caps"></param>
  584. /// <returns></returns>
  585. public string ChatSessionRequest(Scene scene, string request, string path, string param,
  586. UUID agentID, Caps caps)
  587. {
  588. ScenePresence avatar = scene.GetScenePresence(agentID);
  589. string avatarName = avatar.Name;
  590. m_log.DebugFormat("[VivoxVoice][CHATSESSION]: avatar \"{0}\": request: {1}, path: {2}, param: {3}",
  591. avatarName, request, path, param);
  592. return "<llsd>true</llsd>";
  593. }
  594. private string RegionGetOrCreateChannel(Scene scene, LandData land)
  595. {
  596. string channelUri = null;
  597. string channelId = null;
  598. string landUUID;
  599. string landName;
  600. string parentId;
  601. lock (m_parents) parentId = m_parents[scene.RegionInfo.RegionID.ToString()];
  602. // Create parcel voice channel. If no parcel exists, then the voice channel ID is the same
  603. // as the directory ID. Otherwise, it reflects the parcel's ID.
  604. if (land.LocalID != 1 && (land.Flags & (uint)ParcelFlags.UseEstateVoiceChan) == 0)
  605. {
  606. landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, land.Name);
  607. landUUID = land.GlobalID.ToString();
  608. m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}",
  609. landName, land.LocalID, landUUID);
  610. }
  611. else
  612. {
  613. landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionName);
  614. landUUID = scene.RegionInfo.RegionID.ToString();
  615. m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}",
  616. landName, land.LocalID, landUUID);
  617. }
  618. lock (vlock)
  619. {
  620. // Added by Adam to help debug channel not availible errors.
  621. if (VivoxTryGetChannel(parentId, landUUID, out channelId, out channelUri))
  622. m_log.DebugFormat("[VivoxVoice] Found existing channel at " + channelUri);
  623. else if (VivoxTryCreateChannel(parentId, landUUID, landName, out channelUri))
  624. m_log.DebugFormat("[VivoxVoice] Created new channel at " + channelUri);
  625. else
  626. throw new Exception("vivox channel uri not available");
  627. m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parent channel id {1}: retrieved parcel channel_uri {2} ",
  628. landName, parentId, channelUri);
  629. }
  630. return channelUri;
  631. }
  632. private static readonly string m_vivoxLoginPath = "http://{0}/api2/viv_signin.php?userid={1}&pwd={2}";
  633. /// <summary>
  634. /// Perform administrative login for Vivox.
  635. /// Returns a hash table containing values returned from the request.
  636. /// </summary>
  637. private XmlElement VivoxLogin(string name, string password)
  638. {
  639. string requrl = String.Format(m_vivoxLoginPath, m_vivoxServer, name, password);
  640. return VivoxCall(requrl, false);
  641. }
  642. private static readonly string m_vivoxLogoutPath = "http://{0}/api2/viv_signout.php?auth_token={1}";
  643. /// <summary>
  644. /// Perform administrative logout for Vivox.
  645. /// </summary>
  646. private XmlElement VivoxLogout()
  647. {
  648. string requrl = String.Format(m_vivoxLogoutPath, m_vivoxServer, m_authToken);
  649. return VivoxCall(requrl, false);
  650. }
  651. private static readonly string m_vivoxGetAccountPath = "http://{0}/api2/viv_get_acct.php?auth_token={1}&user_name={2}";
  652. /// <summary>
  653. /// Retrieve account information for the specified user.
  654. /// Returns a hash table containing values returned from the request.
  655. /// </summary>
  656. private XmlElement VivoxGetAccountInfo(string user)
  657. {
  658. string requrl = String.Format(m_vivoxGetAccountPath, m_vivoxServer, m_authToken, user);
  659. return VivoxCall(requrl, true);
  660. }
  661. private static readonly string m_vivoxNewAccountPath = "http://{0}/api2/viv_adm_acct_new.php?username={1}&pwd={2}&auth_token={3}";
  662. /// <summary>
  663. /// Creates a new account.
  664. /// For now we supply the minimum set of values, which
  665. /// is user name and password. We *can* supply a lot more
  666. /// demographic data.
  667. /// </summary>
  668. private XmlElement VivoxCreateAccount(string user, string password)
  669. {
  670. string requrl = String.Format(m_vivoxNewAccountPath, m_vivoxServer, user, password, m_authToken);
  671. return VivoxCall(requrl, true);
  672. }
  673. private static readonly string m_vivoxPasswordPath = "http://{0}/api2/viv_adm_password.php?user_name={1}&new_pwd={2}&auth_token={3}";
  674. /// <summary>
  675. /// Change the user's password.
  676. /// </summary>
  677. private XmlElement VivoxPassword(string user, string password)
  678. {
  679. string requrl = String.Format(m_vivoxPasswordPath, m_vivoxServer, user, password, m_authToken);
  680. return VivoxCall(requrl, true);
  681. }
  682. private static readonly string m_vivoxChannelPath = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_name={2}&auth_token={3}";
  683. /// <summary>
  684. /// Create a channel.
  685. /// Once again, there a multitude of options possible. In the simplest case
  686. /// we specify only the name and get a non-persistent cannel in return. Non
  687. /// persistent means that the channel gets deleted if no-one uses it for
  688. /// 5 hours. To accomodate future requirements, it may be a good idea to
  689. /// initially create channels under the umbrella of a parent ID based upon
  690. /// the region name. That way we have a context for side channels, if those
  691. /// are required in a later phase.
  692. ///
  693. /// In this case the call handles parent and description as optional values.
  694. /// </summary>
  695. private bool VivoxTryCreateChannel(string parent, string channelId, string description, out string channelUri)
  696. {
  697. string requrl = String.Format(m_vivoxChannelPath, m_vivoxServer, "create", channelId, m_authToken);
  698. if (parent != null && parent != String.Empty)
  699. {
  700. requrl = String.Format("{0}&chan_parent={1}", requrl, parent);
  701. }
  702. if (description != null && description != String.Empty)
  703. {
  704. requrl = String.Format("{0}&chan_desc={1}", requrl, description);
  705. }
  706. requrl = String.Format("{0}&chan_type={1}", requrl, m_vivoxChannelType);
  707. requrl = String.Format("{0}&chan_mode={1}", requrl, m_vivoxChannelMode);
  708. requrl = String.Format("{0}&chan_roll_off={1}", requrl, m_vivoxChannelRollOff);
  709. requrl = String.Format("{0}&chan_dist_model={1}", requrl, m_vivoxChannelDistanceModel);
  710. requrl = String.Format("{0}&chan_max_range={1}", requrl, m_vivoxChannelMaximumRange);
  711. requrl = String.Format("{0}&chan_ckamping_distance={1}", requrl, m_vivoxChannelClampingDistance);
  712. XmlElement resp = VivoxCall(requrl, true);
  713. if (XmlFind(resp, "response.level0.body.chan_uri", out channelUri))
  714. return true;
  715. channelUri = String.Empty;
  716. return false;
  717. }
  718. /// <summary>
  719. /// Create a directory.
  720. /// Create a channel with an unconditional type of "dir" (indicating directory).
  721. /// This is used to create an arbitrary name tree for partitioning of the
  722. /// channel name space.
  723. /// The parent and description are optional values.
  724. /// </summary>
  725. private bool VivoxTryCreateDirectory(string dirId, string description, out string channelId)
  726. {
  727. string requrl = String.Format(m_vivoxChannelPath, m_vivoxServer, "create", dirId, m_authToken);
  728. // if (parent != null && parent != String.Empty)
  729. // {
  730. // requrl = String.Format("{0}&chan_parent={1}", requrl, parent);
  731. // }
  732. if (description != null && description != String.Empty)
  733. {
  734. requrl = String.Format("{0}&chan_desc={1}", requrl, description);
  735. }
  736. requrl = String.Format("{0}&chan_type={1}", requrl, "dir");
  737. XmlElement resp = VivoxCall(requrl, true);
  738. if (IsOK(resp) && XmlFind(resp, "response.level0.body.chan_id", out channelId))
  739. return true;
  740. channelId = String.Empty;
  741. return false;
  742. }
  743. private static readonly string m_vivoxChannelSearchPath = "http://{0}/api2/viv_chan_search.php?cond_channame={1}&auth_token={2}";
  744. /// <summary>
  745. /// Retrieve a channel.
  746. /// Once again, there a multitude of options possible. In the simplest case
  747. /// we specify only the name and get a non-persistent cannel in return. Non
  748. /// persistent means that the channel gets deleted if no-one uses it for
  749. /// 5 hours. To accomodate future requirements, it may be a good idea to
  750. /// initially create channels under the umbrella of a parent ID based upon
  751. /// the region name. That way we have a context for side channels, if those
  752. /// are required in a later phase.
  753. /// In this case the call handles parent and description as optional values.
  754. /// </summary>
  755. private bool VivoxTryGetChannel(string channelParent, string channelName,
  756. out string channelId, out string channelUri)
  757. {
  758. string count;
  759. string requrl = String.Format(m_vivoxChannelSearchPath, m_vivoxServer, channelName, m_authToken);
  760. XmlElement resp = VivoxCall(requrl, true);
  761. if (XmlFind(resp, "response.level0.channel-search.count", out count))
  762. {
  763. int channels = Convert.ToInt32(count);
  764. // Bug in Vivox Server r2978 where count returns 0
  765. // Found by Adam
  766. if (channels == 0)
  767. {
  768. for (int j=0;j<100;j++)
  769. {
  770. string tmpId;
  771. if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", j, out tmpId))
  772. break;
  773. channels = j + 1;
  774. }
  775. }
  776. for (int i = 0; i < channels; i++)
  777. {
  778. string name;
  779. string id;
  780. string type;
  781. string uri;
  782. string parent;
  783. // skip if not a channel
  784. if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.type", i, out type) ||
  785. (type != "channel" && type != "positional_M"))
  786. {
  787. m_log.Debug("[VivoxVoice] Skipping Channel " + i + " as it's not a channel.");
  788. continue;
  789. }
  790. // skip if not the name we are looking for
  791. if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.name", i, out name) ||
  792. name != channelName)
  793. {
  794. m_log.Debug("[VivoxVoice] Skipping Channel " + i + " as it has no name.");
  795. continue;
  796. }
  797. // skip if parent does not match
  798. if (channelParent != null && !XmlFind(resp, "response.level0.channel-search.channels.channels.level4.parent", i, out parent))
  799. {
  800. m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it's parent doesnt match");
  801. continue;
  802. }
  803. // skip if no channel id available
  804. if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", i, out id))
  805. {
  806. m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it has no channel ID");
  807. continue;
  808. }
  809. // skip if no channel uri available
  810. if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.uri", i, out uri))
  811. {
  812. m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it has no channel URI");
  813. continue;
  814. }
  815. channelId = id;
  816. channelUri = uri;
  817. return true;
  818. }
  819. }
  820. else
  821. {
  822. m_log.Debug("[VivoxVoice] No count element?");
  823. }
  824. channelId = String.Empty;
  825. channelUri = String.Empty;
  826. // Useful incase something goes wrong.
  827. //m_log.Debug("[VivoxVoice] Could not find channel in XMLRESP: " + resp.InnerXml);
  828. return false;
  829. }
  830. private bool VivoxTryGetDirectory(string directoryName, out string directoryId)
  831. {
  832. string count;
  833. string requrl = String.Format(m_vivoxChannelSearchPath, m_vivoxServer, directoryName, m_authToken);
  834. XmlElement resp = VivoxCall(requrl, true);
  835. if (XmlFind(resp, "response.level0.channel-search.count", out count))
  836. {
  837. int channels = Convert.ToInt32(count);
  838. for (int i = 0; i < channels; i++)
  839. {
  840. string name;
  841. string id;
  842. string type;
  843. // skip if not a directory
  844. if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.type", i, out type) ||
  845. type != "dir")
  846. continue;
  847. // skip if not the name we are looking for
  848. if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.name", i, out name) ||
  849. name != directoryName)
  850. continue;
  851. // skip if no channel id available
  852. if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", i, out id))
  853. continue;
  854. directoryId = id;
  855. return true;
  856. }
  857. }
  858. directoryId = String.Empty;
  859. return false;
  860. }
  861. // private static readonly string m_vivoxChannelById = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}";
  862. // private XmlElement VivoxGetChannelById(string parent, string channelid)
  863. // {
  864. // string requrl = String.Format(m_vivoxChannelById, m_vivoxServer, "get", channelid, m_authToken);
  865. // if (parent != null && parent != String.Empty)
  866. // return VivoxGetChild(parent, channelid);
  867. // else
  868. // return VivoxCall(requrl, true);
  869. // }
  870. /// <summary>
  871. /// Delete a channel.
  872. /// Once again, there a multitude of options possible. In the simplest case
  873. /// we specify only the name and get a non-persistent cannel in return. Non
  874. /// persistent means that the channel gets deleted if no-one uses it for
  875. /// 5 hours. To accomodate future requirements, it may be a good idea to
  876. /// initially create channels under the umbrella of a parent ID based upon
  877. /// the region name. That way we have a context for side channels, if those
  878. /// are required in a later phase.
  879. /// In this case the call handles parent and description as optional values.
  880. /// </summary>
  881. private static readonly string m_vivoxChannelDel = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}";
  882. private XmlElement VivoxDeleteChannel(string parent, string channelid)
  883. {
  884. string requrl = String.Format(m_vivoxChannelDel, m_vivoxServer, "delete", channelid, m_authToken);
  885. if (parent != null && parent != String.Empty)
  886. {
  887. requrl = String.Format("{0}&chan_parent={1}", requrl, parent);
  888. }
  889. return VivoxCall(requrl, true);
  890. }
  891. /// <summary>
  892. /// Return information on channels in the given directory
  893. /// </summary>
  894. private static readonly string m_vivoxChannelSearch = "http://{0}/api2/viv_chan_search.php?&cond_chanparent={1}&auth_token={2}";
  895. private XmlElement VivoxListChildren(string channelid)
  896. {
  897. string requrl = String.Format(m_vivoxChannelSearch, m_vivoxServer, channelid, m_authToken);
  898. return VivoxCall(requrl, true);
  899. }
  900. // private XmlElement VivoxGetChild(string parent, string child)
  901. // {
  902. // XmlElement children = VivoxListChildren(parent);
  903. // string count;
  904. // if (XmlFind(children, "response.level0.channel-search.count", out count))
  905. // {
  906. // int cnum = Convert.ToInt32(count);
  907. // for (int i = 0; i < cnum; i++)
  908. // {
  909. // string name;
  910. // string id;
  911. // if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.name", i, out name))
  912. // {
  913. // if (name == child)
  914. // {
  915. // if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id))
  916. // {
  917. // return VivoxGetChannelById(null, id);
  918. // }
  919. // }
  920. // }
  921. // }
  922. // }
  923. // // One we *know* does not exist.
  924. // return VivoxGetChannel(null, Guid.NewGuid().ToString());
  925. // }
  926. /// <summary>
  927. /// This method handles the WEB side of making a request over the
  928. /// Vivox interface. The returned values are tansferred to a has
  929. /// table which is returned as the result.
  930. /// The outcome of the call can be determined by examining the
  931. /// status value in the hash table.
  932. /// </summary>
  933. private XmlElement VivoxCall(string requrl, bool admin)
  934. {
  935. XmlDocument doc = null;
  936. // If this is an admin call, and admin is not connected,
  937. // and the admin id cannot be connected, then fail.
  938. if (admin && !m_adminConnected && !DoAdminLogin())
  939. return null;
  940. doc = new XmlDocument();
  941. try
  942. {
  943. // Otherwise prepare the request
  944. m_log.DebugFormat("[VivoxVoice] Sending request <{0}>", requrl);
  945. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requrl);
  946. HttpWebResponse rsp = null;
  947. // We are sending just parameters, no content
  948. req.ContentLength = 0;
  949. // Send request and retrieve the response
  950. rsp = (HttpWebResponse)req.GetResponse();
  951. XmlTextReader rdr = new XmlTextReader(rsp.GetResponseStream());
  952. doc.Load(rdr);
  953. rdr.Close();
  954. }
  955. catch (Exception e)
  956. {
  957. m_log.ErrorFormat("[VivoxVoice] Error in admin call : {0}", e.Message);
  958. }
  959. // If we're debugging server responses, dump the whole
  960. // load now
  961. if (m_dumpXml) XmlScanl(doc.DocumentElement,0);
  962. return doc.DocumentElement;
  963. }
  964. /// <summary>
  965. /// Just say if it worked.
  966. /// </summary>
  967. private bool IsOK(XmlElement resp)
  968. {
  969. string status;
  970. XmlFind(resp, "response.level0.status", out status);
  971. return (status == "OK");
  972. }
  973. /// <summary>
  974. /// Login has been factored in this way because it gets called
  975. /// from several places in the module, and we want it to work
  976. /// the same way each time.
  977. /// </summary>
  978. private bool DoAdminLogin()
  979. {
  980. m_log.Debug("[VivoxVoice] Establishing admin connection");
  981. lock (vlock)
  982. {
  983. if (!m_adminConnected)
  984. {
  985. string status = "Unknown";
  986. XmlElement resp = null;
  987. resp = VivoxLogin(m_vivoxAdminUser, m_vivoxAdminPassword);
  988. if (XmlFind(resp, "response.level0.body.status", out status))
  989. {
  990. if (status == "Ok")
  991. {
  992. m_log.Info("[VivoxVoice] Admin connection established");
  993. if (XmlFind(resp, "response.level0.body.auth_token", out m_authToken))
  994. {
  995. if (m_dumpXml) m_log.DebugFormat("[VivoxVoice] Auth Token <{0}>",
  996. m_authToken);
  997. m_adminConnected = true;
  998. }
  999. }
  1000. else
  1001. {
  1002. m_log.WarnFormat("[VivoxVoice] Admin connection failed, status = {0}",
  1003. status);
  1004. }
  1005. }
  1006. }
  1007. }
  1008. return m_adminConnected;
  1009. }
  1010. /// <summary>
  1011. /// The XmlScan routine is provided to aid in the
  1012. /// reverse engineering of incompletely
  1013. /// documented packets returned by the Vivox
  1014. /// voice server. It is only called if the
  1015. /// m_dumpXml switch is set.
  1016. /// </summary>
  1017. private void XmlScanl(XmlElement e, int index)
  1018. {
  1019. if (e.HasChildNodes)
  1020. {
  1021. m_log.DebugFormat("<{0}>".PadLeft(index+5), e.Name);
  1022. XmlNodeList children = e.ChildNodes;
  1023. foreach (XmlNode node in children)
  1024. switch (node.NodeType)
  1025. {
  1026. case XmlNodeType.Element :
  1027. XmlScanl((XmlElement)node, index+1);
  1028. break;
  1029. case XmlNodeType.Text :
  1030. m_log.DebugFormat("\"{0}\"".PadLeft(index+5), node.Value);
  1031. break;
  1032. default :
  1033. break;
  1034. }
  1035. m_log.DebugFormat("</{0}>".PadLeft(index+6), e.Name);
  1036. }
  1037. else
  1038. {
  1039. m_log.DebugFormat("<{0}/>".PadLeft(index+6), e.Name);
  1040. }
  1041. }
  1042. private static readonly char[] C_POINT = {'.'};
  1043. /// <summary>
  1044. /// The Find method is passed an element whose
  1045. /// inner text is scanned in an attempt to match
  1046. /// the name hierarchy passed in the 'tag' parameter.
  1047. /// If the whole hierarchy is resolved, the InnerText
  1048. /// value at that point is returned. Note that this
  1049. /// may itself be a subhierarchy of the entire
  1050. /// document. The function returns a boolean indicator
  1051. /// of the search's success. The search is performed
  1052. /// by the recursive Search method.
  1053. /// </summary>
  1054. private bool XmlFind(XmlElement root, string tag, int nth, out string result)
  1055. {
  1056. if (root == null || tag == null || tag == String.Empty)
  1057. {
  1058. result = String.Empty;
  1059. return false;
  1060. }
  1061. return XmlSearch(root,tag.Split(C_POINT),0, ref nth, out result);
  1062. }
  1063. private bool XmlFind(XmlElement root, string tag, out string result)
  1064. {
  1065. int nth = 0;
  1066. if (root == null || tag == null || tag == String.Empty)
  1067. {
  1068. result = String.Empty;
  1069. return false;
  1070. }
  1071. return XmlSearch(root,tag.Split(C_POINT),0, ref nth, out result);
  1072. }
  1073. /// <summary>
  1074. /// XmlSearch is initially called by XmlFind, and then
  1075. /// recursively called by itself until the document
  1076. /// supplied to XmlFind is either exhausted or the name hierarchy
  1077. /// is matched.
  1078. ///
  1079. /// If the hierarchy is matched, the value is returned in
  1080. /// result, and true returned as the function's
  1081. /// value. Otherwise the result is set to the empty string and
  1082. /// false is returned.
  1083. /// </summary>
  1084. private bool XmlSearch(XmlElement e, string[] tags, int index, ref int nth, out string result)
  1085. {
  1086. if (index == tags.Length || e.Name != tags[index])
  1087. {
  1088. result = String.Empty;
  1089. return false;
  1090. }
  1091. if (tags.Length-index == 1)
  1092. {
  1093. if (nth == 0)
  1094. {
  1095. result = e.InnerText;
  1096. return true;
  1097. }
  1098. else
  1099. {
  1100. nth--;
  1101. result = String.Empty;
  1102. return false;
  1103. }
  1104. }
  1105. if (e.HasChildNodes)
  1106. {
  1107. XmlNodeList children = e.ChildNodes;
  1108. foreach (XmlNode node in children)
  1109. {
  1110. switch (node.NodeType)
  1111. {
  1112. case XmlNodeType.Element :
  1113. if (XmlSearch((XmlElement)node, tags, index+1, ref nth, out result))
  1114. return true;
  1115. break;
  1116. default :
  1117. break;
  1118. }
  1119. }
  1120. }
  1121. result = String.Empty;
  1122. return false;
  1123. }
  1124. }
  1125. }