VivoxVoiceModule.cs 61 KB

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