PageRenderTime 55ms CodeModel.GetById 46ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/source/app/NOS.Registration/AutoRegistrationPlugin.cs

http://github.com/agross/netopenspace
C# | 231 lines | 199 code | 32 blank | 0 comment | 10 complexity | 6488116207c69bccce6a4ce57559606c MD5 | raw file
  1using System;
  2using System.Linq;
  3
  4using NOS.Registration.EntryPositioning;
  5
  6using ScrewTurn.Wiki.PluginFramework;
  7
  8namespace NOS.Registration
  9{
 10	public class AutoRegistrationPlugin : IFormatterProviderV30
 11	{
 12		readonly IPluginConfiguration _configuration;
 13		readonly IEntryFormatter _entryFormatter;
 14		readonly IFileReader _fileReader;
 15		readonly ILogger _logger;
 16		readonly INotificationSender _notificationSender;
 17		readonly IPageFormatter _pageFormatter;
 18		readonly IPageRepository _pageRepository;
 19		readonly IRegistrationRepository _registrationRepository;
 20		readonly ISettings _settings;
 21		readonly ISynchronizer _synchronizer;
 22		IHostV30 _host;
 23
 24		public AutoRegistrationPlugin()
 25			: this(new CrossContextSynchronizer(),
 26			       new RegistrationRepository(),
 27			       new PageRepository(),
 28			       new PageFormatter(new DefaultLogger(),
 29			                         new DefaultOpinionEvaluator(
 30			                         	new IHasOpinionAboutEntryPosition[]
 31			                         	{
 32			                         		new AtListEnd(),
 33			                         		new AtListEndWhenSponsoring(),
 34			                         		new AtWaitingListEndWhenHardLimitReached()
 35			                         	})),
 36			       new NVelocityEntryFormatter(),
 37			       new EmailNotificationSender(),
 38			       new DefaultLogger(),
 39			       new DefaultPluginConfiguration(),
 40			       new DefaultFileReader(),
 41			       new WikiSettings())
 42		{
 43		}
 44
 45		public AutoRegistrationPlugin(ISynchronizer synchronizer,
 46		                              IRegistrationRepository registrationRepository,
 47		                              IPageRepository pageRepository,
 48		                              IPageFormatter pageFormatter,
 49		                              IEntryFormatter entryFormatter,
 50		                              INotificationSender notificationSender,
 51		                              ILogger logger,
 52		                              IPluginConfiguration configuration,
 53		                              IFileReader fileReader,
 54		                              ISettings settings)
 55		{
 56			_synchronizer = synchronizer;
 57			_fileReader = fileReader;
 58			_settings = settings;
 59			_registrationRepository = registrationRepository;
 60			_pageRepository = pageRepository;
 61			_pageFormatter = pageFormatter;
 62			_entryFormatter = entryFormatter;
 63			_notificationSender = notificationSender;
 64			_logger = logger;
 65			_configuration = configuration;
 66		}
 67
 68		#region IFormatterProvider Members
 69		public void Init(IHostV30 host, string config)
 70		{
 71			_host = host;
 72
 73			if (Configure(config))
 74			{
 75				_host.UserAccountActivity += Host_UserAccountActivity;
 76				_notificationSender.Configure(_host, _settings);
 77
 78				_logger.Info(String.Format("Waiting list is enabled after {0} attendees with a hard limit of {1}.",
 79				                           _configuration.MaximumAttendees,
 80				                           _configuration.HardLimit),
 81				             "SYSTEM");
 82			}
 83			else
 84			{
 85				_logger.Error("The auto registration plugin will be disabled.", "SYSTEM");
 86			}
 87		}
 88
 89		public void Shutdown()
 90		{
 91		}
 92
 93		public ComponentInformation Information
 94		{
 95			get { return new ComponentInformation(GetType().Name, "Alexander Gro�", "1.1", "http://therightstuff.de", null); }
 96		}
 97
 98		public string ConfigHelpHtml
 99		{
100			get { return String.Empty; }
101		}
102
103		public string Format(string raw, ContextInformation context, FormattingPhase phase)
104		{
105			return raw;
106		}
107
108		public string PrepareTitle(string title, ContextInformation context)
109		{
110			return title;
111		}
112
113		public bool PerformPhase1
114		{
115			get { return false; }
116		}
117
118		public bool PerformPhase2
119		{
120			get { return false; }
121		}
122
123		public bool PerformPhase3
124		{
125			get { return false; }
126		}
127
128		public int ExecutionPriority
129		{
130			get { return 100; }
131		}
132		#endregion
133
134		bool Configure(string config)
135		{
136			var errors = _configuration.Parse(config ?? String.Empty, _pageRepository);
137
138			errors.Each(x => _logger.Error(x, "SYSTEM"));
139
140			return !errors.Any();
141		}
142
143		void Host_UserAccountActivity(object sender, UserAccountActivityEventArgs e)
144		{
145			if (e.Activity != UserAccountActivity.AccountActivated)
146			{
147				return;
148			}
149
150			_synchronizer.Lock(() =>
151				{
152					var failed = false;
153					User user = null;
154					try
155					{
156						user = _registrationRepository.FindByUserName(e.User.Username);
157						if (user == null)
158						{
159							return;
160						}
161
162						var pageInfo = _pageRepository.FindPage(_configuration.PageName);
163						if (pageInfo == null)
164						{
165							_logger.Error(String.Format("The attendee page '{0}' does not exist.", _configuration.PageName), "SYSTEM");
166							throw new Exception("Attendee page does not exist.");
167						}
168
169						PageContent pageContent;
170						try
171						{
172							pageContent = _host.GetPageContent(pageInfo);
173						}
174						catch (Exception ex)
175						{
176							_logger.Error(String.Format("The attendee page's content ('{0}') could not be loaded: {1}", _configuration.PageName, ex),
177								          "SYSTEM");
178							throw;
179						}
180
181						try
182						{
183							string entry = _entryFormatter.FormatUserEntry(user, _settings, _configuration.EntryTemplate);
184							string newContent = _pageFormatter.AddEntry(pageContent.Content, entry, user, _configuration);
185
186							_pageRepository.Save(pageInfo, pageContent.Title, user.UserName, _configuration.Comment, newContent);
187
188							_logger.Info("User entry written successfully", user.UserName);
189						}
190						catch (Exception ex)
191						{
192							_logger.Error(String.Format("Could not add the user's entry to the attendee list: {0}", ex), "SYSTEM");
193							throw;
194						}
195					}
196					catch
197					{
198						failed = true;
199					}
200					finally
201					{
202						if (user != null)
203						{
204							string message = LoadEmailTemplate(failed);
205							message = FillTemplate(message, user);
206
207							_notificationSender.SendMessage(e.User.Email, _configuration.Comment, message);
208							_notificationSender.SendMessage(_settings.ContactEmail, _configuration.Comment, message);
209						}
210					}
211				});
212		}
213
214		string LoadEmailTemplate(bool failed)
215		{
216			string file = typeof(AutoRegistrationPlugin).FullName + ".SuccessMessage";
217
218			if (failed)
219			{
220				file = typeof(AutoRegistrationPlugin).FullName + ".FailureMessage";
221			}
222
223			return _fileReader.Read(file);
224		}
225
226		string FillTemplate(string template, User user)
227		{
228			return _entryFormatter.FormatUserEntry(user, _settings, template);
229		}
230	}
231}