Created
December 7, 2009 16:13
-
-
Save KevM/250897 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Dimebrain.TweetSharp.Extensions; | |
using Dimebrain.TweetSharp.Fluent; | |
using Dimebrain.TweetSharp.Model; | |
namespace Carrier.Extension.Twitter | |
{ | |
public interface ITwitterStream | |
{ | |
ITwitterCredentials Credentials { get; set; } | |
IEnumerable<TwitterDirectMessage> GetDirectMessages(); | |
} | |
public class TwitterStream : ITwitterStream | |
{ | |
private readonly ITwitterIdentifierRepository _identifierRepository; | |
public ITwitterCredentials Credentials { get; set; } | |
public TwitterStream(ITwitterIdentifierRepository identifierRepository, ITwitterCredentials credentials) | |
{ | |
_identifierRepository = identifierRepository; | |
Credentials = credentials; | |
} | |
public IEnumerable<TwitterDirectMessage> GetDirectMessages() | |
{ | |
// Get the public timeline | |
var twitter = AuthenticatedRequest().DirectMessages().Received(); | |
AddSinceClause(twitter); | |
var response = twitter.Request(); | |
var directMessages = response.AsDirectMessages(); | |
RememberMostRecentDirectMessageIdentifier(directMessages); | |
CheckResponseForError(response); | |
return directMessages; | |
} | |
private void AddSinceClause(ITwitterDirectMessagesReceived twitter) | |
{ | |
var mostRecentTweetId = _identifierRepository.Get(); | |
if (mostRecentTweetId.HasValue) | |
twitter.Since(mostRecentTweetId.Value); | |
} | |
private void RememberMostRecentDirectMessageIdentifier(IEnumerable<TwitterDirectMessage> directMessages) | |
{ | |
if (directMessages != null && directMessages.Count() > 0) | |
_identifierRepository.Save(directMessages.First().Id); | |
} | |
private static void CheckResponseForError(string response) | |
{ | |
var error = response.AsError(); | |
if (error != null && !String.IsNullOrEmpty(error.ErrorMessage)) | |
throw new Exception(error.ErrorMessage); | |
} | |
private IFluentTwitter AuthenticatedRequest() | |
{ | |
return FluentTwitter.CreateRequest().AuthenticateAs(Credentials.UserName, Credentials.Password); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment