VivoxVoiceModule.cs 58 KB

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