VivoxVoiceModule.cs 61 KB

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