cloutier--bird.makeup/src/BirdsiteLive.Pipeline/Processors/SendTweetsToFollowersProcessor.cs

84 lines
2.9 KiB
C#
Raw Normal View History

2020-07-22 19:27:25 -04:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
2020-07-18 23:35:19 -04:00
using System.Threading.Tasks;
using BirdsiteLive.DAL.Contracts;
2020-07-22 19:27:25 -04:00
using BirdsiteLive.DAL.Models;
using BirdsiteLive.Domain;
2020-07-18 23:35:19 -04:00
using BirdsiteLive.Pipeline.Contracts;
using BirdsiteLive.Pipeline.Models;
using BirdsiteLive.Twitter;
2020-07-22 19:27:25 -04:00
using Tweetinvi.Models;
2020-07-18 23:35:19 -04:00
namespace BirdsiteLive.Pipeline.Processors
{
public class SendTweetsToFollowersProcessor : ISendTweetsToFollowersProcessor
{
private readonly IActivityPubService _activityPubService;
2020-07-22 19:27:25 -04:00
private readonly IStatusService _statusService;
private readonly IFollowersDal _followersDal;
#region Ctor
2020-07-22 19:27:25 -04:00
public SendTweetsToFollowersProcessor(IActivityPubService activityPubService, IFollowersDal followersDal, IStatusService statusService)
{
_activityPubService = activityPubService;
_followersDal = followersDal;
2020-07-22 19:27:25 -04:00
_statusService = statusService;
}
#endregion
2020-07-22 19:27:25 -04:00
public async Task<UserWithTweetsToSync> ProcessAsync(UserWithTweetsToSync userWithTweetsToSync, CancellationToken ct)
2020-07-18 23:35:19 -04:00
{
var user = userWithTweetsToSync.User;
var userId = user.Id;
foreach (var follower in userWithTweetsToSync.Followers)
{
2020-07-22 19:27:25 -04:00
try
{
await ProcessFollowerAsync(userWithTweetsToSync.Tweets, follower, userId, user);
}
catch (Exception e)
{
Console.WriteLine(e);
//TODO handle error
}
}
return userWithTweetsToSync;
}
private async Task ProcessFollowerAsync(IEnumerable<ITweet> tweets, Follower follower, int userId,
SyncTwitterUser user)
{
var fromStatusId = follower.FollowingsSyncStatus[userId];
var tweetsToSend = tweets.Where(x => x.Id > fromStatusId).OrderBy(x => x.Id).ToList();
2020-07-22 19:27:25 -04:00
var syncStatus = fromStatusId;
try
{
foreach (var tweet in tweetsToSend)
{
2020-07-22 19:27:25 -04:00
var note = _statusService.GetStatus(user.Acct, tweet);
var result = await _activityPubService.PostNewNoteActivity(note, user.Acct, tweet.Id.ToString(), follower.Host,
follower.InboxUrl);
if (result == HttpStatusCode.Accepted)
syncStatus = tweet.Id;
else
2020-07-22 19:27:25 -04:00
throw new Exception("Posting new note activity failed");
}
}
finally
{
if (syncStatus != fromStatusId)
{
follower.FollowingsSyncStatus[userId] = syncStatus;
await _followersDal.UpdateFollowerAsync(follower);
}
}
2020-07-18 23:35:19 -04:00
}
}
}