Beispiel #1
0
        public OAuthParameters GetOAuthParameters(long UserId, oAuthService Service)
        {
            using (var db = new ToketeeData().Context)
            {

            }

            return null;
        }
Beispiel #2
0
        public int SyncToDatabase(SyncToDatabaseOp Op, CurrentUser currentUser, long UserId)
        {
            logger.Debug("SyncFollowersToDatabase(Op: {0}, CurrentUser: {1}, UserId: {2})", (object) Op, (object) currentUser.Id, (object) UserId);

            FriendsClient friends = new FriendsClient(currentUser.Id);
            WebClientResult<FriendsList> FriendsList;

            if (Op == SyncToDatabaseOp.GetFollowers)
                FriendsList = friends.FollowerIds(UserId.ToString(), null, null);
            else
                FriendsList = friends.FriendIds(UserId.ToString(), null, null);

            using (var db = new ToketeeData().Context)
            {

                // TODO Handle deletes

                // Get the current known followers list from the DB
                // TODO find a way to create an IQueryable when specific columns are returned
                IQueryable<TwitterFriends> qFriendsInDb;
                if (Op == SyncToDatabaseOp.GetFollowers)
                {
                    qFriendsInDb = from f in db.TwitterFriends
                                   where f.FriendId == UserId
                                   select f;
                }
                else
                {
                    qFriendsInDb = from f in db.TwitterFriends
                                   where f.OwnerId == UserId
                                   select f;
                }

                logger.Trace("Known friends in DB for {0} / Count: {1}", UserId.ToString(), qFriendsInDb.Count().ToString());

                var qtest = qFriendsInDb.Where(x => x.FriendId == 13348).Count();
                // Determine which followers are not in the friend tracking table

                //ownerid

                IEnumerable<long> NewFollowers;
                IEnumerable<TwitterFriends> DeletedFollowers;
                if (Op == SyncToDatabaseOp.GetFollowers)
                {
                    // Followers are identified by the OwnerId having a FriendId of the method's UserId
                    NewFollowers = from f in FriendsList.Object
                                   where !(from a in qFriendsInDb
                                           select a.OwnerId).Contains(f)
                                   select f;

                    var tempFriendsList = FriendsList.Object.ToList();
                    DeletedFollowers = from f in qFriendsInDb
                                       where !tempFriendsList.Contains(f.OwnerId)
                                       select f;

                    //DeletedFollowers = from f in qFriendsInDb
                    //                   where !(from a in FriendsList.Object
                    //                           select a).Contains(f.OwnerId)
                    //                   select f;
                }
                else
                {
                    // Friends are identified by the FriendId having the OwnerId of the method's UserId
                    NewFollowers = from f in FriendsList.Object
                                   where !(from a in qFriendsInDb
                                           select a.FriendId).Contains(f)
                                   select f;

                    var tempFriendsList = FriendsList.Object.ToList();
                    DeletedFollowers = from f in qFriendsInDb
                                       where !tempFriendsList.Contains(f.FriendId)
                                       select f;

                    //DeletedFollowers = from f in qFriendsInDb
                    //                   where !(from a in FriendsList.Object
                    //                           select a).Contains(f.FriendId)
                    //                   select f;
                }

                logger.Trace("New followers: {0} / Unfollows: {1}", NewFollowers.Count(), DeletedFollowers.Count());

                var NewFollowersList = new List<long>();
                foreach (long Id in NewFollowers)
                {
                    var tFriends = new TwitterFriends()
                    {
                        OwnerId = (Op == SyncToDatabaseOp.GetFollowers) ? Id : UserId,
                        FriendId = (Op == SyncToDatabaseOp.GetFollowers) ? UserId : Id
                    };
                    db.TwitterFriends.Add(tFriends);
                    NewFollowersList.Add(Id);
                }

                var userOps = new UserOps(currentUser.Id);
                Users users = userOps.Lookup(NewFollowersList);

                string s = string.Join(",", FriendsList.Object.ToArray());
                var qExistingUsers = db.TwitterUser.SqlQuery("select * from TwitterUser where Id in (" + s + ");");

                // for each User in Users, find the corresponding TwitterUser to update

                // Filter out the users that do exist so we can insert the new ones

                var qDontExist = from u in users
                                 where !(from a in qExistingUsers
                                         select a.Id.ToString()).Contains(u.Id)
                                 select u;

                logger.Trace("Users to be inserted: {0}", qDontExist.Count().ToString());

                foreach (TwitterAPI.User u in qDontExist)
                {
                    if (qExistingUsers.Where(x => x.Id.ToString() == u.Id).Count() > 0)
                        logger.Error("User already exists, but shouldn't! {0}", u.Id);

                }

                TwitterUser tUser;

                foreach (TwitterAPI.User u in qDontExist.Distinct())
                {
                    tUser = new TwitterUser();
                    UserOps.UserObjToTwitterUser(u, tUser);
                    db.TwitterUser.Add(tUser);
                    logger.Trace("Inserted TwitterUser: {0}", tUser.Id);
                }

                foreach (TwitterUser tu in qExistingUsers)
                {
                    try
                    {
                        var q2 = (from u in users
                                  where u.Id == tu.Id.ToString()
                                  select u).SingleOrDefault();
                        if (q2 != null) UserOps.UserObjToTwitterUser(q2, tu);
                        logger.Trace("Updated TwitterUser: {0}", tu.Id);
                    }
                    catch (InvalidOperationException e)
                    {
                        string sError = String.Format("UserObjToTwitterUser unable to match existing user TwitterUser {0} to friends list user", tu.Id);
                        logger.ErrorException(sError, e);
                    }
                }

                // Process unfollows

                int iFriendshipsDeleted = 0;
                foreach (TwitterFriends tf in DeletedFollowers)
                {
                    logger.Trace("Deleting friendship: Owner {0} Friend {1}", tf.OwnerId, tf.FriendId);
                    db.TwitterFriends.Remove(tf);
                    iFriendshipsDeleted++;
                }
                if (iFriendshipsDeleted > 0) logger.Debug("Friendships deleted: {0}", iFriendshipsDeleted);
                return db.SaveChanges();
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        curUser = Membership.GetUser();

        if (Request.PathInfo.StartsWith("/twitter/"))
        {
            var oauth = new OAuthConsumer();
            var requestToken = (RequestToken)Session["TwitterToken"];
            string verifier = Request.QueryString["oauth_verifier"];
            string tokenSecret = Request.QueryString["oauth_token"];
            AccessToken accessToken = oauth.GetOAuthAccessToken(appSettings["Twitter_AccessURL"],
                appSettings["Twitter_Realm"], appSettings["Twitter_ConsumerKey"],
                appSettings["Twitter_ConsumerSecret"], tokenSecret, verifier, requestToken.Token);
            string curUserId = curUser.ProviderUserKey.ToString();

            var oAuthParams = new OAuthParameters(appSettings["Twitter_ConsumerKey"],
                appSettings["Twitter_ConsumerSecret"], appSettings["Twitter_Realm"],
                accessToken.Token, accessToken.TokenSecret);

            Func<OAuthParameters> OAuthDirect = () => oAuthParams;
            var account = new AccountClient(OAuthDirect);

            var tUser = Json.Deserialize<Bridgeport.TwitterAPI.User>(account.VerifyCredentials().Data);

            using (var db = new Data.ToketeeData().Context)
            {
                var q = from u in db.User
                        where u.UserId == curUserId
                        select u;
                if (q.Any()) // User does not exist
                {

                    var user = new Data.Entities.User()
                    {
                        UserId = curUserId,
                    };
                    var twitterUser = new TwitterData.TwitterUser()
                        {
                            rUser = user,
                            Token = accessToken.Token,
                            Secret = accessToken.TokenSecret,
                            AuthAttemptCount = 0,
                            AuthStatus = 1,
                            AppUser = true,
                            AuthTime = DateTime.Now.ToUniversalTime()
                        };
                    UserOps.UserObjToTwitterUser(tUser, twitterUser);

                    db.User.Add(user);
                    db.TwitterUser.Add(twitterUser);
                }
                else // User exists
                {
                    var qry = q.Single();

                    TwitterData.TwitterUser tu;
                    if (qry.TwitterUsers.Count() != 0) // Twitter user exists
                    {
                        var q2 = from u in qry.TwitterUsers
                                 where u.Id == long.Parse(tUser.Id)
                                 select u;

                        tu = q2.Single();
                    }
                    else
                    {
                        tu = new TwitterData.TwitterUser() { rUser = qry };
                        db.TwitterUser.Add(tu);
                    }

                    tu.Token = accessToken.Token;
                    tu.Secret = accessToken.TokenSecret;
                    tu.AuthAttemptCount = 0;
                    tu.AuthStatus = 1;
                    tu.AppUser = true;
                    tu.AuthTime = DateTime.Now.ToUniversalTime();

                    UserOps.UserObjToTwitterUser(tUser, tu);
                }
                db.SaveChanges();
            }

        }
    }
Beispiel #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //ITwitterStatuses status = TwitterProxy.GetProxy<ITwitterStatuses>("username", "password");

        //ObjectModel.Status s = new ObjectModel.Status();
        //s = status.Show("6586391125");

        //WebClient.Status status = new TwitterProxy.GetProxy<Status>("username", "password");
        //var s = status.Show("6586391125");

        //WebHttpBinding binding = new WebHttpBinding();
        //binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
        //binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

        //WebChannelFactory<ITwitterStatuses> channel = new WebChannelFactory<Bridgeport.TwitterAPI.Entities.ITwitterStatuses>(binding, new Uri("http://api.twitter.com"));
        //channel.Credentials.UserName.UserName = "******";
        //channel.Credentials.UserName.Password = "******";

        //ITwitterStatuses status = channel.CreateChannel();
        //using (new OperationContextScope((IContextChannel)status))
        //{
        //    OutgoingWebRequestContext ctx = WebOperationContext.Current.OutgoingRequest;
        //    Bridgeport.TwitterAPI.Entities.Status s = status.Showzomblog.cog  ("6586391125");
        //    IncomingWebResponseContext rctx = WebOperationContext.Current.IncomingResponse;

        //    if (rctx.StatusCode == HttpStatusCode.Created)
        //    {

        //    }
        //}

        //Bridgeport.TwitterAPI.Status status = new Bridgeport.TwitterAPI.Status("username","password");
        //var s = status.Show("6586391125");
        //var s = status.Update("12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890");

        //Status st = (Status)new GenericServiceProxyAgent<Status, ITwitterStatuses>();

        //TwitterExecutive<ObjectModel.Status, WebClient.Status, ITwitterStatuses> exec =
        //    new TwitterExecutive<ObjectModel.Status, WebClient.Status, ITwitterStatuses>();

        //string Token = "1929121-wjRzrZI9A4rLFBNh1TpeTDlFSwn4rGcgel1LNAYNjU";
        //string Secret = "qbRETrhRAvlQFBBTTqUUeFaNVife8WttPAZ0HbC1sXw";
        //NameValueCollection appSettings = ConfigurationManager.AppSettings;
        //OAuthParameters oAuth = new OAuthParameters()
        //{
        //    ConsumerKey = appSettings["Twitter_ConsumerKey"],
        //    ConsumerSecret = appSettings["Twitter_ConsumerSecret"],
        //    Realm = appSettings["Twitter_Realm"],
        //    UserToken = Token,
        //    UserSecret = Secret
        //};

        //Dictionary<string, object> d = new Dictionary<string,object>();
        //d.Add("id", "6586391125");
        //d.Add("count", 234);

        //LiteClientBase<Status, ITwitterStatuses> client =
        //    new LiteClientBase<Status, ITwitterStatuses>();

        //TwitterWebClientResult<Status> result = client.Execute("Show", d, oAuth);

        //Status status = new Status(oAuth);
        //TwitterWebClientResult<Twitter.Status> result = status.Show("6586391125");

        //BasicHttpBinding httpBinding = new BasicHttpBinding();
        //EndpointAddress endpoint = new EndpointAddress("http://api.twitter.com");
        //ChannelFactory<ITwitterStatuses> cf = new ChannelFactory<ITwitterStatuses>(httpBinding, endpoint);

        //ITwitterStatuses wcfClient = cf.CreateChannel();

        //Twitter.Status status = wcfClient.Show("6586391125");
        //((IClientChannel)wcfClient).Close();

        //Test<ITwitterStatuses> test = new Test<ITwitterStatuses>();

        //Status status = new Status(oAuth);
        //WebClientResult s = status.Channel.Show("12345");

        //MySqlConnection conn;
        //conn = new MySqlConnection("server=127.0.0.1;database=toketee;uid=toketee;pwd=toketee");
        //conn.Open();

        using (var db = new  ToketeeData().Context)
        {
            var q = from u in db.TwitterList
                    select u;
        }
    }
