VivoxVoiceModule.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  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.Communications.Cache;
  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. public class VivoxVoiceModule : ISharedRegionModule
  51. {
  52. // channel distance model values
  53. public const int CHAN_DIST_NONE = 0; // no attenuation
  54. public const int CHAN_DIST_INVERSE = 1; // inverse distance attenuation
  55. public const int CHAN_DIST_LINEAR = 2; // linear attenuation
  56. public const int CHAN_DIST_EXPONENT = 3; // exponential attenuation
  57. public const int CHAN_DIST_DEFAULT = CHAN_DIST_LINEAR;
  58. // channel type values
  59. public static readonly string CHAN_TYPE_POSITIONAL = "positional";
  60. public static readonly string CHAN_TYPE_CHANNEL = "channel";
  61. public static readonly string CHAN_TYPE_DEFAULT = CHAN_TYPE_POSITIONAL;
  62. // channel mode values
  63. public static readonly string CHAN_MODE_OPEN = "open";
  64. public static readonly string CHAN_MODE_LECTURE = "lecture";
  65. public static readonly string CHAN_MODE_PRESENTATION = "presentation";
  66. public static readonly string CHAN_MODE_AUDITORIUM = "auditorium";
  67. public static readonly string CHAN_MODE_DEFAULT = CHAN_MODE_OPEN;
  68. // unconstrained default values
  69. public const double CHAN_ROLL_OFF_DEFAULT = 2.0; // rate of attenuation
  70. public const double CHAN_ROLL_OFF_MIN = 1.0;
  71. public const double CHAN_ROLL_OFF_MAX = 4.0;
  72. public const int CHAN_MAX_RANGE_DEFAULT = 80; // distance at which channel is silent
  73. public const int CHAN_MAX_RANGE_MIN = 0;
  74. public const int CHAN_MAX_RANGE_MAX = 160;
  75. public const int CHAN_CLAMPING_DISTANCE_DEFAULT = 10; // distance before attenuation applies
  76. public const int CHAN_CLAMPING_DISTANCE_MIN = 0;
  77. public const int CHAN_CLAMPING_DISTANCE_MAX = 160;
  78. // Infrastructure
  79. private static readonly ILog m_log =
  80. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  81. private static readonly Object vlock = new Object();
  82. // Capability strings
  83. private static readonly string m_parcelVoiceInfoRequestPath = "0107/";
  84. private static readonly string m_provisionVoiceAccountRequestPath = "0108/";
  85. private static readonly string m_chatSessionRequestPath = "0109/";
  86. // Control info, e.g. vivox server, admin user, admin password
  87. private static bool m_pluginEnabled = false;
  88. private static bool m_adminConnected = false;
  89. private static string m_vivoxServer;
  90. private static string m_vivoxSipUri;
  91. private static string m_vivoxVoiceAccountApi;
  92. private static string m_vivoxAdminUser;
  93. private static string m_vivoxAdminPassword;
  94. private static string m_authToken = String.Empty;
  95. private static int m_vivoxChannelDistanceModel;
  96. private static double m_vivoxChannelRollOff;
  97. private static int m_vivoxChannelMaximumRange;
  98. private static string m_vivoxChannelMode;
  99. private static string m_vivoxChannelType;
  100. private static int m_vivoxChannelClampingDistance;
  101. private static Dictionary<string,string> m_parents = new Dictionary<string,string>();
  102. private static bool m_dumpXml;
  103. private IConfig m_config;
  104. public void Initialise(IConfigSource config)
  105. {
  106. m_config = config.Configs["VivoxVoice"];
  107. if (null == m_config)
  108. {
  109. m_log.Info("[VivoxVoice] no config found, plugin disabled");
  110. return;
  111. }
  112. if (!m_config.GetBoolean("enabled", false))
  113. {
  114. m_log.Info("[VivoxVoice] plugin disabled by configuration");
  115. return;
  116. }
  117. try
  118. {
  119. // retrieve configuration variables
  120. m_vivoxServer = m_config.GetString("vivox_server", String.Empty);
  121. m_vivoxSipUri = m_config.GetString("vivox_sip_uri", String.Empty);
  122. m_vivoxAdminUser = m_config.GetString("vivox_admin_user", String.Empty);
  123. m_vivoxAdminPassword = m_config.GetString("vivox_admin_password", String.Empty);
  124. m_vivoxChannelDistanceModel = m_config.GetInt("vivox_channel_distance_model", CHAN_DIST_DEFAULT);
  125. m_vivoxChannelRollOff = m_config.GetDouble("vivox_channel_roll_off", CHAN_ROLL_OFF_DEFAULT);
  126. m_vivoxChannelMaximumRange = m_config.GetInt("vivox_channel_max_range", CHAN_MAX_RANGE_DEFAULT);
  127. m_vivoxChannelMode = m_config.GetString("vivox_channel_mode", CHAN_MODE_DEFAULT).ToLower();
  128. m_vivoxChannelType = m_config.GetString("vivox_channel_type", CHAN_TYPE_DEFAULT).ToLower();
  129. m_vivoxChannelClampingDistance = m_config.GetInt("vivox_channel_clamping_distance",
  130. CHAN_CLAMPING_DISTANCE_DEFAULT);
  131. m_dumpXml = m_config.GetBoolean("dump_xml", false);
  132. // Validate against constraints and default if necessary
  133. if (m_vivoxChannelRollOff < CHAN_ROLL_OFF_MIN || m_vivoxChannelRollOff > CHAN_ROLL_OFF_MAX)
  134. {
  135. m_log.WarnFormat("[VivoxVoice] Invalid value for roll off ({0}), reset to {1}.",
  136. m_vivoxChannelRollOff, CHAN_ROLL_OFF_DEFAULT);
  137. m_vivoxChannelRollOff = CHAN_ROLL_OFF_DEFAULT;
  138. }
  139. if (m_vivoxChannelMaximumRange < CHAN_MAX_RANGE_MIN || m_vivoxChannelMaximumRange > CHAN_MAX_RANGE_MAX)
  140. {
  141. m_log.WarnFormat("[VivoxVoice] Invalid value for maximum range ({0}), reset to {1}.",
  142. m_vivoxChannelMaximumRange, CHAN_MAX_RANGE_DEFAULT);
  143. m_vivoxChannelMaximumRange = CHAN_MAX_RANGE_DEFAULT;
  144. }
  145. if (m_vivoxChannelClampingDistance < CHAN_CLAMPING_DISTANCE_MIN ||
  146. m_vivoxChannelClampingDistance > CHAN_CLAMPING_DISTANCE_MAX)
  147. {
  148. m_log.WarnFormat("[VivoxVoice] Invalid value for clamping distance ({0}), reset to {1}.",
  149. m_vivoxChannelClampingDistance, CHAN_CLAMPING_DISTANCE_DEFAULT);
  150. m_vivoxChannelClampingDistance = CHAN_CLAMPING_DISTANCE_DEFAULT;
  151. }
  152. switch (m_vivoxChannelMode)
  153. {
  154. case "open" : break;
  155. case "lecture" : break;
  156. case "presentation" : break;
  157. case "auditorium" : break;
  158. default :
  159. m_log.WarnFormat("[VivoxVoice] Invalid value for channel mode ({0}), reset to {1}.",
  160. m_vivoxChannelMode, CHAN_MODE_DEFAULT);
  161. m_vivoxChannelMode = CHAN_MODE_DEFAULT;
  162. break;
  163. }
  164. switch (m_vivoxChannelType)
  165. {
  166. case "positional" : break;
  167. case "channel" : break;
  168. default :
  169. m_log.WarnFormat("[VivoxVoice] Invalid value for channel type ({0}), reset to {1}.",
  170. m_vivoxChannelType, CHAN_TYPE_DEFAULT);
  171. m_vivoxChannelType = CHAN_TYPE_DEFAULT;
  172. break;
  173. }
  174. m_vivoxVoiceAccountApi = String.Format("http://{0}/api2", m_vivoxServer);
  175. // Admin interface required values
  176. if (String.IsNullOrEmpty(m_vivoxServer) ||
  177. String.IsNullOrEmpty(m_vivoxSipUri) ||
  178. String.IsNullOrEmpty(m_vivoxAdminUser) ||
  179. String.IsNullOrEmpty(m_vivoxAdminPassword))
  180. {
  181. m_log.Error("[VivoxVoice] plugin mis-configured");
  182. m_log.Info("[VivoxVoice] plugin disabled: incomplete configuration");
  183. return;
  184. }
  185. m_log.InfoFormat("[VivoxVoice] using vivox server {0}", m_vivoxServer);
  186. // Get admin rights and cleanup any residual channel definition
  187. DoAdminLogin();
  188. m_pluginEnabled = true;
  189. m_log.Info("[VivoxVoice] plugin enabled");
  190. }
  191. catch (Exception e)
  192. {
  193. m_log.ErrorFormat("[VivoxVoice] plugin initialization failed: {0}", e.Message);
  194. m_log.DebugFormat("[VivoxVoice] plugin initialization failed: {0}", e.ToString());
  195. return;
  196. }
  197. }
  198. // Called to indicate that the module has been added to the region
  199. public void AddRegion(Scene scene)
  200. {
  201. if (m_pluginEnabled)
  202. {
  203. lock (vlock)
  204. {
  205. string channelId;
  206. string sceneUUID = scene.RegionInfo.RegionID.ToString();
  207. string sceneName = scene.RegionInfo.RegionName;
  208. // Make sure that all local channels are deleted.
  209. // So we have to search for the children, and then do an
  210. // iteration over the set of chidren identified.
  211. // This assumes that there is just one directory per
  212. // region.
  213. if (VivoxTryGetDirectory(sceneUUID + "D", out channelId))
  214. {
  215. m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}",
  216. sceneName, sceneUUID, channelId);
  217. XmlElement children = VivoxListChildren(channelId);
  218. string count;
  219. if (XmlFind(children, "response.level0.channel-search.count", out count))
  220. {
  221. int cnum = Convert.ToInt32(count);
  222. for (int i = 0; i < cnum; i++)
  223. {
  224. string id;
  225. if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id))
  226. {
  227. if (!IsOK(VivoxDeleteChannel(channelId, id)))
  228. m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id);
  229. }
  230. }
  231. }
  232. }
  233. else
  234. {
  235. if (!VivoxTryCreateDirectory(sceneUUID + "D", sceneName, out channelId))
  236. {
  237. m_log.WarnFormat("[VivoxVoice] Create failed <{0}:{1}:{2}>",
  238. "*", sceneUUID, sceneName);
  239. channelId = String.Empty;
  240. }
  241. }
  242. // Create a dictionary entry unconditionally. This eliminates the
  243. // need to check for a parent in the core code. The end result is
  244. // the same, if the parent table entry is an empty string, then
  245. // region channels will be created as first-level channels.
  246. lock (m_parents)
  247. if (m_parents.ContainsKey(sceneUUID))
  248. {
  249. RemoveRegion(scene);
  250. m_parents.Add(sceneUUID, channelId);
  251. }
  252. else
  253. {
  254. m_parents.Add(sceneUUID, channelId);
  255. }
  256. }
  257. // we need to capture scene in an anonymous method
  258. // here as we need it later in the callbacks
  259. scene.EventManager.OnRegisterCaps += delegate(UUID agentID, Caps caps)
  260. {
  261. OnRegisterCaps(scene, agentID, caps);
  262. };
  263. }
  264. }
  265. // Called to indicate that all loadable modules have now been added
  266. public void RegionLoaded(Scene scene)
  267. {
  268. // Do nothing.
  269. }
  270. // Called to indicate that the region is going away.
  271. public void RemoveRegion(Scene scene)
  272. {
  273. if (m_pluginEnabled)
  274. {
  275. lock (vlock)
  276. {
  277. string channelId;
  278. string sceneUUID = scene.RegionInfo.RegionID.ToString();
  279. string sceneName = scene.RegionInfo.RegionName;
  280. // Make sure that all local channels are deleted.
  281. // So we have to search for the children, and then do an
  282. // iteration over the set of chidren identified.
  283. // This assumes that there is just one directory per
  284. // region.
  285. if (VivoxTryGetDirectory(sceneUUID + "D", out channelId))
  286. {
  287. m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}",
  288. sceneName, sceneUUID, channelId);
  289. XmlElement children = VivoxListChildren(channelId);
  290. string count;
  291. if (XmlFind(children, "response.level0.channel-search.count", out count))
  292. {
  293. int cnum = Convert.ToInt32(count);
  294. for (int i = 0; i < cnum; i++)
  295. {
  296. string id;
  297. if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id))
  298. {
  299. if (!IsOK(VivoxDeleteChannel(channelId, id)))
  300. m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id);
  301. }
  302. }
  303. }
  304. }
  305. if (!IsOK(VivoxDeleteChannel(null, channelId)))
  306. m_log.WarnFormat("[VivoxVoice] Parent channel delete failed {0}:{1}:{2}", sceneName, sceneUUID, channelId);
  307. // Remove the channel umbrella entry
  308. lock (m_parents)
  309. {
  310. if (m_parents.ContainsKey(sceneUUID))
  311. {
  312. m_parents.Remove(sceneUUID);
  313. }
  314. }
  315. }
  316. }
  317. }
  318. public void PostInitialise()
  319. {
  320. // Do nothing.
  321. }
  322. public void Close()
  323. {
  324. if (m_pluginEnabled)
  325. VivoxLogout();
  326. }
  327. public Type ReplaceableInterface
  328. {
  329. get { return null; }
  330. }
  331. public string Name
  332. {
  333. get { return "VivoxVoiceModule"; }
  334. }
  335. public bool IsSharedModule
  336. {
  337. get { return true; }
  338. }
  339. // <summary>
  340. // OnRegisterCaps is invoked via the scene.EventManager
  341. // everytime OpenSim hands out capabilities to a client
  342. // (login, region crossing). We contribute two capabilities to
  343. // the set of capabilities handed back to the client:
  344. // ProvisionVoiceAccountRequest and ParcelVoiceInfoRequest.
  345. //
  346. // ProvisionVoiceAccountRequest allows the client to obtain
  347. // the voice account credentials for the avatar it is
  348. // controlling (e.g., user name, password, etc).
  349. //
  350. // ParcelVoiceInfoRequest is invoked whenever the client
  351. // changes from one region or parcel to another.
  352. //
  353. // Note that OnRegisterCaps is called here via a closure
  354. // delegate containing the scene of the respective region (see
  355. // Initialise()).
  356. // </summary>
  357. public void OnRegisterCaps(Scene scene, UUID agentID, Caps caps)
  358. {
  359. m_log.DebugFormat("[VivoxVoice] OnRegisterCaps: agentID {0} caps {1}", agentID, caps);
  360. string capsBase = "/CAPS/" + caps.CapsObjectPath;
  361. caps.RegisterHandler("ProvisionVoiceAccountRequest",
  362. new RestStreamHandler("POST", capsBase + m_provisionVoiceAccountRequestPath,
  363. delegate(string request, string path, string param,
  364. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  365. {
  366. return ProvisionVoiceAccountRequest(scene, request, path, param,
  367. agentID, caps);
  368. }));
  369. caps.RegisterHandler("ParcelVoiceInfoRequest",
  370. new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath,
  371. delegate(string request, string path, string param,
  372. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  373. {
  374. return ParcelVoiceInfoRequest(scene, request, path, param,
  375. agentID, caps);
  376. }));
  377. caps.RegisterHandler("ChatSessionRequest",
  378. new RestStreamHandler("POST", capsBase + m_chatSessionRequestPath,
  379. delegate(string request, string path, string param,
  380. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  381. {
  382. return ChatSessionRequest(scene, request, path, param,
  383. agentID, caps);
  384. }));
  385. }
  386. /// <summary>
  387. /// Callback for a client request for Voice Account Details
  388. /// </summary>
  389. /// <param name="scene">current scene object of the client</param>
  390. /// <param name="request"></param>
  391. /// <param name="path"></param>
  392. /// <param name="param"></param>
  393. /// <param name="agentID"></param>
  394. /// <param name="caps"></param>
  395. /// <returns></returns>
  396. public string ProvisionVoiceAccountRequest(Scene scene, string request, string path, string param,
  397. UUID agentID, Caps caps)
  398. {
  399. try
  400. {
  401. ScenePresence avatar = null;
  402. string avatarName = null;
  403. if (scene == null) throw new Exception("[VivoxVoice][PROVISIONVOICE] Invalid scene");
  404. avatar = scene.GetScenePresence(agentID);
  405. while (avatar == null)
  406. {
  407. Thread.Sleep(100);
  408. avatar = scene.GetScenePresence(agentID);
  409. }
  410. avatarName = avatar.Name;
  411. m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: scene = {0}, agentID = {1}", scene, agentID);
  412. m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}",
  413. request, path, param);
  414. XmlElement resp;
  415. bool retry = false;
  416. string agentname = "x" + Convert.ToBase64String(agentID.GetBytes());
  417. string password = new UUID(Guid.NewGuid()).ToString().Replace('-','Z').Substring(0,16);
  418. string code = String.Empty;
  419. agentname = agentname.Replace('+', '-').Replace('/', '_');
  420. do
  421. {
  422. resp = VivoxGetAccountInfo(agentname);
  423. if (XmlFind(resp, "response.level0.status", out code))
  424. {
  425. if (code != "OK")
  426. {
  427. if (XmlFind(resp, "response.level0.body.code", out code))
  428. {
  429. // If the request was recognized, then this should be set to something
  430. switch (code)
  431. {
  432. case "201" : // Account expired
  433. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : expired credentials",
  434. avatarName);
  435. m_adminConnected = false;
  436. retry = DoAdminLogin();
  437. break;
  438. case "202" : // Missing credentials
  439. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : missing credentials",
  440. avatarName);
  441. break;
  442. case "212" : // Not authorized
  443. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : not authorized",
  444. avatarName);
  445. break;
  446. case "300" : // Required parameter missing
  447. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : parameter missing",
  448. avatarName);
  449. break;
  450. case "403" : // Account does not exist
  451. resp = VivoxCreateAccount(agentname,password);
  452. // Note: This REALLY MUST BE status. Create Account does not return code.
  453. if (XmlFind(resp, "response.level0.status", out code))
  454. {
  455. switch (code)
  456. {
  457. case "201" : // Account expired
  458. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : expired credentials",
  459. avatarName);
  460. m_adminConnected = false;
  461. retry = DoAdminLogin();
  462. break;
  463. case "202" : // Missing credentials
  464. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : missing credentials",
  465. avatarName);
  466. break;
  467. case "212" : // Not authorized
  468. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : not authorized",
  469. avatarName);
  470. break;
  471. case "300" : // Required parameter missing
  472. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : parameter missing",
  473. avatarName);
  474. break;
  475. case "400" : // Create failed
  476. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : create failed",
  477. avatarName);
  478. break;
  479. }
  480. }
  481. break;
  482. case "404" : // Failed to retrieve account
  483. m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : retrieve failed");
  484. // [AMW] Sleep and retry for a fixed period? Or just abandon?
  485. break;
  486. }
  487. }
  488. }
  489. }
  490. } while (retry);
  491. if (code != "OK")
  492. {
  493. m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: Get Account Request failed for \"{0}\"", avatarName);
  494. throw new Exception("Unable to execute request");
  495. }
  496. // Unconditionally change the password on each request
  497. VivoxPassword(agentname, password);
  498. LLSDVoiceAccountResponse voiceAccountResponse =
  499. new LLSDVoiceAccountResponse(agentname, password, m_vivoxSipUri, m_vivoxVoiceAccountApi);
  500. string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse);
  501. m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: avatar \"{0}\": {1}", avatarName, r);
  502. return r;
  503. }
  504. catch (Exception e)
  505. {
  506. m_log.ErrorFormat("[VivoxVoice][PROVISIONVOICE]: : {0}, retry later", e.Message);
  507. m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: : {0} failed", e.ToString());
  508. return "<llsd><undef /></llsd>";
  509. }
  510. }
  511. /// <summary>
  512. /// Callback for a client request for ParcelVoiceInfo
  513. /// </summary>
  514. /// <param name="scene">current scene object of the client</param>
  515. /// <param name="request"></param>
  516. /// <param name="path"></param>
  517. /// <param name="param"></param>
  518. /// <param name="agentID"></param>
  519. /// <param name="caps"></param>
  520. /// <returns></returns>
  521. public string ParcelVoiceInfoRequest(Scene scene, string request, string path, string param,
  522. UUID agentID, Caps caps)
  523. {
  524. ScenePresence avatar = scene.GetScenePresence(agentID);
  525. string avatarName = avatar.Name;
  526. // - check whether we have a region channel in our cache
  527. // - if not:
  528. // create it and cache it
  529. // - send it to the client
  530. // - send channel_uri: as "sip:regionID@m_sipDomain"
  531. try
  532. {
  533. LLSDParcelVoiceInfoResponse parcelVoiceInfo;
  534. string channel_uri;
  535. if (null == scene.LandChannel)
  536. throw new Exception(String.Format("region \"{0}\": avatar \"{1}\": land data not yet available",
  537. scene.RegionInfo.RegionName, avatarName));
  538. // get channel_uri: check first whether estate
  539. // settings allow voice, then whether parcel allows
  540. // voice, if all do retrieve or obtain the parcel
  541. // voice channel
  542. LandData land = scene.GetLandData(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y);
  543. m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": request: {4}, path: {5}, param: {6}",
  544. scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, request, path, param);
  545. // m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: avatar \"{0}\": location: {1} {2} {3}",
  546. // avatarName, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, avatar.AbsolutePosition.Z);
  547. // TODO: EstateSettings don't seem to get propagated...
  548. if (!scene.RegionInfo.EstateSettings.AllowVoice)
  549. {
  550. m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": voice not enabled in estate settings",
  551. scene.RegionInfo.RegionName);
  552. channel_uri = String.Empty;
  553. }
  554. if ((land.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0)
  555. {
  556. m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": voice not enabled for parcel",
  557. scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName);
  558. channel_uri = String.Empty;
  559. }
  560. else
  561. {
  562. channel_uri = RegionGetOrCreateChannel(scene, land);
  563. }
  564. // fill in our response to the client
  565. Hashtable creds = new Hashtable();
  566. creds["channel_uri"] = channel_uri;
  567. parcelVoiceInfo = new LLSDParcelVoiceInfoResponse(scene.RegionInfo.RegionName, land.LocalID, creds);
  568. string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo);
  569. m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": {4}",
  570. scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, r);
  571. return r;
  572. }
  573. catch (Exception e)
  574. {
  575. m_log.ErrorFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2}, retry later",
  576. scene.RegionInfo.RegionName, avatarName, e.Message);
  577. m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2} failed",
  578. scene.RegionInfo.RegionName, avatarName, e.ToString());
  579. return "<llsd><undef /></llsd>";
  580. }
  581. }
  582. /// <summary>
  583. /// Callback for a client request for a private chat channel
  584. /// </summary>
  585. /// <param name="scene">current scene object of the client</param>
  586. /// <param name="request"></param>
  587. /// <param name="path"></param>
  588. /// <param name="param"></param>
  589. /// <param name="agentID"></param>
  590. /// <param name="caps"></param>
  591. /// <returns></returns>
  592. public string ChatSessionRequest(Scene scene, string request, string path, string param,
  593. UUID agentID, Caps caps)
  594. {
  595. ScenePresence avatar = scene.GetScenePresence(agentID);
  596. string avatarName = avatar.Name;
  597. m_log.DebugFormat("[VivoxVoice][CHATSESSION]: avatar \"{0}\": request: {1}, path: {2}, param: {3}",
  598. avatarName, request, path, param);
  599. return "<llsd>true</llsd>";
  600. }
  601. private string RegionGetOrCreateChannel(Scene scene, LandData land)
  602. {
  603. string channelUri = null;
  604. string channelId = null;
  605. string landUUID;
  606. string landName;
  607. string parentId;
  608. lock (m_parents) 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. /// <summary>
  878. /// Delete a channel.
  879. /// Once again, there a multitude of options possible. In the simplest case
  880. /// we specify only the name and get a non-persistent cannel in return. Non
  881. /// persistent means that the channel gets deleted if no-one uses it for
  882. /// 5 hours. To accomodate future requirements, it may be a good idea to
  883. /// initially create channels under the umbrella of a parent ID based upon
  884. /// the region name. That way we have a context for side channels, if those
  885. /// are required in a later phase.
  886. /// In this case the call handles parent and description as optional values.
  887. /// </summary>
  888. private static readonly string m_vivoxChannelDel = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}";
  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. /// <summary>
  899. /// Return information on channels in the given directory
  900. /// </summary>
  901. private static readonly string m_vivoxChannelSearch = "http://{0}/api2/viv_chan_search.php?&cond_chanparent={1}&auth_token={2}";
  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. }