VivoxVoiceModule.cs 59 KB

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