view Agendas/trunk/src/Agendas.Twitter/TwitterPublicador.cs @ 134:a4ef6874ec81

Se termina prueba unitaria que verifica que se cree el evento solo si la acción es Agendar.
author alabra
date Sun, 17 Jul 2011 13:58:31 -0400
parents 17531db40d4e
children 734d3f0853bf
line wrap: on
line source

using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using AltNetHispano.Agendas.Domain;
using AltNetHispano.Agendas.Twitter.Writers;
using Twitterizer;

namespace AltNetHispano.Agendas.Twitter
{
	public class TwitterPublicador : IPublicador
	{
		private readonly IDictionary<Accion, ITwitterWriter> _writers;
		private readonly ITwitterAdapter _twitterAdapter;

		public TwitterPublicador()
			: this(new TwitterAdapter())
		{
		}

		public TwitterPublicador(ITwitterAdapter twitterAdapter)
		{
			_writers = new Dictionary<Accion, ITwitterWriter>
			            	{
			            		{Accion.Proponer, new ProponerTwitterWriter()},
			            		{Accion.Agendar, new AgendarTwitterWriter()},
			            		{Accion.Confirmar, new ConfirmarTwitterWriter()},
			            		{Accion.Publicar, new PublicarTwitterWriter()}
			            	};

			_twitterAdapter = twitterAdapter;
		}

		private const int LIMITE_MENSAJE = 140;

		private static string ConsumerKey
		{
			get { return ConfigurationManager.AppSettings["consumerKeyAppTwitt"]; }
		}

		private static string ConsumerSecret
		{
			get { return ConfigurationManager.AppSettings["consumerSecretAppTwitt"]; }
		}


		private static string AccessToken
		{
			get { return ConfigurationManager.AppSettings["accessTokenAppTwitt"]; }
		}


		private static string AccessTokenSecret
		{
			get { return ConfigurationManager.AppSettings["accessTokenSecretAppTwitt"]; }
		}

		public void Publicar(IEnumerable<Track> tracks)
		{
			foreach (var track in tracks)
			{
				//Si ya hicimos el twitt de este track, no volvemos a hacerlo
				if (track.Logs.Any(l => l.Propietario == TrackLogPropietario.Twitter && l.Successful)) continue;

				var twitt = BuildTwitt(track);
				if (!string.IsNullOrWhiteSpace(twitt))
				{
					string message;
					bool success = Publicar(twitt, out message);
					track.LogAdd(new TrackLog(TrackLogPropietario.Twitter, message, track.Usuario, success));
				}
			}
		}

		private string BuildTwitt(Track track)
		{
			ITwitterWriter writer;
			if (!_writers.TryGetValue(track.Accion, out writer))
				return string.Empty;

			string body = writer.Write(track);

			return body.Length > LIMITE_MENSAJE ? body.Substring(0, LIMITE_MENSAJE - 1) : body;
		}

		public bool Publicar(string status, out string message)
		{
			var tokens = new OAuthTokens
							{
								ConsumerKey = ConsumerKey,
								ConsumerSecret = ConsumerSecret,
								AccessToken = AccessToken,
								AccessTokenSecret = AccessTokenSecret
							};

			var response = _twitterAdapter.UpdateStatus(tokens, status);

			message = response.ErrorMessage;
			return response.Result == RequestResult.Success;
		}
	}
}