/Server/IServV2/IPhone/Plugins/Content/AFP.IPhone.Content.Plugins.JournalInternet/Plugin.cs
C# | 3180 lines | 2278 code | 446 blank | 456 comment | 372 complexity | 89b288cb6c243a771e0dbf16bfc6be8c 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
- using AFP.IPhone.Application;
- using AFP.IPhone.Extensions;
- using AFP.IPhone.Storage;
- using AFP.IPhone.Processor.Plugins.JournalInternet.Documents;
-
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.SqlClient;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading;
- using System.Xml;
- using System.Xml.Xsl;
- using System.Web.Services;
- using System.Globalization;
-
- #if SERVICE
- using AFP.IPhone.Plugins.GetCourseId;
- #endif
-
- namespace AFP.IPhone.Processor.Plugins.JournalInternet
- {
- class ExXmlTextWriter : XmlTextWriter
- {
- private StringWriter mvar_Writer;
-
- private ExXmlTextWriter(StringWriter w)
- : base(w)
- {
- mvar_Writer = w;
- // Indentation
- this.Formatting = Formatting.Indented;
- this.Indentation = 2;
- }
-
- public ExXmlTextWriter()
- : this(new StringWriter())
- {
- }
-
- public override string ToString()
- {
- return mvar_Writer.ToString();
- }
- }
- /// <summary>
- /// Class to handle JI AFP iPhone Content
- /// </summary>
- ///
- public class Plugin : ProcessorPluginBase
- {
-
-
- private const string _storagePhotosFormatName = "Photos";
- private const string _storageVideosFormatName = "Videos";
- private const string _storageDocumentFormatName = "Documents";
-
- private readonly List<SqlProcessor> _sqlProcessorList;
- private readonly List<SqlProcessor> _sqlProcessorList2;
- private readonly List<string> _dynamicTopicList;
- private XmlDocument _sites;
-
- private ProcessorServer.TTrace _levelTrace;
-
- private int _Version =1;
- private string _ImageActive ="true";
- private string _PreviewRole ="HighDef";
-
- private Boolean _UseUri = false;
-
- private System.Collections.Hashtable _Xslt;
-
-
- private static XmlWriter createXmlWriter()
- {
- return new ExXmlTextWriter();
- }
-
- public struct RatingEntry
- {
- public readonly string Lang;
- public readonly string NewsId;
- public readonly string TopicId;
-
- public RatingEntry(string topicId, string newsId, string lang)
- {
- Lang = lang;
- NewsId = newsId;
- TopicId = topicId;
- }
- }
-
- public struct HitEntry
- {
- public readonly string Lang;
- public readonly string NewsId;
- public readonly string TopicId;
- public readonly int Hits;
-
- public HitEntry(string topicId, string newsId, string lang, int hits)
- {
- Lang = lang;
- NewsId = newsId;
- TopicId = topicId;
- Hits = hits;
- }
- }
-
- public struct RatingEntryKey : IComparable<RatingEntryKey>
- {
- private readonly string _value;
-
- public RatingEntryKey(DateTime newsDate, DataRow row)
- {
- _value = string.Format("{0}{1}", (((double)row["averageRating"] * 1000) / (1 + (Math.Truncate(DateTime.Now.Subtract(newsDate).TotalDays) * 10))).ToString("0000"), ((int)row["votes"]).ToString("0000000000"));
- }
-
- public int CompareTo(RatingEntryKey other)
- {
- var cmp = other._value.CompareTo(_value);
- return (cmp == 0) ? -1 : cmp;
- }
- }
-
-
- private enum ComponentType
- {
- photo,
- video,
- text,
- unsupported
- }
-
- private enum MessageSection
- {
- Alimentation,
- Database,
- Processing
- }
-
- private enum NewsMediaFilter
- {
- all,
- photoOnly,
- videoOnly
- }
-
-
- private static Object GBLock = new Object();
-
- /// <summary>
- /// Creates a new instance of Plugin
- /// </summary>
- ///
- public Plugin()
- {
- // Initialisations
- _dynamicTopicList = new List<string>();
- _sqlProcessorList = new List<SqlProcessor>();
- _sites = new XmlDocument();
- _Xslt = new System.Collections.Hashtable();
-
-
- // Chargement sites
- _sites.LoadXml("<sites/>");
-
- // Initialisation des bases rating
- try
- {
- foreach (var connection in Configuration.GetAttribute("ratingConnection").Split('|'))
- {
- if (string.IsNullOrEmpty(connection) == false)
- _sqlProcessorList.Add(new SqlProcessor(connection));
- }
- foreach (var connection in Configuration.GetAttribute("alertConnection").Split('|'))
- {
- if (string.IsNullOrEmpty(connection) == false)
- _sqlProcessorList2.Add(new SqlProcessor(connection));
- }
-
- }
- catch (Exception e)
- {
- Process.Trace(e, System.Diagnostics.EventLogEntryType.Error);
- throw;
- }
-
-
- }
-
-
-
-
-
- /// <summary>
- /// Gets the plugin key name.
- /// </summary>
- ///
- public override string Key
- {
- get { return "JI"; }
- }
-
- /// <summary>
- /// Get or Set Leveltrace
- /// </summary>
- public override ProcessorServer.TTrace levelTrace
- {
- get
- {
- return _levelTrace;
- }
- set
- {
- _levelTrace = value;
- }
- }
-
- public override int Version
- {
- get
- {
- return _Version;
- }
- set
- {
- _Version = value;
- }
- }
-
- public override string ImageActive
- {
- get
- {
- return _ImageActive;
- }
- set
- {
- _ImageActive = value;
- }
- }
-
- public override bool UseUri
- {
- get
- {
- return _UseUri;
- }
- set
- {
- _UseUri = value;
- }
- }
-
- public override string PreviewRole
- {
- get
- {
- return _PreviewRole;
- }
- set
- {
- _PreviewRole = value;
- }
- }
- public override void MakeTopic(string topicId)
- {
- TopicImplementation topic;
- topic = TopicImplementation.Load(topicId);
- MakeTopic(topic, false, null);
- }
-
- /// <summary>
- /// Process the defined topics.
- /// </summary>
- /// <param name="content">The content configuration.</param>
- /// <param name="refresh">Flag for refreshing content.</param>
- ///
- public override void MakeTopics(XmlElement content, bool refresh, Boolean multiThread, int maxThreads)
- {
- var doneTopics = new List<ManualResetEvent>();
-
- //note : Traitement de tous les topics et subtopics du site
- try
- {
- foreach (XmlNode item in content.ChildNodes)
- {
- if (item is XmlElement)
- {
- if (item.HasChildNodes)
- MakeTopics((XmlElement)item, refresh, Boolean.Parse(item.GetAttributeValue("multiThread", multiThread.ToString())), maxThreads);
-
- // Traitement d'un topic
- if (item.Name.Equals("topic") || item.Name.Equals("subtopic"))
- {
- // dans le cadre du Touch il faut passer l'id et non l'item...
- var topic = new TopicImplementation((XmlElement)item);
-
- // note: Tout ce passe ici pour la synchro
- if (multiThread == false)
- {
- MakeTopic(topic, refresh, null);
- }
- else
- {
- if (topic.DynamicDelay.Equals(TimeSpan.Zero))
- {
- doneTopics.Add(new ManualResetEvent(false));
- ThreadPool.QueueUserWorkItem
- (
- MakeTopic, new object[]
- {
- topic,
- refresh,
- doneTopics[doneTopics.Count - 1]
- });
-
- // Limitation WaitAll à 64
- if (doneTopics.Count == maxThreads)
- {
- WaitHandle.WaitAll(doneTopics.ToArray());
- doneTopics.Clear();
- }
- }
- else if (_dynamicTopicList.Contains(topic.Id) == false)
- {
- var dynamicMakeTopicThread = new Thread(MakeTopicFromThread);
-
- dynamicMakeTopicThread.IsBackground = true;
- dynamicMakeTopicThread.Name = String.Format("MakeTopics:{0}", topic.Id);
- dynamicMakeTopicThread.Start(topic);
- _dynamicTopicList.Add(topic.Id);
- }
- }
- }
- }
- }
- }
- finally
- {
- // Attente fin de traitement de tous les topics d'un même niveau
- if (doneTopics.Count > 0)
- WaitHandle.WaitAll(doneTopics.ToArray());
- }
- }
-
- /// <summary>
- /// Rate a media.
- /// </summary>
- /// <param name="topicImplementation">Topic implementation.</param>
- /// <param name="newsId">Id of the owner news.</param>
- /// <param name="mediaId">Id of the media.</param>
- /// <param name="rate">Rate value.</param>
- ///
- public override string Rate(TopicImplementation topicImplementation, string productId, string newsId, string mediaId, float rate, string device)
- {
- //en cours
- double realRate = rate;
- int votes;
-
- // Vérification site
- if (_sites == null)
- new Rating(rate, "Invalid site value.", 1).ToString();
-
- lock (_sites)
- {
- // Récupération des votes
- GetRating(string.Format("SELECT SUM(votes) AS votes, SUM(rating) AS rating FROM Ratings2 WHERE mediaId='{0}' and productId='{1}' GROUP BY mediaId", mediaId, productId), ref realRate, out votes);
-
- // Vote
- foreach (var sqlProcessor in _sqlProcessorList)
- sqlProcessor.Add(new SqlMediaRateRequest(productId, topicImplementation.Id, newsId, mediaId, topicImplementation.Lang, rate, device));
- }
-
- return new Rating(rate, realRate, votes).ToString();
- }
-
- /// <summary>
- /// Rate a media.
- /// </summary>
- /// <param name="topicImplementation">Topic implementation</param>
- /// <param name="topicId">Id of the owner topic.</param>
- /// <param name="newsId">Id of the owner news.</param>
- /// <param name="rate">Rate value.</param>
- ///
- public override string Rate(TopicImplementation topicImplementation, string productId, string newsId, float rate, string device)
- {
- double realRate = rate;
- int votes;
-
- // Vérification site
- if (_sites == null)
- new Rating(rate, "Invalid site value.", 1).ToString();
-
- lock (_sites)
- {
- // Récupération des votes
- GetRating(string.Format("SELECT SUM(votes) AS votes, SUM(rating) AS rating FROM Ratings2 WHERE newsId='{0}' AND mediaId IS NULL AND producId='{1}' GROUP BY newsId", newsId, productId), ref realRate, out votes);
-
- // Vote
- foreach (var sqlProcessor in _sqlProcessorList)
- {
- sqlProcessor.Add(new SqlNewsRateRequest(productId, topicImplementation.Id, newsId, topicImplementation.Lang, rate, device));
- #if DEBUG && TRACE_REQUEST
- Process.Trace(string.Format(" productId {0} topicId {1} newsId {2} lang {3} rating {4} device {5} ", productId, topicImplementation.Id, newsId, topicImplementation.Lang, rate, device), System.Diagnostics.EventLogEntryType.Information);
- #endif
-
- }
- }
-
- return new Rating(rate, realRate, votes).ToString();
- }
-
-
-
- /// <summary>
- /// Appel via WCF pour connaitre le vote sur un article ou une photo
- /// </summary>
- /// <param name="productId"></param>
- /// <param name="topicId"></param>
- /// <param name="newsId"></param>
- /// <param name="mediaId"></param>
- /// <param name="lang"></param>
- /// <param name="rate"></param>
- /// <param name="vote"></param>
- public override void getRated(string productId, string topicId, string newsId, string mediaId, string lang, out double rate, out int vote)
- {
- if (_sites == null)
- throw new Exception("Invalid Site value");
- double realRate = 0;
- //int votes;
- if (string.IsNullOrEmpty(mediaId) == false)
- GetRating(string.Format("SELECT SUM(votes) AS votes, SUM(rating) AS rating FROM Ratings2 WHERE mediaId='{0}' and productId='{1}' GROUP BY mediaId", newsId, productId), ref realRate, out vote);
- else
- GetRating(string.Format("SELECT SUM(votes) AS votes, SUM(rating) AS rating FROM Ratings2 WHERE newsId='{0}' AND mediaId IS NULL AND productId='{1}' GROUP BY newsId", newsId, productId), ref realRate, out vote);
- rate = realRate;
-
- //return realRate;
- }
- //Encours GetMostViewed
- /// <summary>
- /// donne la liste des plus vus pour ce serveur...
- /// </summary>
- /// <param name="lstId"></param>
- /// <param name="productId"></param>
- /// <returns></returns>
- public override string GetMostViewed(string lstId, string productId, string topicId, TimeSpan MaxAge, int MaxEntries)
- {
- throw new NotImplementedException();
- }
- /// <summary>
- /// Donne la listes des medias les plus votés
- /// </summary>
- /// <param name="lstId"></param>
- /// <param name="productId"></param>
- /// <returns></returns>
- public override string GetHeartRatedList(string lstId, string productId, string topicId, TimeSpan MaxAge, int MaxEntries, string lang )
- {
- string sqlLang;
-
- if (string.IsNullOrEmpty(lang))
- {
- sqlLang = "";
- }
- else
- {
- sqlLang = string.Format(" AND [lang] = '{0}' ", lang);
- }
-
- string query = string.Format(
- "SELECT lang, topicId, newsId, MAX([rating]/[votes]) AS averageRating, SUM([votes]) AS votes " +
- "FROM [Ratings2] WHERE NOT [mediaId] IS NULL AND [dateUpdated] > CONVERT(datetime, '{0}', 120) " +
- "AND [productId]='{1}' {2} GROUP BY lang, topicId, newsId ORDER BY [averageRating] DESC, [votes] DESC",
- DateTime.UtcNow.Subtract(MaxAge).ToString("yyyy-MM-dd"), productId, sqlLang );
- //en cours
- #if DEBUG && TRACE_REQUEST
- Process.Trace(query, "GetHeartRatedList", System.Diagnostics.EventLogEntryType.Information);
- #endif
-
- return TopicBuildRated(query, topicId, MaxEntries, new StorageServer(), false);
- }
- /// <summary>
- /// Donne la liste les Articles les mieux votés
- /// </summary>
- /// <param name="lstId"></param>
- /// <param name="productId"></param>
- /// <returns></returns>
- public override string GetArticleRatedList(string lstId, string productId, string topicId, TimeSpan MaxAge, int MaxEntries, string lang )
- {
- #if DEBUG && DEBUGRATEDLIST
- System.Diagnostics.Debugger.Break();
- #endif
- string sqlLang ;
-
- if (string.IsNullOrEmpty(lang))
- {
- sqlLang = "";
- }
- else
- {
- sqlLang = string.Format(" AND [lang] = '{0}' ", lang);
- }
-
- string query = string.Format(
- "SELECT lang, topicId, newsId, MAX([rating]/[votes]) AS averageRating, SUM([votes]) AS votes " +
- "FROM [Ratings2] WHERE [mediaId] IS NULL AND [dateUpdated] > CONVERT(datetime, '{0}', 120) " +
- "AND [productId]='{1}' {2} GROUP BY lang, topicId, newsId ORDER BY [averageRating] DESC, [votes] DESC"
- , DateTime.UtcNow.Subtract(MaxAge).ToString("yyyy-MM-dd"), productId ,sqlLang );
- //en cours
- #if DEBUG && TRACE_REQUEST
- Process.Trace(query, "GetArticleRatedList", System.Diagnostics.EventLogEntryType.Information);
- #endif
- return TopicBuildRated(query, topicId, MaxEntries, new StorageServer(), false);
- }
-
-
- private void getDegMinSec(string value, ref int deg ,ref int min , ref int sec)
- {
- float Valeur = value.toFloat(0f) ;
-
- deg = (int) Math.Truncate(Valeur);
- Valeur = (Valeur - (float) deg ) * 60f;
-
- min = (int)Math.Truncate(Valeur);
- Valeur = (Valeur - (float)min) * 60f;
-
- sec = (int)Math.Truncate(Valeur);
-
- }
-
- public override string GetAroundMe(string latitude, string longitude, string range ,int MaxEntries, string lang )
- {
-
- //ttot
-
- // Determination de la plage
- /* int degLat = 0;
- int minLat = 0;
- int secLat = 0;
-
- int degLong = 0;
- int minLong = 0;
- int secLong = 0;
- */
-
- string sWhere = " where ";
- string sWhereLatitudeSup ="" ;
- string sWhereLatitudeInf ="" ;
- string sWhereLongitudeSup ="" ;
- string sWhereLongitudeInf ="" ;
-
- Decimal oLat = latitude.toDecimal(0m);
- Decimal oLong = longitude.toDecimal(0m);
- Sexagesimal sRange = new Sexagesimal (range, true);
- Decimal Valeur = range.toDecimal(0m) / 111.195m;
-
- Decimal latitudeBornesup ;
- Decimal latitudeBorneInf ;
-
- latitudeBornesup = oLat + Valeur ;
- if( latitudeBornesup > 90m)
- {
- // il faut découper
- sWhereLatitudeSup = string.Format(" latitude < 90 or ( latitude > {0:0.########} and latitude <90 and longitude >-180 and longitude <180) ", 90m - (latitudeBornesup - 90m));
- }
- else
- {
- sWhereLatitudeSup = string.Format(" latitude < {0:0.########} ", latitudeBornesup.ToString("G",CultureInfo.InvariantCulture) );
- }
-
- latitudeBorneInf = oLat - Valeur ;
- if ( latitudeBorneInf <-90m)
- {
- // il faut découper
- sWhereLatitudeInf = string.Format (" latitude > -90 or ( latitude < {1} and latitude >-90 and longitude >-180 and longitude <180) ", -90m +(latitudeBornesup -90m) );
- }
- else
- {
- sWhereLatitudeInf = string.Format(" latitude > {0:0.########}", latitudeBorneInf.ToString("G", CultureInfo.InvariantCulture));
- }
-
- Decimal longitudeBordSup ;
- Decimal longitudeBordInf;
-
- longitudeBordSup = oLong + Valeur ;
- longitudeBordInf = oLong - Valeur ;
-
- if( longitudeBordSup > 180m )
- {
- // on a dépasser le bord de la terre on tombe... ha non c'est rond.
- sWhereLongitudeSup = string.Format(" (longitude < {0:0.########} or (longitude > -180 and longitude < {1:0.########} ) ", longitudeBordSup.ToString("G", CultureInfo.InvariantCulture), -180m + (longitudeBordSup - 180m));
-
- }
- else
- {
- sWhereLongitudeSup = string.Format(" longitude < {0:0.########} ", longitudeBordSup.ToString("G", CultureInfo.InvariantCulture));
- }
-
- if(longitudeBordInf <-180m )
- {
- sWhereLongitudeSup = string.Format(" (longitude > {0:0.########} or (longitude > {1:0.########} and longitude < 180 ) ", longitudeBordSup.ToString("G", CultureInfo.InvariantCulture), 180m - (longitudeBordInf - 180m));
- }
- else
- {
- sWhereLongitudeInf = string.Format(" longitude > {0:0.########}", longitudeBordInf.ToString("G", CultureInfo.InvariantCulture));
- }
-
- sWhere = string.Format ("{4} {0} and {1} and {2} and {3}" , sWhereLatitudeInf , sWhereLatitudeSup , sWhereLongitudeInf ,sWhereLongitudeSup , sWhere );
-
- string query = string.Format(
- "SELECT * from Localization {0} ", sWhere );
- if (!string.IsNullOrEmpty(lang))
- {
- query = string.Format("{0} and lang='{1}'", query, lang);
- }
- #if DEBUG && TRACEAROUND
- Process.Trace(query, System.Diagnostics.EventLogEntryType.Information);
- #endif
-
- return TopicBuildAround(query,new StorageServer() , MaxEntries );
-
- }
-
- /// <summary>
- /// Trace viewed.
- /// </summary>
- /// <param name="topicImplementation"></param>
- /// <param name="productId"></param>
- /// <param name="newsId"></param>
- /// <param name="mediaId"></param>
- /// <param name="device"></param>
- public override void InsertViewed(TopicImplementation topicImplementation, string productId, string newsId, string mediaId, string device)
- {
- #if DEBUG && DEBUGINSERT
- System.Diagnostics.Debugger.Break();
-
- #endif
- // Insert viewed
- foreach (var sqlProcessor in _sqlProcessorList)
- sqlProcessor.Add(new SqlNewsViewed(productId, topicImplementation.Id, newsId, mediaId, topicImplementation.Lang, device));
-
- }
-
-
-
-
- private XslCompiledTransform GetXsltCT(string path)
- {
- lock (_Xslt)
- {
- if (!_Xslt.ContainsKey(path))
- {
- XslCompiledTransform newX = new XslCompiledTransform(System.Diagnostics.Debugger.IsAttached);
- newX.Load(path);
- _Xslt.Add(path, newX);
-
- }
- }
-
- return (XslCompiledTransform)_Xslt[path];
- }
-
- private string GetMediaName(string href, TopicImplementation topic)
- {
- var pattern = topic["mediaNamePattern"];
- var regEx = new Regex((string.IsNullOrEmpty(pattern)) ? "(.)*" : pattern);
-
- return regEx.Match(Path.GetFileNameWithoutExtension(href)).ToString();
- }
-
- public void GetRating(string query, ref double rate, out int votes)
- {
- // Valeur par défaut
- votes = 0;
-
- // Ajout du rating
- foreach (var processor in _sqlProcessorList)
- using (var sqlRatingReader = new SqlDataAdapter(query, processor.ConnectionString))
- {
- using (var sqlRatingTable = new DataTable())
- {
- try
- {
- sqlRatingReader.Fill(sqlRatingTable);
- }
- catch
- {
- continue;
- }
-
- if (sqlRatingTable.Rows.Count == 0)
- votes = 0;
- else
- {
- votes = ((int)sqlRatingTable.Rows[0]["votes"] + 1);
- rate = ((double)sqlRatingTable.Rows[0]["rating"] + rate) / votes;
- }
-
- break;
- }
- }
- }
-
- private void MakeTopic(object stateInfo)
- {
- MakeTopic((TopicImplementation)((object[])stateInfo)[0], (bool)((object[])stateInfo)[1], (ManualResetEvent)((object[])stateInfo)[2]);
- }
-
- private void MakeTopic(TopicImplementation topic, bool refresh, ManualResetEvent doneEvent)
- {
- var storage = new StorageServer();
- #if DBG_PERFORMANCE_TRACE
- var timer = new System.Diagnostics.Stopwatch();
-
- // Démarage compteur
- timer.Start();
-
- if (_levelTrace.TraceTimeMakeTopic == true )
- {
- Process.Trace(string.Format(" Start Processing {0} at {1}", topic.Id, DateTime.Now), System.Diagnostics.EventLogEntryType.Information);
- }
- #endif
- try
- {
- // Traitement des différents type de topic
- switch (topic.Type)
- {
- case TopicImplementation.TopicType.heart:
- case TopicImplementation.TopicType.rated:
- // Construction du topic et stockage
- // TO DO a reprendre et a tester...
- XmlDocument topicRated = new XmlDocument();
- topicRated.LoadXml(TopicBuildRated(topic, storage, refresh));
- using (var storageTopicFile = storage.Store(Constants._storageTopicFormatName, Key, string.Format("{0}.xml", topic.Id)))
- topicRated.Save(storageTopicFile);
-
- break;
-
- case TopicImplementation.TopicType.videorama:
- case TopicImplementation.TopicType.standard:
- // Récupération du fichier index NewsML
- NewsML index = TopicLoadDocument(topic, storage);
- #if DBG_PERFORMANCE_TRACE
-
- if (_levelTrace.TraceTimeMakeTopic == true)
- {
- Process.Trace(string.Format("TopicLoadDocument for topicId '{0}' processed after {1} seconds.", topic.Id, timer.ElapsedMilliseconds / 1000), System.Diagnostics.EventLogEntryType.SuccessAudit);
- }
- #endif
- // Transformation du document et stockage
- if (index != null)
- {
- String topicContent = TopicBuildStandard(index, topic, storage, topic.MaxEntries, refresh);
-
- #if DBG_PERFORMANCE_TRACE
- if (_levelTrace.TraceTimeMakeTopic == true)
- {
- Process.Trace(string.Format("TopicBuildStandard for topicId '{0}' processed after {1} seconds.", topic.Id, timer.ElapsedMilliseconds / 1000), System.Diagnostics.EventLogEntryType.SuccessAudit);
- }
- #endif
- if (String.IsNullOrEmpty(topicContent) == false)
- {
- Stream output = storage.Store(Constants._storageTopicFormatName, Key, string.Format("{0}.xml", topic.Id));
-
- if (output != null)
- {
- TextWriter wr = new StreamWriter(output, Encoding.UTF8);
-
- wr.Write(topicContent);
-
- wr.Flush();
- output.Close();
- }
- }
- }
-
- break;
-
- case TopicImplementation.TopicType.buildedvideorama:
- // Construction du topic et stockage
- var topicVideorama = TopicBuildVideorama(topic, storage, refresh);
- using (var storageTopicFile = storage.Store(Constants._storageTopicFormatName, Key, string.Format("{0}.xml", topic.Id)))
- topicVideorama.Save(storageTopicFile);
-
- break;
-
- /* case TopicImplementation.TopicType.magazin:
- case TopicImplementation.TopicType.diaporama:
- var indexd = TopicLoadDocument(topic, storage);
- if (indexd != null)
- {
- String topicContent = TopicBuildMagazin(indexd, topic, storage, topic.MaxEntries, refresh,"");
-
- #if DBG_PERFORMANCE_TRACE
- if (_levelTrace.TraceTimeMakeTopic == true)
- {
- Process.Trace(string.Format("TopicBuildStandard for topicId '{0}' processed after {1} seconds.", topic.Id, timer.ElapsedMilliseconds / 1000), System.Diagnostics.EventLogEntryType.SuccessAudit);
- }
- #endif
- if (String.IsNullOrEmpty(topicContent) == false)
- {
- Stream output = storage.Store(Constants._storageTopicFormatName, Key, string.Format("{0}.xml", topic.Id));
-
- if (output != null)
- {
- TextWriter wr = new StreamWriter(output, Encoding.UTF8);
-
- wr.Write(topicContent);
-
- wr.Flush();
- output.Close();
- }
- }
- }
- break;*/
- case TopicImplementation.TopicType.alert:
- //TODO implementer fonction alert
- break;
-
- case TopicImplementation.TopicType.diaporama:
- case TopicImplementation.TopicType.magazin:
- if (topic.IsSubTopic() == false)
- TopicLoadTableAndDoneTopics(topic, storage);
- else
- {
- // cas de l'update d'un topic spé Ipad de merde...
-
- NewsML index1 = TopicLoadDocument(topic, storage);
- // Transformation du document et stockage
- if (index1 != null)
- {
- String topicContent = TopicBuildStandard(index1, topic, storage, topic.MaxEntries, refresh);
- if (String.IsNullOrEmpty(topicContent) == false)
- {
- Stream output = storage.Store(Constants._storageTopicFormatName, Key, string.Format("{0}.xml", topic.Id));
- if (output != null)
- {
- TextWriter wr = new StreamWriter(output, Encoding.UTF8);
- wr.Write(topicContent);
- wr.Flush();
- output.Close();
- }
- }
- }
- }
-
- break;
-
- }
- }
- catch (ThreadAbortException)
- {
- }
- catch (Exception e)
- {
- Process.Trace(string.Format("Can't process topic {0}", topic.Id), e.ToString(), System.Diagnostics.EventLogEntryType.Error);
- this.Set("Topic process error", MessageSection.Processing.ToString(), System.Diagnostics.EventLogEntryType.Warning);
- }
- finally
- {
- #if DBG_PERFORMANCE_TRACE
- timer.Stop();
-
-
- if (_levelTrace.TraceTimeMakeTopic == true)
- {
- Process.Trace(string.Format("Topic '{0}' processed in {1} seconds.", topic.Id, timer.ElapsedMilliseconds / 1000), System.Diagnostics.EventLogEntryType.SuccessAudit);
- }
- #endif
- }
- // Attente fin des traitements
- if (doneEvent != null)
- doneEvent.Set();
- }
-
- private void MakeTopicFromThread(object state)
- {
- while (true)
- try
- {
- // Traitement
- MakeTopic((TopicImplementation)state, false, null);
-
- // Pause dynamique
- Thread.Sleep(((TopicImplementation)state).DynamicDelay);
- }
- catch (ThreadAbortException)
- {
- }
- }
-
- private void NewsBuildHtml(XmlElement extensions, XmlDocument news, TopicImplementation topic, string uno, StorageServer storage)
- {
- // Stockage et transformation de la news au format html
- if (String.IsNullOrEmpty((string)topic["htmlModel"]) == false)
- {
- using (var storageHtmlNews = storage.Store(Constants._storageNewsFormatName, Key, string.Format("{0}.htm", uno)))
- {
- XslCompiledTransform transform = GetXsltCT((string)topic["htmlModel"]);
- XsltArgumentList arguments = new XsltArgumentList();
-
- arguments.AddParam("NewsExtension", String.Empty, extensions);
- arguments.AddParam("Version", string.Empty, Version);
- arguments.AddParam("ImageActive", string.Empty, Convert.ToBoolean ( ImageActive )) ;
-
- transform.Transform(news, arguments, storageHtmlNews);
- }
- }
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="doc">Noeud ou on rajoute l'attribut</param>
- /// <param name="name">Nom de l'attribut</param>
- /// <param name="value">Valeur </param>
- /// <returns></returns>
- public XmlAttribute createAttribute(XmlDocument doc, String name, String value)
- {
- XmlAttribute attr = doc.CreateAttribute(name);
-
- attr.Value = value;
-
- return attr;
- }
-
- void appendXmlDateAttribute(XmlElement element, XmlDocument doc, String name, DateTime? dt)
- {
- if (dt != null && dt.HasValue)
- {
- String dtStr = XmlConvert.ToString(dt.Value, XmlDateTimeSerializationMode.RoundtripKind);
-
- element.Attributes.Append(createAttribute(doc, name, dtStr));
- }
- }
-
- private XmlElement NewsExtendDocument(XmlDocument news, List<Media> photoList, List<Media> documentsList, TopicImplementation topic, string uno, StorageServer storage, int XsltVersion)
- {
- XmlElement NewsExtension;
-
- Int16 pos = 0;
- Int16 previewB = 0;
-
- NewsExtension = news.CreateElement("NewsExtension");
- //NewsExtension.Attributes.Append(createAttribute(news, "id", topic.Id));
- if (topic.Id.Contains("__"))
- NewsExtension.Attributes.Append(createAttribute(news, "id", string.Format("{0:X}", topic.Id.Substring(topic.Id.IndexOf("__") + 2).MyGetHashCode())));
- else
- NewsExtension.Attributes.Append(createAttribute(news, "id", string.Format("{0:X}",topic.Id.MyGetHashCode())));
- //BUG le bon id commence par topic.Id.Substring(topic.Id.IndexOf("__")+2).MyGetHashCode()
- NewsExtension.Attributes.Append(createAttribute(news, "uno", uno));
- if (topic.UseBase64 == false)
- {
- NewsExtension.Attributes.Append(createAttribute(news, "DontUseDataUrl", "1"));
- }
-
- //NewsExtension.Attributes.Append(createAttribute(news, "Version", XsltVersion.ToString() ));
-
- // Traitement des dates
- if (XsltVersion == 1)
- {
- // on reste avec l'ancien traitement on ne sait jamais
- appendXmlDateAttribute(NewsExtension, news, "dateAndTime", news.DocumentElement.FindDate("/NewsML/NewsEnvelope/DateAndTime"));
- appendXmlDateAttribute(NewsExtension, news, "firstCreated", news.DocumentElement.FindDate("/NewsML/NewsItem/NewsManagement/FirstCreated"));
- appendXmlDateAttribute(NewsExtension, news, "thisRevisionCreated", news.DocumentElement.FindDate("/NewsML/NewsItem/NewsManagement/ThisRevisionCreated"));
- }
- else
- {
- NewsExtension.Attributes.Append(createAttribute(news, "dateAndTime", news.DocumentElement.FindDateToXmlUtcString("/NewsML/NewsEnvelope/DateAndTime")));
- NewsExtension.Attributes.Append(createAttribute(news, "firstCreated", news.DocumentElement.FindDateToXmlUtcString("/NewsML/NewsItem/NewsManagement/FirstCreated")));
- NewsExtension.Attributes.Append(createAttribute(news, "thisRevisionCreated", news.DocumentElement.FindDateToXmlUtcString("/NewsML/NewsItem/NewsManagement/ThisRevisionCreated")));
- }
- // Traitement des photos
-
- XmlElement ContainerNewsComponent = null ;
-
- string mediaCurrentId ="";
- Boolean newMediaId = false;
-
- foreach (Media media in photoList)
- {
- //XmlElement NewsComponent1 = news.CreateElement("NewsComponent");
- if (mediaCurrentId != media.Duid)
- {
- newMediaId = true;
- mediaCurrentId = media.Duid;
- }
-
-
- if (XsltVersion > 1 && newMediaId == true )
- {
- ContainerNewsComponent = news.CreateElement("NewsComponent");
- NewsExtension.AppendChild(ContainerNewsComponent);
- pos = 0; previewB = 0;
- newMediaId = false;
- }
-
-
- XmlElement NewsComponent;
- NewsComponent = news.CreateElement("NewsComponent");
- if (XsltVersion > 1)
- {
- ContainerNewsComponent.AppendChild(NewsComponent);
- }
- else
- {
- NewsExtension.AppendChild(NewsComponent);
- }
-
- //favori : Ici sont passées les Parametres...
- //NewsExtension.Attributes.Append(createAttribute(news, "uno", uno));
-
- if (XsltVersion == 1)
- {
- NewsComponent.Attributes.Append(createAttribute(news, "duid", media.Duid));
- NewsComponent.Attributes.Append(createAttribute(news, "hduid", string.Format("#{0}", media.Duid)));
-
- }
- else
- {
- if (pos == 0)
- {
- ContainerNewsComponent.Attributes.Append(createAttribute(news, "duid", media.Duid));
- ContainerNewsComponent.Attributes.Append(createAttribute(news, "huid", string.Format("#{0}", media.AbsoluteWebPath)));
- }
- pos += 1;
- }
-
- // insertion de la preview
- if (media.Role.Equals( _PreviewRole, StringComparison.InvariantCultureIgnoreCase ))
- {
- ContainerNewsComponent.Attributes.Append(createAttribute(news, "preview", string.Format("{0}", media.AbsoluteWebPath)));
-
- previewB += 1;
- }
-
- NewsComponent.Attributes.Append(createAttribute(news, "role", media.Role));
- // est-ce une video
- Boolean video= false;
- if (media.Role.ToLower() == "iformat" || media.Role.ToLower() == "video" || media.AbsoluteWebPath.EndsWith("mp4"))
- {
- NewsComponent.Attributes.Append(createAttribute(news, "video", "1"));
- video = true;
- }
- else
- {
- NewsComponent.Attributes.Append(createAttribute(news, "video", "0"));
- video = false;
- }
-
-
- if (topic.UseBase64 == true )
- {
- NewsComponent.Attributes.Append(createAttribute(news, "href", string.Format("{0}/{1}/{2}/{3}/{4}",
- topic.ProductServiceName,
- _storagePhotosFormatName,
- Key,
- Storage.StorageServer.GetHashFolder(media.Name),
- media.Name.UrlEncode()
- )
- ));
-
- }
- else
- {
- NewsComponent.Attributes.Append(createAttribute(news, "href", media.AbsoluteWebPath));
- }
- NewsComponent.Attributes.Append(createAttribute(news, "width", media.Width));
- NewsComponent.Attributes.Append(createAttribute(news, "height", media.Height));
-
- // Ecriture fichier encodé
- if (topic.UseBase64 && video == false)
- {
- if (storage.Exists(_storagePhotosFormatName, Key, media.Name))
- {
- using (var file = storage.Restore("Photos", Key, media.Name, true))
- {
- NewsComponent.InnerText = StorageServer.FileToBase64(file);
- }
- }
- }
- else
- {
- // NewsComponent.InnerText = media.AbsoluteWebPath;
- }
- }
-
-
-
- // on va maintenant prendre la liste des documents
- if (XsltVersion > 1)
- {
- XmlElement NewsComponent1 = news.CreateElement("NewsComponent");
- ((XmlElement)NewsComponent1).SetAttribute("role", "document");
- foreach (Media media in documentsList)
- {
- XmlElement docNewsComponent = news.CreateElement("NewsComponent");
- // NewsExtension.AppendChild(docNewsComponent);
- docNewsComponent.Attributes.Append(createAttribute(news, "duid", media.Duid));
- docNewsComponent.Attributes.Append(createAttribute(news, "role", "document"));
- docNewsComponent.Attributes.Append(createAttribute(news, "href", media.AbsoluteWebPath));
- NewsComponent1.AppendChild(docNewsComponent);
- }
-
- NewsExtension.AppendChild(NewsComponent1);
- }
-
- /* Process.Trace(" News Extension ",
- string.Format("version {0} ", XsltVersion),
- System.Diagnostics.EventLogEntryType.Information);
- */
- return NewsExtension;
- }
-
- private News NewsLoadDocument(NewsComponent newsComponent, TopicImplementation topic, StorageServer storage, DateTime dateReference)
- {
- return NewsLoadDocument(((NewsItemRef)newsComponent.Items[0]).NewsItem, topic, storage, dateReference);
- }
-
- private News NewsLoadDocument(String newsItemRef, TopicImplementation topic, StorageServer storage, DateTime dateReference)
- {
- String fileName = Path.GetFileName(newsItemRef);
- StorageFileInfo storedNewsInfo = storage.Info(Constants._storageNewsFormatName, Key, fileName);
- News news = new News(Path.GetFileNameWithoutExtension(fileName));
- Boolean srcNewsExists = false;
- String livraisonNewsPath = string.Empty;
- DateTime? ThisRevisionCreated;
- news.State = News.NewsState.New;
-
- try
- {
- // Recherche de la news
- foreach (var directoryName in topic.Folders)
- {
- livraisonNewsPath = Path.Combine(directoryName, newsItemRef);
- srcNewsExists = StorageServer.FileExists(livraisonNewsPath);
-
- if (srcNewsExists)
- {
- news.LastModificationDate = File.GetLastWriteTime(livraisonNewsPath);
- break;
- }
- }
-
- // Détermination de l'état de la news
- // News locale présente
- if (srcNewsExists)
- {
- // Ancienne news stockée existe ?
- using (var localNewsFile = StorageServer.FileOpen(livraisonNewsPath))
- {
- if (storedNewsInfo == null)
- {
- // Nouvelle news
- news.Document.Load(localNewsFile);
-
- news.Path = livraisonNewsPath;
- news.State = News.NewsState.New;
- #if SERVICE
-
- lock (GBLock)
- {
- AFP.IPhone.Plugins.GetCourseId.GetRefIdSoapClient Client = new AFP.IPhone.Plugins.GetCourseId.GetRefIdSoapClient();
- Client.ClientCredentials.Windows.AllowNtlm = true;
-
- news.Uid = Client.GetCourseId(topic.Id, news.Uno);
- };
- #endif
- }
- else
- {
- // La news a-t-elle été modifiée ? et la feuille de style a elle été modifiée?
- if (storedNewsInfo.LastModified >= news.LastModificationDate && topic.XsltDate <= storedNewsInfo.LastModified)
- {
- // La news est ancienne
- news.Document.Load(storedNewsInfo.Path);
- news.State = News.NewsState.Stored;
- try
- {
- news.Uid = Convert.ToInt64(news.Document.SelectSingleNode("NewsML").Attributes["absoluteindex"].Value);
- }
- finally
- {
- }
- }
- else
- {
- // Nouvelle version de la news
- news.Document.Load(localNewsFile);
- news.Path = livraisonNewsPath;
- #if SERVICE
- lock (GBLock)
- {
- /*TO DO appel au service WEB !!! */
- // TO DO a voir à factoriser le client
- AFP.IPhone.Plugins.GetCourseId.GetRefIdSoapClient Client = new AFP.IPhone.Plugins.GetCourseId.GetRefIdSoapClient();
- Client.ClientCredentials.Windows.AllowNtlm = true;
- news.Uid = Client.GetCourseId(topic.Id, news.Uno);
- };
-
- #endif
- news.State = News.NewsState.New;
- }
- }
- }
- // La news est ancienne
- }
- else
- {
- if (storedNewsInfo == null)
- {
-
- String Folders = "";
- foreach (string cFolder in topic.Folders)
- {
- Folders = string.Format("{0} ; {1}", cFolder, Folders);
- }
-
- Process.Trace("Bug Store", string.Format("NO DOCUMENT FOUND {0}-{1}. Folder : {2}", topic.Id, newsItemRef, Folders), System.Diagnostics.EventLogEntryType.Information);
-
- // La news n'est pas archivée
- news.State = News.NewsState.Invalid;
- }
- else
- {
- //Process.Trace("Bug Store", string.Format("REUSE STORED DOCUMENT {0}-{1}", topic.Id, newsItemRef), System.Diagnostics.EventLogEntryType.Information);
-
- // La news est archivée
- if (topic.XsltDate <= storedNewsInfo.LastModified)
- {
- news.Document.Load(storedNewsInfo.Path);
- try
- {
- news.Uid = Convert.ToInt64(news.Document.SelectSingleNode("NewsML").Attributes["absoluteindex"].Value);
- }
- finally
- {
- }
- news.State = News.NewsState.Stored;
- }
- else
- {
- // la feuille de style a été modifiée on force le recalcul
- news.Document.Load(storedNewsInfo.Path);
- news.State = News.NewsState.New;
- }
- }
- }
-
-
- // Vérification date de validité et transformation éventuelle
- if (news.State != News.NewsState.Invalid)
- {
- if (string.IsNullOrEmpty(topic.NewsXslt) == false)
- {
- using (var newsStream = new MemoryStream())
- {
- // Transformation de la news
- GetXsltCT(topic.NewsXslt).Transform(news.Document, null, newsStream);
- // Récupération
- newsStream.Position = 0;
- news.Document.Load(newsStream);
- }
- }
-
- //ENCOURS si message alert on la prépare
- if (topic.CanBeAlert)
…
Large files files are truncated, but you can click here to view the full file