Beispiel #5
0
        public static IEnumerable<TwitterStatus> SelectMany(string[] ids)
        {
            // validate the id's by converting to a long array, also limit request to 50 id's
            var idList = new long[ids.Length];
            var maxLength = (ids.Length < 50) ? ids.Length : 50;
            for (int i = 0; i < maxLength; i++)
            {
                idList[i] = long.Parse(ids[i]);
            }

            using (var db = new ToketeeData().Context)
            {
                var tweets = (from a in db.TwitterStatuses
                              where idList.Contains(a.Id)
                              select a).Distinct().ToArray().ToList();

                var notFound = (from a in idList
                                where !tweets.Select(status => status.Id).Contains(a)
                                select a);

                if (notFound.Any())
                {
                    using (var queue = new Queue())
                    {
                        var statusClient = new StatusClient(TwitterDelegates.GetOAuth, 117547746);
                        foreach (var value in notFound)
                        {
                            var statusResult = statusClient.Show(value.ToString());

                            if (statusResult != null)
                            {
                                var result = TranslateStatus.ToInternal(statusResult.Data);
                                DbTwitterStatus.Insert(result.Id, result.CreatedAt.FromEpoch(), Json.Serialize(result));

                                tweets.Add(new TwitterStatus
                                           	{
                                           		Id = Parse.Long(result.Id),
                                           		Data = Encoding.UTF8.GetBytes(Json.Serialize(result)),
                                           		Sent = result.CreatedAt.FromEpoch()
                                           	});
                                //var result = queue.GetBrowser("id = " + value.ToString());
                                //foreach (var item in result)
                                //{
                                //    var msg = (Apache.NMS.ActiveMQ.Commands.ActiveMQTextMessage) item;
                                //    msg.Acknowledge();

                                //    Queue.SingleSend(msg.Text, MsgPriority.Highest);
                                //}
                            }
                        }
                    }
                }

                return tweets;
            }
        }