PageRenderTime 74ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/Server/IServV2/IPhone/Sites/IPWS/PageHandler.cs

https://bitbucket.org/fboltz/afpmobile
C# | 2788 lines | 2095 code | 407 blank | 286 comment | 423 complexity | fb268bc8cd9c86783ed46031a842560e MD5 | raw file
Possible License(s): Apache-2.0, MPL-2.0, LGPL-2.1, MIT, BSD-3-Clause, 0BSD, AGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. using System.Collections.Generic;
  2. using System.Web.Caching;
  3. using AFP.IPhone.Application;
  4. using AFP.IPhone.Extensions;
  5. using AFP.IPhone.Processor;
  6. using AFP.IPhone.Storage;
  7. using System;
  8. using System.IO;
  9. using System.IO.Compression;
  10. using System.Linq;
  11. using System.Threading;
  12. using System.Web;
  13. using System.Xml;
  14. using System.Security.Cryptography;
  15. using System.Text;
  16. namespace AFP.IPhone.Web
  17. {
  18. public class PageHandler : IHttpHandler
  19. {
  20. private class CachedDocument
  21. {
  22. private string GetChecksum(byte[] document)
  23. {
  24. MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
  25. Byte[] ba = MD5.ComputeHash(document);
  26. StringBuilder hex = new StringBuilder(ba.Length * 2);
  27. foreach (byte b in ba)
  28. hex.AppendFormat("{0:x2}", b);
  29. return hex.ToString();
  30. }
  31. public CachedDocument(byte[] document, DateTime lastModified)
  32. {
  33. Document = document;
  34. LastModified = lastModified;
  35. Checksum = GetChecksum(document);
  36. }
  37. public string Checksum { get; private set; }
  38. public byte[] Document { get; private set; }
  39. public DateTime LastModified { get; private set; }
  40. }
  41. private static readonly object _lockRootCache = new object();
  42. private static readonly object _lockTopicCache = new object();
  43. private struct PathAndWCF
  44. {
  45. public string RootPath;
  46. public string EndPointName;
  47. public XmlDocument GeneratedSites;
  48. }
  49. private static System.Collections.Hashtable _services; // virtualdir ---> PathAndWCF config;
  50. private static System.Collections.Hashtable _idVD; // id service ---> virtualdir;
  51. private static System.Collections.Hashtable _VdByTopicId; // topicid ---> EndPointName;
  52. private static XmlDocument _BuildedSiteConfiguration;
  53. private static TimeSpan? _ExpireCacheVote = null;
  54. private static TimeSpan? _BuildWithXDay = null;
  55. public bool IsReusable
  56. {
  57. get { return false; }
  58. }
  59. private static FileInfo GetMediaInfo(string virtualdir, string format, string plugin, string mediaId)
  60. {
  61. return new System.IO.FileInfo(GetPath((string)(((PathAndWCF)_services[virtualdir]).RootPath), format, plugin, mediaId));
  62. //return new StorageServer().Info(format, plugin, mediaId);
  63. }
  64. private static void GetMedia(Stream output, string virtualdir, string format, string plugin, string mediaId)
  65. {
  66. var buffer = new byte[16384];
  67. int read;
  68. /* using (Stream document = new StorageServer().Restore(format, plugin, mediaId))
  69. {}
  70. */
  71. Stream document = new FileStream(GetPath(((PathAndWCF)_services[virtualdir]).RootPath, format, plugin, mediaId), FileMode.Open, FileAccess.Read, FileShare.Read);
  72. do
  73. {
  74. if ((read = document.Read(buffer, 0, buffer.Length)) > 0)
  75. output.Write(buffer, 0, read);
  76. } while (read > 0);
  77. document.Close();
  78. }
  79. private static void RequestAbout(HttpContext context)
  80. {
  81. // Préparation Http
  82. WebApplication.PageSetHeaders();
  83. context.Response.Charset = "utf-8";
  84. context.Response.ContentType = "text/html";
  85. // Compression Gzip
  86. if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
  87. {
  88. context.Response.AddHeader("Content-Encoding", "gzip");
  89. context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
  90. }
  91. try
  92. {
  93. if (string.IsNullOrEmpty(context.Request.QueryString["site"]))
  94. {
  95. context.Response.TransmitFile(string.Format(@"{0}about\about-{1}.html", context.Request.PhysicalApplicationPath, (string.IsNullOrEmpty(context.Request.Headers["Accept-Language"])) ? "en" : context.Request.Headers["Accept-Language"].Substring(0, 2)));
  96. }
  97. else
  98. {
  99. // plusieurs produits...
  100. string fPath = string.Format(@"{0}about\{2}-{1}.html", context.Request.PhysicalApplicationPath, (string.IsNullOrEmpty(context.Request.Headers["Accept-Language"])) ? "en" : context.Request.Headers["Accept-Language"].Substring(0, 2), context.Request.QueryString["site"]);
  101. if (System.IO.File.Exists(fPath))
  102. {
  103. context.Response.TransmitFile(fPath);
  104. }
  105. else
  106. {
  107. context.Response.TransmitFile(string.Format(@"{0}about\about-{1}.html", context.Request.PhysicalApplicationPath, (string.IsNullOrEmpty(context.Request.Headers["Accept-Language"])) ? "en" : context.Request.Headers["Accept-Language"].Substring(0, 2)));
  108. }
  109. }
  110. }
  111. catch (Exception e)
  112. {
  113. try
  114. {
  115. context.Response.TransmitFile(string.Format(@"{0}about\about-en.html", context.Request.PhysicalApplicationPath));
  116. }
  117. catch
  118. {
  119. // Reporting
  120. Process.Trace(WebApplication.PageName, e.ToString(), System.Diagnostics.EventLogEntryType.Error);
  121. Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
  122. // Erreur de traitement
  123. context.Response.ContentType = "text/xml";
  124. context.Response.ClearContent();
  125. context.Response.Write(new ExceptionDocument(e, "About error"));
  126. }
  127. }
  128. }
  129. private static void RequestCheck(HttpContext context)
  130. {
  131. try
  132. {
  133. // Préparation Http
  134. WebApplication.PageSetHeaders();
  135. context.Response.ContentType = "text/html";
  136. if (context.Request.QueryString.Get("deep") == "1")
  137. try
  138. {
  139. using (var processorClient = new ProcessorClient(Process.Configuration.DocumentElement.GetAttribute("processorEndpointName")))
  140. {
  141. var processorServiceStatus = processorClient.Status();
  142. // Ecriture du tag ok
  143. switch (processorServiceStatus)
  144. {
  145. case System.Diagnostics.EventLogEntryType.Error:
  146. context.Response.Write("STATUS_ERROR");
  147. break;
  148. case System.Diagnostics.EventLogEntryType.Warning:
  149. context.Response.Write("STATUS_WARNING");
  150. break;
  151. default:
  152. context.Response.Write("STATUS_OK");
  153. break;
  154. }
  155. }
  156. }
  157. catch (Exception e)
  158. {
  159. // Reporting
  160. Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
  161. // Ecriture du tag error
  162. context.Response.Write("STATUS_ERROR");
  163. }
  164. else
  165. context.Response.Write("STATUS_OK");
  166. }
  167. catch (Exception e)
  168. {
  169. // Reporting
  170. Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
  171. // Ecriture de l'erreur sur la sortie
  172. context.Response.Write(e.ToString());
  173. }
  174. }
  175. private static void RequestDescription(HttpContext context)
  176. {
  177. // Préparation Http
  178. WebApplication.PageSetHeaders();
  179. context.Response.ContentType = "text/html";
  180. // Compression Gzip
  181. if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
  182. {
  183. context.Response.AddHeader("Content-Encoding", "gzip");
  184. context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
  185. }
  186. try
  187. {
  188. context.Response.TransmitFile(string.Format(@"{0}description\{1}-{2}.html", context.Request.PhysicalApplicationPath, context.Request.QueryString["product"], (string.IsNullOrEmpty(context.Request.Headers["Accept-Language"])) ? "en" : context.Request.Headers["Accept-Language"].Substring(0, 2)));
  189. }
  190. catch (Exception e)
  191. {
  192. try
  193. {
  194. context.Response.TransmitFile(string.Format(@"{0}description\{1}-en.html", context.Request.PhysicalApplicationPath, context.Request.QueryString["product"]));
  195. }
  196. catch (Exception e2)
  197. {
  198. // Reporting
  199. Process.Trace(WebApplication.PageName, string.Format("{0},{1}", e.ToString(), e2.ToString()), System.Diagnostics.EventLogEntryType.Error);
  200. Process.Set(WebApplication.PageName, string.Format("{0},{1}", e.Message, e2.Message), System.Diagnostics.EventLogEntryType.Error);
  201. // Erreur de traitement
  202. context.Response.ContentType = "text/xml";
  203. context.Response.ClearContent();
  204. context.Response.Write(new ExceptionDocument(e, "About error"));
  205. }
  206. }
  207. }
  208. private static void RequestDisclaimer(HttpContext context)
  209. {
  210. // Préparation Http
  211. WebApplication.PageSetHeaders();
  212. context.Response.Charset = "utf-8";
  213. context.Response.ContentType = "text/html";
  214. // Compression Gzip
  215. if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
  216. {
  217. context.Response.AddHeader("Content-Encoding", "gzip");
  218. context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
  219. }
  220. try
  221. {
  222. context.Response.TransmitFile(string.Format(@"{0}disclaimers\{1}\disclaimer-{2}.html", context.Request.PhysicalApplicationPath, context.Request.QueryString["SC"], (string.IsNullOrEmpty(context.Request.Headers["Accept-Language"])) ? "en" : context.Request.Headers["Accept-Language"].Substring(0, 2)));
  223. }
  224. catch (Exception e)
  225. {
  226. try
  227. {
  228. context.Response.TransmitFile(string.Format(@"{0}disclaimers\{1}\disclaimer-en.html", context.Request.PhysicalApplicationPath, context.Request.QueryString["SC"]));
  229. }
  230. catch
  231. {
  232. // Reporting
  233. Process.Trace(WebApplication.PageName, e.ToString(), System.Diagnostics.EventLogEntryType.Error);
  234. Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
  235. // Erreur de traitement
  236. context.Response.ContentType = "text/xml";
  237. context.Response.ClearContent();
  238. context.Response.Write(new ExceptionDocument(e, "About error"));
  239. }
  240. }
  241. }
  242. private static void RequestProducts(HttpContext context, List<String> StringsCachedDepency, DateTime? CachedDate)
  243. {
  244. try
  245. {
  246. #if DEBUG && DEBUGPRODUCT
  247. System.Diagnostics.Debugger.Break();
  248. #endif
  249. String FilePathConfig = Process.FileConfigurationPath;
  250. FileInfo info = null;
  251. if (string.IsNullOrEmpty(FilePathConfig) == false)
  252. {
  253. info = new FileInfo(FilePathConfig);
  254. }
  255. if (string.IsNullOrEmpty(FilePathConfig) == false)
  256. {
  257. if (StringsCachedDepency == null)
  258. {
  259. StringsCachedDepency = new List<string>();
  260. }
  261. StringsCachedDepency.Add(FilePathConfig);
  262. }
  263. CachedDocument products;
  264. try
  265. {
  266. Monitor.Enter(_lockRootCache);
  267. products = (CachedDocument)context.Cache[Constants._storageProductsFileId];
  268. // Products présent dans le cache ?
  269. if (products == null)
  270. {
  271. // Récupération des informations
  272. var productsDocument = new XmlDocument();
  273. productsDocument.LoadXml("<sites/>");
  274. foreach (XmlNode site in _BuildedSiteConfiguration.SelectNodes("//site"))
  275. {
  276. if (site is XmlElement)
  277. productsDocument.DocumentElement.AppendChild(productsDocument.ImportNode(site, false));
  278. }
  279. // Suppression des sites non requis
  280. if (Process.Configuration.DocumentElement.HasAttribute("sitesIdList"))
  281. {
  282. var allowedIds = Process.Configuration.DocumentElement.GetAttribute("sitesIdList").Split(';');
  283. var removedSites = new List<XmlElement>();
  284. // Recherche des sites non requis
  285. foreach (XmlElement site in _BuildedSiteConfiguration.SelectNodes("//site"))
  286. if (site.HasAttribute("id") && !allowedIds.Contains(site.GetAttribute("id")))
  287. removedSites.Add(site);
  288. // Suppression des sites non requis
  289. foreach (var site in removedSites)
  290. productsDocument.DocumentElement.RemoveChild(site);
  291. }
  292. // Mise en mémoire du document sites
  293. using (var buffer = new MemoryStream())
  294. {
  295. productsDocument.Save(buffer);
  296. if (info != null)
  297. products = new CachedDocument(buffer.ToArray(), info.LastWriteTimeUtc);
  298. }
  299. // Mise en cache
  300. if (info != null)
  301. context.Cache.Insert(Constants._storageProductsFileId, products, new CacheDependency(info.FullName));
  302. }
  303. }
  304. catch (Exception e3)
  305. {
  306. string Message = e3.ToString();
  307. products = null;
  308. }
  309. finally
  310. {
  311. Monitor.Exit(_lockRootCache);
  312. }
  313. // Vérification du cache
  314. Boolean bCache = true;
  315. if (context.Request.Headers.AllKeys.Contains("Cache-Control"))
  316. if (context.Request.Headers["Cache-Control"].ToLower() == "no-cache")
  317. bCache = false;
  318. if (context.Request.Headers.AllKeys.Contains("Pragma"))
  319. {
  320. // doit-on faire une boucle?
  321. if (context.Request.Headers["Pragma"].ToLower() == "no-cache")
  322. bCache = false;
  323. }
  324. if (bCache)
  325. if (context.Request.Headers.AllKeys.Contains("If-Modified-Since"))
  326. if (products.LastModified.ToUniversalTime().Subtract(DateTime.Parse(context.Request.Headers["If-Modified-Since"])).TotalSeconds <= 1)
  327. {
  328. context.Response.AddHeader("cache-control", "public");
  329. context.Response.StatusCode = 304;
  330. return;
  331. }
  332. // Préparation Http
  333. WebApplication.PageSetHeaders
  334. (
  335. new Dictionary<string, string>
  336. {
  337. { "##LM##", products.LastModified.ToUniversalTime ().ToHTTPHeaderString () } ,
  338. { "##ET##", products.Checksum },
  339. { "##EXP##", DateTime.Now.ToUniversalTime().AddSeconds (WebApplication.GetExpires()).ToHTTPHeaderString()}
  340. }
  341. );
  342. context.Response.Buffer = true;
  343. context.Response.BufferOutput = true;
  344. context.Response.ContentType = "text/xml";
  345. // Ecriture du document Sites
  346. context.Response.BinaryWrite(products.Document);
  347. // Compression Gzip
  348. if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
  349. {
  350. context.Response.AddHeader("Content-Encoding", "gzip");
  351. context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
  352. }
  353. // Reporting
  354. Process.Set(WebApplication.PageName, "Hits", System.Diagnostics.EventLogEntryType.Information);
  355. }
  356. catch (Exception e)
  357. {
  358. // Reporting
  359. Process.Trace(WebApplication.PageName, e.ToString(), System.Diagnostics.EventLogEntryType.Error);
  360. Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
  361. // Erreur de traitement
  362. context.Response.ContentType = "text/xml";
  363. context.Response.ClearContent();
  364. context.Response.Write(new ExceptionDocument(e, "Products error"));
  365. }
  366. }
  367. private static void RequestRating(HttpContext context)
  368. {
  369. #if DEBUG && DEBUGRATING
  370. System.Diagnostics.Debugger.Break();
  371. #endif
  372. // Préparation Http
  373. WebApplication.PageSetHeaders();
  374. context.Response.ContentType = "text/xml";
  375. // Récupération des informations
  376. string productId = GetProductName(context, true);
  377. string device = GetDeviceName(context);
  378. string endPointName = GetEndPointName(context);
  379. // Vote selon type
  380. try
  381. {
  382. using (var processorClient = new ProcessorClient(endPointName))
  383. {
  384. // Vote
  385. switch (context.Request.QueryString["type"])
  386. {
  387. case "0":
  388. context.Response.Write(processorClient.SetRate(productId, context.Request.QueryString["id"], context.Request.QueryString["item"], float.Parse(context.Request.QueryString["rate"], System.Globalization.CultureInfo.InvariantCulture), device));
  389. break;
  390. case "1":
  391. context.Response.Write(processorClient.SetRate(productId, context.Request.QueryString["id"], context.Request.QueryString["parent"], context.Request.QueryString["item"], float.Parse(context.Request.QueryString["rate"], System.Globalization.CultureInfo.InvariantCulture), device));
  392. break;
  393. default:
  394. throw new Exception("Invalid type value.");
  395. }
  396. }
  397. }
  398. catch (Exception e)
  399. {
  400. // Reporting
  401. Process.Trace(WebApplication.PageName, string.Format(" endpointName {0} error {1} ", endPointName, e.ToString()), System.Diagnostics.EventLogEntryType.Error);
  402. Process.Set(WebApplication.PageName, string.Format(" endpointName {0} error {1} ", endPointName, e.Message), System.Diagnostics.EventLogEntryType.Error);
  403. // Réponse
  404. context.Response.ClearContent();
  405. context.Response.Write(new ExceptionDocument(e, string.Format(" {1} on endpointName {0} ProductId {2}", endPointName, "Rating error", productId)));
  406. }
  407. }
  408. private static void RequestSites(HttpContext context, Boolean rebuildSites)
  409. {
  410. #if DEBUG && DEBUG_SITE
  411. System.Diagnostics.Debugger.Break();
  412. #endif
  413. Process.Start();
  414. // on a reconstruit le document... sans les favoris toutefois a faire plus tard
  415. try
  416. {
  417. CachedDocument sites;
  418. /*
  419. * Raccourci de debuggage en prod...
  420. */
  421. /*
  422. List<string> StringsCachedDepency1;
  423. DateTime CachedDate1;
  424. var sitesDocument1 = BuildSites(out StringsCachedDepency1, out CachedDate1);
  425. */
  426. try
  427. {
  428. Monitor.Enter(_lockRootCache);
  429. // Vérification du cache
  430. sites = (CachedDocument)context.Cache[Constants._storageSitesFileId];
  431. // Sites présent dans le cache ?
  432. if (sites == null || rebuildSites)
  433. {
  434. _services = null; // on force la reconstruction totale... evitera le bug du cache pour la partie Ipad...
  435. // Récupération des informations
  436. var sitesDocument = new XmlDocument();
  437. context.Cache.Remove(Constants._storageSitesFileId);
  438. List<string> StringsCachedDepency;
  439. DateTime CachedDate;
  440. sitesDocument = BuildSites(out StringsCachedDepency, out CachedDate);
  441. //StringsCachedDepency.Add(Process.FileConfigurationPath); // Si la config change il faut que l'on s'adapte. déjà fait dans buildSites...
  442. // si le document sites.xml change il faut aussi se mettre à jour
  443. //StringsCachedDepency.Add(Process.FileConfigurationPath); // Si la config change il faut que l'on s'adapte.
  444. _BuildedSiteConfiguration = sitesDocument;
  445. // Site par défaut
  446. if (Process.Configuration.DocumentElement.HasAttribute("defaultSite"))
  447. sitesDocument.DocumentElement.SetAttribute("defaultSite", Process.Configuration.DocumentElement.GetAttribute("defaultSite"));
  448. // Suppression des attributs inutiles
  449. foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@id]|//subtopic[@id]"))
  450. item.RemoveAttribute("id");
  451. foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@product]|//subtopic[@product]"))
  452. item.RemoveAttribute("product");
  453. foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@showcatchline]|//subtopic[@showcatchline]"))
  454. item.RemoveAttribute("showcatchline");
  455. foreach (XmlElement item in sitesDocument.SelectNodes("//site[@smallIconsPath]"))
  456. item.RemoveAttribute("smallIconsPath");
  457. foreach (XmlElement item in sitesDocument.SelectNodes("//site[@bigIconsPath]"))
  458. item.RemoveAttribute("bigIconsPath");
  459. foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@maxAge]"))
  460. item.RemoveAttribute("maxAge");
  461. foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@overrideuno]"))
  462. item.RemoveAttribute("overrideuno");
  463. // foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@newuno]"))
  464. // item.RemoveAttribute("newuno");
  465. foreach (XmlElement item in sitesDocument.SelectNodes("//subtopic[@maxAge]"))
  466. item.RemoveAttribute("maxAge");
  467. foreach (XmlElement item in sitesDocument.SelectNodes("//site[@defaultIcon]"))
  468. item.RemoveAttribute("defaultIcon");
  469. foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@announce]"))
  470. item.RemoveAttribute("announce");
  471. foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@Serve]|//subtopic[@Serve]"))
  472. item.RemoveAttribute("Serve");
  473. foreach (XmlElement item in sitesDocument.SelectNodes("//site[@maxNumberOfItems]"))
  474. item.RemoveAttribute("maxNumberOfItems");
  475. foreach (XmlElement item in sitesDocument.SelectNodes("//site[@productVote]"))
  476. item.RemoveAttribute("productVote");
  477. /* foreach (XmlElement item in sitesDocument.SelectNodes("//site"))
  478. item.RemoveAttribute("maxNumberOfItems");
  479. */
  480. foreach (XmlElement item in sitesDocument.SelectNodes("//topic|//subtopic|//topics"))
  481. {
  482. item.RemoveAttribute("path");
  483. item.RemoveAttribute("file");
  484. item.RemoveAttribute("htmlModel");
  485. item.RemoveAttribute("serviceCongigPath");
  486. item.RemoveAttribute("virtualDir");
  487. item.RemoveAttribute("siteId");
  488. item.RemoveAttribute("service");
  489. if (item.HasAttribute("shortName") == false)
  490. {
  491. item.SetAttribute("shortName", item.GetAttributeValue("fullName", ""));
  492. }
  493. }
  494. sitesDocument.DocumentElement.SetAttribute("updateDate", DateTime.UtcNow.ToXmlElementString());
  495. // Mise en mémoire du document sites
  496. using (var buffer = new MemoryStream())
  497. {
  498. sitesDocument.Save(buffer);
  499. sites = new CachedDocument(buffer.ToArray(), CachedDate);
  500. Process.Trace(string.Format("Cached document {0}", CachedDate), System.Diagnostics.EventLogEntryType.Information);
  501. }
  502. // Mise en cache
  503. context.Cache.Remove(Constants._storageSitesFileId);
  504. context.Cache.Insert(Constants._storageSitesFileId, sites, new CacheDependency(StringsCachedDepency.ToArray()));
  505. }
  506. }
  507. catch (Exception e3)
  508. {
  509. throw e3;
  510. }
  511. finally
  512. {
  513. Monitor.Exit(_lockRootCache);
  514. }
  515. // Vérification du cache
  516. Boolean bCache = true;
  517. if (context.Request.Headers.AllKeys.Contains("Cache-Control"))
  518. if (context.Request.Headers["Cache-Control"].ToLower() == "no-cache")
  519. bCache = false;
  520. if (context.Request.Headers.AllKeys.Contains("Pragma"))
  521. {
  522. // doit-on faire une boucle?
  523. if (context.Request.Headers["Pragma"].ToLower() == "no-cache")
  524. bCache = false;
  525. }
  526. if (bCache)
  527. if (context.Request.Headers.AllKeys.Contains("If-Modified-Since"))
  528. if (sites.LastModified.ToUniversalTime().Subtract(DateTime.Parse(context.Request.Headers["If-Modified-Since"])).TotalSeconds <= 1)
  529. {
  530. context.Response.AddHeader("cache-control", "public");
  531. context.Response.StatusCode = 304;
  532. return;
  533. }
  534. // Préparation Http
  535. WebApplication.PageSetHeaders(
  536. new Dictionary<string, string>
  537. {
  538. { "##LM##", sites.LastModified.ToUniversalTime ().ToHTTPHeaderString () } ,
  539. { "##ET##", sites.Checksum} ,
  540. { "##EXP##", DateTime.UtcNow.ToUniversalTime().AddSeconds (WebApplication.GetExpires()).ToHTTPHeaderString()}
  541. });
  542. context.Response.Buffer = true;
  543. context.Response.BufferOutput = true;
  544. context.Response.ContentType = "text/xml";
  545. // Ecriture du document Sites
  546. context.Response.BinaryWrite(sites.Document);
  547. // Compression Gzip
  548. if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
  549. {
  550. context.Response.AddHeader("Content-Encoding", "gzip");
  551. context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
  552. }
  553. // Reporting
  554. Process.Set(WebApplication.PageName, "Hits", System.Diagnostics.EventLogEntryType.Information);
  555. }
  556. catch (Exception e)
  557. {
  558. // Reporting
  559. Process.Trace(WebApplication.PageName, e.ToString(), System.Diagnostics.EventLogEntryType.Error);
  560. Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
  561. // Erreur de traitement
  562. context.Response.ContentType = "text/xml";
  563. context.Response.ClearContent();
  564. context.Response.Write(new ExceptionDocument(e, "Sites error"));
  565. }
  566. }
  567. private static void RequestTopic(HttpContext context)
  568. {
  569. String FilePathConfig = Process.FileConfigurationPath;
  570. List<string> StringsCachedDepency = null;
  571. int startAt = 0;
  572. string mes = "";
  573. string dmes = " start";
  574. String uno = "";
  575. if (string.IsNullOrEmpty(FilePathConfig) == false)
  576. {
  577. if (StringsCachedDepency == null)
  578. {
  579. StringsCachedDepency = new List<string>();
  580. }
  581. StringsCachedDepency.Add(FilePathConfig);
  582. }
  583. try
  584. {
  585. CachedDocument topic = null;
  586. String VirtualDirectory;
  587. String ProductID;
  588. XmlElement SelectedSite;
  589. String sCacheReference = "";
  590. uno = context.Request.QueryString["uno"];
  591. XmlDocument sitesDocument = new XmlDocument();
  592. XmlDocument xapplicationConfiguration = Process.Configuration;
  593. string overtype = "";
  594. ProductID = context.Request.QueryString["product"];
  595. if (string.IsNullOrEmpty(ProductID))
  596. {
  597. //TODO il faut mettre le DefaultSiteName dans SiteName
  598. }
  599. VirtualDirectory = context.Request.QueryString["vd"];
  600. if (string.IsNullOrEmpty(VirtualDirectory))
  601. {
  602. VirtualDirectory = context.Request.QueryString["product"];
  603. }
  604. dmes += " 1 ";
  605. using (var buffer = new MemoryStream())
  606. {
  607. GetMedia(buffer, VirtualDirectory, Constants._storageSitesFormatName, Constants._storageSitesKey, Constants._storageSitesFileId);
  608. buffer.Position = 0;
  609. sitesDocument.Load(buffer);
  610. }
  611. // Récupération de l'id topic
  612. // ici il faudrait faire le calcul du maxEntries??
  613. dmes += " on cherche avec le uno " + uno;
  614. dmes += "\n" + string.Format("//*[@uno='{0}']", uno);
  615. XmlNode topicElement = sitesDocument.SelectSingleNode(string.Format("//*[@uno='{0}']", uno));
  616. TopicDeclaration topicDeclaration;
  617. if (topicElement == null)
  618. {
  619. //cas des votes !!!
  620. if (uno.IndexOf("__") > -1)
  621. uno = uno.Substring(uno.IndexOf("__") + 2);
  622. dmes += " on re cherche avec le uno " + uno;
  623. dmes += "Process configuration \n" + Process.Configuration.OuterXml;
  624. topicElement = Process.Configuration.SelectSingleNode(string.Format("//*[@uno='{0}']", uno));
  625. if (((XmlElement)topicElement).HasAttribute("type"))
  626. {
  627. overtype = topicElement.Attributes["type"].Value.ToLower();
  628. }
  629. dmes += "Process configuration \n" + Process.Configuration.OuterXml;
  630. }
  631. dmes += "\n topicElement " + topicElement.OuterXml;
  632. topicDeclaration = new TopicDeclaration((XmlElement)topicElement);
  633. // Récupération des informations sur le topic source
  634. string idTopic = "";
  635. if (((XmlElement)topicElement).HasAttribute("id"))
  636. idTopic = topicElement.Attributes["id"].Value;
  637. else
  638. idTopic = " __" + uno;
  639. string nameMedia = idTopic;
  640. dmes += " et on a trouvé";
  641. if (topicElement.Name == "subtopic")
  642. {
  643. if (((XmlElement)topicElement).HasAttribute("type"))
  644. {
  645. if ((topicElement.Attributes["type"].Value == "diaporama") || (topicElement.Attributes["type"].Value == "magazin") || (topicElement.Attributes["type"].Value == "7") || (topicElement.Attributes["type"].Value == "8"))
  646. {
  647. nameMedia = string.Format("{0}__{1}", VirtualDirectory, nameMedia);
  648. }
  649. }
  650. }
  651. SelectedSite = (XmlElement)_BuildedSiteConfiguration.SelectSingleNode(string.Format("//site[@id='{0}']", ProductID));
  652. if (SelectedSite == null)
  653. {
  654. throw new Exception(string.Format("Configuration Error no product with id {0}", ProductID));
  655. }
  656. /******************************************************************************************************************************************/
  657. /******************************************************************************************************************************************/
  658. /******************************************************************************************************************************************/
  659. /******************************************************************************************************************************************/
  660. /******************************************************************************************************************************************/
  661. /******************************************************************************************************************************************/
  662. XmlElement curNode;
  663. String LocalId = idTopic.Substring(idTopic.IndexOf("__") + 2);
  664. XmlElement ConfigSiteNode = null;
  665. ConfigSiteNode = (XmlElement)Process.Configuration.SelectSingleNode(string.Format(".//site[@id='{0}']", ProductID));
  666. curNode = (XmlElement)ConfigSiteNode.SelectSingleNode(string.Format(".//*[@id='{0}']", LocalId));
  667. // et evidement ce n'est pas bon...
  668. // dans le cadre d'un Free/payant...
  669. int maxEntries;
  670. try
  671. {
  672. while (curNode is XmlElement && !(curNode.ParentNode is XmlDocument) && curNode.HasAttribute("maxNumberOfItems") == false)
  673. {
  674. curNode = (XmlElement)curNode.ParentNode;
  675. }
  676. if (curNode.HasAttribute("maxNumberOfItems"))
  677. maxEntries = int.Parse(curNode.GetAttribute("maxNumberOfItems"));
  678. else
  679. maxEntries = 30;
  680. }
  681. catch (Exception e)
  682. {
  683. string a = e.Message;
  684. maxEntries = 30;
  685. #if DEBUG && toto
  686. Process.Trace(WebApplication.PageName, string.Format(" Determination maxNumberOfItems {0} ProductId {1} LocalId{2} idTopic {4} \n\n ## {3}", e.ToString(), ProductID, LocalId, Process.Configuration.OuterXml, idTopic), System.Diagnostics.EventLogEntryType.Error);
  687. //Process.Set(WebApplication.PageName, string.Format(" Determination maxNumber {0}", e.ToString()), System.Diagnostics.EventLogEntryType.Error);
  688. #endif
  689. }
  690. //int maxEntries;
  691. //curNode = (XmlElement)sitesDocument.SelectSingleNode(string.Format(".//*[@uno='{0}']", uno));
  692. curNode = (XmlElement)ConfigSiteNode.SelectSingleNode(string.Format(".//*[@id='{0}']", LocalId));
  693. try
  694. {
  695. while (curNode is XmlElement && !(curNode.ParentNode is XmlDocument) && curNode.HasAttribute("startat") == false)
  696. {
  697. curNode = (XmlElement)curNode.ParentNode;
  698. }
  699. if (curNode.HasAttribute("startat"))
  700. startAt = int.Parse(curNode.GetAttribute("startat"));
  701. else
  702. startAt = 0;
  703. }
  704. catch (Exception e)
  705. {
  706. string a = e.Message;
  707. startAt = 0;
  708. }
  709. #if DEBUG_TOPIC
  710. System.Diagnostics.Debugger.Break();
  711. #endif
  712. try
  713. {
  714. Monitor.Enter(_lockTopicCache);
  715. // Vérification du cache
  716. sCacheReference = string.Format("{0}_{1}", uno, ProductID);
  717. topic = (CachedDocument)context.Cache[sCacheReference];
  718. // Topic présent dans le cache ?
  719. if (topic == null)
  720. {
  721. String topicType = GetType(uno);
  722. string lang = GetLang(uno);
  723. if (string.IsNullOrEmpty(overtype) == false)
  724. {
  725. topicType = overtype;
  726. }
  727. dmes += "\n" + overtype + "\n";
  728. var topicDocument = new XmlDocument();
  729. if (topicType == "heart" || topicType == "rated" || topicType == "mostviewed")
  730. {
  731. dmes += "\n on a bien un Rated\n";
  732. XmlDocument btopic = BuildRateTopic(context, topicType, 50, (TimeSpan)_BuildWithXDay, lang );
  733. dmes += "\n buildrated done \n";
  734. using (var buffer = new MemoryStream())
  735. {
  736. btopic.Save(buffer);
  737. topic = new CachedDocument(buffer.ToArray(), System.DateTime.UtcNow);
  738. }
  739. dmes += "\n " + btopic.OuterXml + "\n";
  740. #if DEBUG && DEBUGTRACERATING
  741. Process.Trace(WebApplication.PageName, string.Format(" Build Rated Topic {0}", dmes), System.Diagnostics.EventLogEntryType.Error);
  742. //Process.Set(WebApplication.PageName, string.Format(" Build Rated Topic {0}", dmes), System.Diagnostics.EventLogEntryType.Error);
  743. #endif
  744. if (_ExpireCacheVote != null)
  745. context.Cache.Insert(sCacheReference, topic, null, System.Web.Caching.Cache.NoAbsoluteExpiration, (TimeSpan)_ExpireCacheVote);
  746. else
  747. context.Cache.Insert(sCacheReference, topic, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(2));
  748. }
  749. else
  750. {
  751. // Chargement du document sites
  752. dmes += " non Rated";
  753. var topicInfo = GetMediaInfo(VirtualDirectory, Constants._storageTopicFormatName, context.Request.QueryString["plugin"], string.Format("{0}.xml", nameMedia));
  754. // Chargement du document topic XAfp
  755. //TODO du ou des topics
  756. using (var buffer = new MemoryStream())
  757. {
  758. GetMedia(buffer, VirtualDirectory, Constants._storageTopicFormatName, context.Request.QueryString["plugin"], string.Format("{0}.xml", nameMedia));
  759. buffer.Position = 0;
  760. topicDocument.Load(buffer);
  761. }
  762. // Suppression des éléments en excédent et ajout du parentUno
  763. var bag = topicDocument.DocumentElement.SelectSingleNode("Bag");
  764. var rmv = 0;
  765. int currentI = 0;
  766. foreach (XmlNode item in bag.SelectNodes("Item"))
  767. {
  768. // présence de topicId ?
  769. //UpdateRating(context, item);
  770. if (((XmlElement)item).HasAttribute("topicId"))
  771. {
  772. if (topicDeclaration.Topics.SelectSingleNode(string.Format("*[@id='{0}']", ((XmlElement)item).GetAttribute("topicId"))) == null)
  773. {
  774. bag.RemoveChild(((XmlElement)item));
  775. rmv++;
  776. }
  777. else
  778. {
  779. ((XmlElement)item).RemoveAttribute("topicId");
  780. if (int.Parse(((XmlElement)item).GetAttributeValue("index", "0")) < maxEntries + rmv)
  781. {
  782. if (currentI < startAt)
  783. {
  784. bag.RemoveChild(((XmlElement)item));
  785. //currentI++;
  786. }
  787. else
  788. {
  789. ((XmlElement)item).RemoveAttribute("index");
  790. }
  791. currentI++;
  792. }
  793. else
  794. {
  795. bag.RemoveChild(((XmlElement)item));
  796. }
  797. }
  798. }
  799. else if (int.Parse(((XmlElement)item).GetAttributeValue("index", "0")) < maxEntries + rmv)
  800. {
  801. if (currentI < startAt)
  802. {
  803. bag.RemoveChild(((XmlElement)item));
  804. // rmv++;
  805. }
  806. else
  807. {
  808. ((XmlElement)item).RemoveAttribute("index");
  809. }
  810. currentI++;
  811. }
  812. else
  813. bag.RemoveChild(((XmlElement)item));
  814. }
  815. // Modification NumberOfItems
  816. var nbi = topicDocument.DocumentElement.SelectSingleNode("Head/NumberOfItems");
  817. if (nbi != null)
  818. nbi.InnerText = bag.SelectNodes("Item").Count.ToString();
  819. if (topicDocument.DocumentElement.SelectSingleNode("Xafp/CatchLine") != null)
  820. {
  821. topicDocument.DocumentElement.RemoveChild(topicDocument.DocumentElement.SelectSingleNode("Xafp/CatchLine"));
  822. }
  823. // Ajout namespace xml
  824. var topicDocumentNavigator = topicDocument.CreateNavigator();
  825. var topicDocumentManager = new XmlNamespaceManager(topicDocumentNavigator.NameTable);
  826. topicDocumentManager.AddNamespace("xml", "http://www.w3.org/XML/1998/namespace");
  827. // Attributs obligatoires
  828. if (topicDocument.DocumentElement.SelectSingleNode("@lang", topicDocumentManager) == null)
  829. topicDocument.DocumentElement.SetAttribute("xml:lang", topicDeclaration.Topics.GetAttribute("lang"));
  830. // Mise en mémoire
  831. using (var buffer = new MemoryStream())
  832. {
  833. topicDocument.Save(buffer);
  834. topic = new CachedDocument(buffer.ToArray(), topicInfo.LastWriteTimeUtc);
  835. #if DEBUG && TRACE_LASTMODIFIEDTOPIC
  836. StringBuilder text2;
  837. text2 = new StringBuilder();
  838. text2.AppendLine(string.Format("Topic Local ID {0} lastmodified {1} lastAccessTime {2} ", LocalId, topicInfo.LastWriteTimeUtc, topicInfo.LastAccessTimeUtc ));
  839. Process.Trace(text2.ToString(), "LastModified topic", System.Diagnostics.EventLogEntryType.Information);
  840. #endif
  841. }
  842. // Mise en cache
  843. // il faut aussi faire une dépendance selon le site...
  844. // doit on le cacher?
  845. StringsCachedDepency.Add(topicInfo.FullName);
  846. if (_ExpireCacheVote != null)
  847. context.Cache.Insert(sCacheReference, topic, new CacheDependency(StringsCachedDepency.ToArray()), System.Web.Caching.Cache.NoAbsoluteExpiration, (TimeSpan)_ExpireCacheVote);
  848. else
  849. context.Cache.Insert(sCacheReference, topic, new CacheDependency(StringsCachedDepency.ToArray()));
  850. }// topic == rated etc.
  851. }
  852. }
  853. catch (Exception e2)
  854. {
  855. mes = e2.Message;
  856. Process.Trace(e2, System.Diagnostics.EventLogEntryType.Error);
  857. #if DEBUG && DEBUGDEBE
  858. try
  859. {
  860. Process.Trace(e2, System.Diagnostics.EventLogEntryType.Error);
  861. System.Diagnostics.EventLog.WriteEntry("AFP Iphone", e2.StackTrace, System.Diagnostics.EventLogEntryType.Error);
  862. }
  863. catch
  864. { }
  865. #endif
  866. }
  867. finally
  868. {
  869. Monitor.Exit(_lockTopicCache);
  870. }
  871. // Vérification du cache
  872. Boolean bCache = true;
  873. if (context.Request.Headers.AllKeys.Contains("Cache-Control"))

Large files files are truncated, but you can click here to view the full file