Example #1
0
        public void MarkNotificationsAsRead(params FacebookObjectId[] notificationIds)
        {
            Verify.IsNotNull(notificationIds, "notificationIds");

            var  sb      = new StringBuilder();
            bool isFirst = true;

            foreach (FacebookObjectId id in notificationIds)
            {
                if (FacebookObjectId.IsValid(id))
                {
                    if (!isFirst)
                    {
                        sb.Append(",");
                    }
                    sb.Append(id.ToString());
                }
            }

            if (sb.Length == 0)
            {
                return;
            }

            var readMap = new METHOD_MAP
            {
                { "method", "Notifications.markRead" },
                { "notification_ids", sb.ToString() },
            };

            Utility.FailableFunction(() => _SendRequest(readMap));
        }
Example #2
0
        private MessageNotification _DeserializeMessageNotification(JSON_OBJECT jsonThread)
        {
            var message = new MessageNotification(_service)
            {
                Created         = _SafeGetDateTime(jsonThread, "updated_time") ?? _UnixEpochTime,
                IsUnread        = _SafeGetBoolean(jsonThread, "unread") ?? true,
                DescriptionText = _SafeGetString(jsonThread, "snippet"),
                IsHidden        = false,
                NotificationId  = _SafeGetId(jsonThread, "thread_id"),
                SenderId        = _SafeGetId(jsonThread, "snippet_author"),
                Title           = _SafeGetString(jsonThread, "subject"),
                Updated         = _SafeGetDateTime(jsonThread, "updated_time") ?? DateTime.Now,
            };

            // TODO: This is actually a list of recipients.
            var jsonRecipientList = jsonThread.Get <JSON_ARRAY>("recipients");

            if (jsonRecipientList != null && jsonRecipientList.Count > 0)
            {
                message.RecipientId = new FacebookObjectId(jsonRecipientList[0].ToString());
            }

            if (FacebookObjectId.IsValid(message.NotificationId))
            {
                message.Link = new Uri(string.Format("http://www.facebook.com/inbox/#/inbox/?folder=[fb]messages&page=1&tid={0}", message.NotificationId));
            }
            else
            {
                Assert.Fail();
                message.NotificationId = SafeGetUniqueId();
                message.Link           = new Uri("http://www.facebook.com/inbox");
            }

            return(message);
        }
Example #3
0
        public ActivityPost PublishStream(FacebookObjectId targetId, string message)
        {
            var streamMap = new METHOD_MAP
            {
                { "method", "stream.publish" },
                { "message", message },
                { "target_id", targetId.ToString() },
            };

            Utility.FailableFunction(() => _SendRequest(streamMap));

            // Return a proxy that looks close to what we expect the updated status to look like.
            // We'll replace it with the real one the next time we sync.
            return(new ActivityPost(_Service)
            {
                ActorUserId = _UserId,
                TargetUserId = targetId,
                Attachment = null,
                CanComment = false,
                CanLike = false,
                CanRemoveComments = false,
                CommentCount = 0,
                Created = DateTime.Now,
                HasLiked = false,
                LikedCount = 0,
                LikeUri = null,
                Message = message,
                PostId = new FacebookObjectId("-1"),
                RawComments = new FBMergeableCollection <ActivityComment>(),
                Updated = DateTime.Now,
            });
        }
Example #4
0
        public static void DeserializeSessionInfo(string xml, out string sessionKey, out FacebookObjectId userId)
        {
            XDocument  xdoc = _SafeParseObject(xml);
            XNamespace ns   = xdoc.Root.GetDefaultNamespace();

            sessionKey = _SafeGetValue(xdoc.Root, "session_key");
            userId     = _SafeGetId(xdoc.Root, "uid");
        }
Example #5
0
 public void MarkMessageAsRead(FacebookObjectId messageId)
 {
     lock (_lock)
     {
         _VerifyHasUserInformation();
         _readMessages.Add(messageId);
     }
 }
Example #6
0
 public bool IsMessageRead(FacebookObjectId messageId)
 {
     lock (_lock)
     {
         _VerifyHasUserInformation();
         return(_readMessages.Contains(messageId));
     }
 }
Example #7
0
        public List <FacebookPhotoAlbum> GetUserAlbums(FacebookObjectId userId)
        {
            Verify.IsTrue(FacebookObjectId.IsValid(userId), "Invalid userId");

            string albumQueryResult = Utility.FailableFunction(() => _SendQuery(string.Format(_GetSingleUserAlbumsQueryString, userId)));

            return(_jsonSerializer.DeserializeGetAlbumsResponse(albumQueryResult));
        }
Example #8
0
 public void MarkUnfriendNotificationAsRead(FacebookObjectId userId)
 {
     lock (_lock)
     {
         _VerifyHasUserInformation();
         _unknownFriendRemovals.Remove(userId);
     }
 }
Example #9
0
        public bool IsFriendRequestKnown(FacebookObjectId uid)
        {
            lock (_lock)
            {
                _VerifyHasUserInformation();

                return(_ignoredFriendRequests.Contains(uid));
            }
        }
Example #10
0
 public FacebookWebApi(FacebookService service, string secret)
 {
     _ApplicationKey = service.ApplicationKey;
     _SessionKey     = service.SessionKey;
     _UserId         = service.UserId;
     _Secret         = secret;
     _Service        = service;
     _jsonSerializer = new JsonDataSerialization(service);
 }
Example #11
0
 public FacebookWebApi(string applicationId, string sessionKey, FacebookObjectId userId, string secret)
 {
     _ApplicationKey = applicationId;
     _SessionKey     = sessionKey;
     _UserId         = userId;
     _Secret         = secret;
     _Service        = null;
     _jsonSerializer = new JsonDataSerialization(null);
 }
Example #12
0
        public void RemoveLike(FacebookObjectId postId)
        {
            var likeMap = new METHOD_MAP
            {
                { "method", "stream.removeLike" },
                { "post_id", postId.ToString() },
            };

            Utility.FailableFunction(() => _SendRequest(likeMap));
        }
Example #13
0
 // Light constructor for Attachment provided photos
 internal FacebookPhoto(FacebookService service, FacebookObjectId albumId, FacebookObjectId photoId, Uri source)
 {
     SourceService = service;
     AlbumId       = albumId;
     PhotoId       = photoId;
     Created       = default(DateTime);
     Link          = null;
     Image         = new FacebookImage(service, source);
     RawComments   = new FBMergeableCollection <ActivityComment>();
     RawTags       = new FBMergeableCollection <FacebookPhotoTag>();
 }
Example #14
0
        public void DeserializeNotificationsGetResponse(string jsonString, out List <Notification> friendRequests, out int unreadMessageCount)
        {
            JSON_OBJECT jsonNotification = SafeParseObject(jsonString);
            var         notificationList = new List <Notification>(from string id in jsonNotification.Get <JSON_ARRAY>("friend_requests")
                                                                   let uid = new FacebookObjectId(id)
                                                                             where FacebookObjectId.IsValid(uid)
                                                                             select new FriendRequestNotification(_service, uid));

            unreadMessageCount = _SafeGetInt32(jsonNotification, "messages", "unread") ?? 0;
            friendRequests     = notificationList;
        }
Example #15
0
 public void MarkFriendRequestAsRead(FacebookObjectId userId)
 {
     lock (_lock)
     {
         _VerifyHasUserInformation();
         if (!_ignoredFriendRequests.Contains(userId))
         {
             _ignoredFriendRequests.Add(userId);
         }
     }
 }
Example #16
0
        public bool GetPhotoCanComment(FacebookObjectId photoId)
        {
            var commentMap = new METHOD_MAP
            {
                { "method", "photos.canComment" },
                { "pid", photoId.ToString() },
            };

            string response = Utility.FailableFunction(() => _SendRequest(commentMap));

            return(_jsonSerializer.DeserializePhotoCanCommentResponse(response));
        }
Example #17
0
        public List <FacebookPhotoTag> GetPhotoTags(FacebookObjectId photoId)
        {
            var tagMap = new METHOD_MAP
            {
                { "method", "photos.getTags" },
                { "pids", photoId.ToString() },
            };

            string response = Utility.FailableFunction(() => _SendRequest(tagMap));

            return(_jsonSerializer.DeserializePhotoTagsList(response));
        }
Example #18
0
        public FacebookObjectId AddPhotoComment(FacebookObjectId photoId, string comment)
        {
            var addMap = new METHOD_MAP
            {
                { "method", "photos.addComment" },
                { "pid", photoId.ToString() },
                { "body", comment },
            };

            string response = Utility.FailableFunction(() => _SendRequest(addMap));

            return(_jsonSerializer.DeserializePhotoAddCommentResponse(response));
        }
Example #19
0
 internal UnfriendNotification(FacebookService service, FacebookObjectId userId)
     : base(service)
 {
     Created                 = default(DateTime);
     Updated                 = default(DateTime);
     IsHidden                = false;
     IsUnread                = true;
     NotificationId          = new FacebookObjectId("Unfriended_" + userId.ToString());
     RecipientId             = service.UserId;
     SenderId                = userId;
     Sender.PropertyChanged += _OnSenderPropertyChanged;
     Title     = string.Format(_friendRemovalFormat, Sender.ProfileUri.ToString(), Sender.Name);
     TitleText = string.Format(_friendRemovalTextFormat, Sender.Name);
     Link      = Sender.ProfileUri;
 }
Example #20
0
        public void RemoveComment(FacebookObjectId commentId)
        {
            if (!FacebookObjectId.IsValid(commentId))
            {
                // If we're removing a comment that we haven't yet posted we can't remove it.
                return;
            }
            var commentMap = new METHOD_MAP
            {
                { "method", "stream.removeComment" },
                { "comment_id", commentId.ToString() },
            };

            Utility.FailableFunction(() => _SendRequest(commentMap));
        }
Example #21
0
        public void SetInterestLevel(FacebookObjectId userId, double value)
        {
            lock (_lock)
            {
                _VerifyHasUserInformation();

                Assert.IsNotDefault(userId);

                if (userId == _user.UserId)
                {
                    _user.InterestLevel = value;
                    return;
                }

                _friendLookup[userId].InterestLevel = value;
            }
        }
Example #22
0
        public void SetSessionInfo(string sessionKey, string sessionSecret, FacebookObjectId userId)
        {
            lock (_lock)
            {
                SessionKey    = sessionKey;
                SessionSecret = sessionSecret;
                _user.UserId  = userId;

                if (HasSessionInfo)
                {
                    _GetUserInfo();
                }
                else
                {
                    _ClearUserInfo();
                }
            }
        }
Example #23
0
        public List <FacebookPhotoTag> AddPhotoTag(FacebookObjectId photoId, FacebookObjectId userId, float x, float y)
        {
            Verify.IsTrue(FacebookObjectId.IsValid(userId), "Invalid userId");
            Verify.IsTrue(FacebookObjectId.IsValid(photoId), "Invalid photoId");

            x *= 100;
            y *= 100;
            var tagMap = new METHOD_MAP
            {
                { "method", "photos.addTag" },
                { "pid", photoId.ToString() },
                { "tag_uid", userId.ToString() },
                { "x", string.Format("{0:0.##}", x) },
                { "y", string.Format("{0:0.##}", y) },
            };

            string response = Utility.FailableFunction(() => _SendRequest(tagMap));

            return(GetPhotoTags(photoId));
        }
Example #24
0
        public double?GetInterestLevel(FacebookObjectId userId)
        {
            lock (_lock)
            {
                _VerifyHasUserInformation();

                Assert.IsNotDefault(userId);

                if (userId == UserId)
                {
                    return(_user.InterestLevel);
                }

                _LiteContact c;
                if (_friendLookup.TryGetValue(userId, out c))
                {
                    return(c.InterestLevel);
                }
                return(null);
            }
        }
Example #25
0
        public FacebookPhotoAlbum GetAlbum(FacebookObjectId albumId)
        {
            Verify.IsTrue(FacebookObjectId.IsValid(albumId), "Invalid albumId");

            var albumMap = new METHOD_MAP
            {
                { "method", "photos.getAlbums" },
                { "aids", albumId.ToString() },
            };

            string response = Utility.FailableFunction(() => _SendRequest(albumMap));
            List <FacebookPhotoAlbum> albumsResponse = _jsonSerializer.DeserializeGetAlbumsResponse(response);

            Assert.IsFalse(albumsResponse.Count > 1);

            if (albumsResponse.Count == 0)
            {
                return(null);
            }
            return(albumsResponse[0]);
        }
Example #26
0
        public List <ActivityPost> GetStream(FacebookObjectId filterKey, int limit, DateTime getItemsSince)
        {
            Assert.IsTrue(limit > 0);

            // Facebook changed the semantics of the default feed, so we need to explicitly
            // request the newsfeed filter to keep things working as expected.
            // I think everyone should have a filter with this key, but this is unfortunately fragile.
            if (!FacebookObjectId.IsValid(filterKey))
            {
                filterKey = new FacebookObjectId("nf");
            }

            long startTime = JsonDataSerialization.GetUnixTimestampFromDateTime(getItemsSince);

            Assert.IsTrue(startTime >= 0);

            // Don't use metadata field.  Facebook regressed support for it.
            // Getting profile data needs to be simulated at a higher level.
            var streamMap = new METHOD_MAP
            {
                { "method", "stream.get" },
                { "viewer_id", _UserId.ToString() },
                { "start_time", startTime.ToString("G") },
                { "limit", limit.ToString("G") },
                { "filter_key", filterKey.ToString() },
            };

            string result = Utility.FailableFunction(() => _SendRequest(streamMap));

            return(_jsonSerializer.DeserializeStreamData(result));

            //var userIds = new HashSet<FacebookObjectId>();
            //foreach (var post in posts)
            //{
            //    userIds.Add(post.ActorUserId);
            //    userIds.Add(post.TargetUserId);
            //    userIds.AddRange(from comment in post.Comments select comment.FromUserId);
            //    userIds.AddRange(from liker in post.PeopleWhoLikeThis select liker.UserId);
            //}
        }
Example #27
0
        public FacebookContact TryGetUser(FacebookObjectId userId, bool getFullData)
        {
            _Verify();

            var userMap = new METHOD_MAP
            {
                { "method", "users.GetInfo" },
                { "uids", userId.ToString() },
                //{ "fields", _UserColumns },
            };

            if (getFullData)
            {
                userMap["fields"] = _UserColumns;
            }
            else
            {
                userMap["fields"] = _UserColumnsLite;
            }

            // Facebook bogusly errors this call fairly frequently.
            List <FacebookContact> contactList = null;
            int reaskCount = 0;

            do
            {
                string result = Utility.FailableFunction(5, () => _SendRequest(userMap));
                contactList = _jsonSerializer.DeserializeUsersList(result);
            } while (contactList.Count == 0 && ++reaskCount < 3);

            if (contactList.Count == 0)
            {
                // I'd like to do something better here.  This fails too frequently.
                // Maybe once we move to the graph API there will be a more privacy friendly way to get this data.
                return(null);
                //throw new FacebookException("Unable to obtain information about the user.", null);
            }

            return(contactList[0]);
        }
Example #28
0
        public void Save()
        {
            lock (_lock)
            {
                XElement sessionXml = new XElement("sessionSettings",
                                                   new XAttribute("v", 1),
                                                   new XElement("sessionInfo",
                                                                new XElement("sessionKey", SessionKey),
                                                                new XElement("sessionSecret", SessionSecret),
                                                                new XElement("userId", UserId)));
                sessionXml.Save(Path.Combine(_settingsRootPath, _SessionSettingsFileName));

                if (FacebookObjectId.IsValid(UserId))
                {
                    XElement userXml = new XElement("userSettings",
                                                    new XAttribute("v", 2),
                                                    new XElement("friends",
                                                                 from c in _friendLookup.Values
                                                                 select(new XElement("contact"))
                                                                 .NewXAttribute("interestLevel", c.InterestLevel)
                                                                 .NewXAttribute("name", c.Name)
                                                                 .NewXAttribute("uid", c.UserId)),
                                                    new XElement("knownFriendRequests",
                                                                 from uid in _ignoredFriendRequests
                                                                 select new XElement("contact",
                                                                                     new XAttribute("uid", uid))),
                                                    new XElement("unreadUnfriendings",
                                                                 from uid in _unknownFriendRemovals
                                                                 select new XElement("contact",
                                                                                     new XAttribute("uid", uid))),
                                                    new XElement("readMessages",
                                                                 from messageId in _readMessages
                                                                 select new XElement("message",
                                                                                     new XAttribute("id", messageId))));
                    userXml.Save(Path.Combine(Path.Combine(_settingsRootPath, UserId.ToString()), _UserSettingsFileName));
                }
            }
        }
Example #29
0
        public FacebookPhoto AddPhotoToAlbum(FacebookObjectId albumId, string caption, string imageFile)
        {
            _Verify();

            var updateMap = new METHOD_MAP
            {
                { "method", "photos.upload" },
            };

            if (FacebookObjectId.IsValid(albumId))
            {
                updateMap.Add("aid", albumId.ToString());
            }

            if (!string.IsNullOrEmpty(caption))
            {
                updateMap.Add("caption", caption);
            }

            string response = Utility.FailableFunction(() => _SendFileRequest(updateMap, imageFile));

            return(_jsonSerializer.DeserializePhotoUploadResponse(response));
        }
Example #30
0
        private ActivityPost _DeserializePost(JSON_OBJECT jsonPost)
        {
            var post = new ActivityPost(_service);

            JSON_OBJECT attachmentObject;

            if (jsonPost.TryGetTypedValue("attachment", out attachmentObject))
            {
                string postType = null;

                var jsonMediaArray = (JSON_ARRAY)_SafeGetValue(jsonPost, "attachment", "media");
                if (jsonMediaArray != null && jsonMediaArray.Count > 0)
                {
                    postType = _SafeGetString((JSON_OBJECT)jsonMediaArray[0], "type");
                }

                switch (postType)
                {
                case "photo":
                    post.Attachment = _DeserializePhotoPostAttachmentData(post, attachmentObject);
                    break;

                case "link":
                    post.Attachment = _DeserializeLinkPostAttachmentData(post, attachmentObject);
                    break;

                case "video":
                    post.Attachment = _DeserializeVideoPostAttachmentData(post, attachmentObject);
                    break;

                // We're not currently supporting music or flash.  Just treat it like a normal post...
                case "music":
                case "swf":

                case "":
                case null:
                    if (attachmentObject.Count != 0)
                    {
                        // We have attachment information but no rich stream-media associated with it.
                        ActivityPostAttachment attachment = _DeserializeGenericPostAttachmentData(post, attachmentObject);
                        if (!attachment.IsEmpty)
                        {
                            attachment.Type = ActivityPostAttachmentType.Simple;
                            post.Attachment = attachment;
                        }
                    }
                    break;

                default:
                    Assert.Fail("Unknown type:" + postType);
                    break;
                }
            }

            post.PostId = _SafeGetId(jsonPost, "post_id");
            if (!FacebookObjectId.IsValid(post.PostId))
            {
                // Massive Facebook failure.
                // This happens too frequently for the assert to be useful.
                // Assert.Fail();
                post.PostId = SafeGetUniqueId();
            }
            post.ActorUserId  = _SafeGetId(jsonPost, "actor_id");
            post.Created      = _SafeGetDateTime(jsonPost, "created_time") ?? _UnixEpochTime;
            post.Message      = _SafeGetString(jsonPost, "message");
            post.TargetUserId = _SafeGetId(jsonPost, "target_id");
            post.Updated      = _SafeGetDateTime(jsonPost, "updated_time") ?? _UnixEpochTime;

            JSON_OBJECT likesElement;

            if (jsonPost.TryGetTypedValue("likes", out likesElement))
            {
                post.CanLike    = _SafeGetBoolean(likesElement, "can_like") ?? false;
                post.HasLiked   = _SafeGetBoolean(likesElement, "user_likes") ?? false;
                post.LikedCount = _SafeGetInt32(likesElement, "count") ?? 0;
                post.LikeUri    = _SafeGetUri(likesElement, "likes", "href");
                //XElement friendsElement = likesElement.Element("friends");
                //XElement sampleElement = likesElement.Element("sample");
                //post.SetPeopleWhoLikeThisIds(
                //    Enumerable.Union(
                //        sampleElement == null
                //            ? new FacebookObjectId[0]
                //            : from uidElement in sampleElement.Elements("uid") select new FacebookObjectId(uidElement.Value),
                //        friendsElement == null
                //            ? new FacebookObjectId[0]
                //            : from uidElement in friendsElement.Elements("uid") select new FacebookObjectId(uidElement.Value)));
            }

            JSON_OBJECT jsonComments;

            jsonPost.TryGetTypedValue("comments", out jsonComments);

            post.CanComment        = _SafeGetBoolean(jsonComments, "can_post") ?? false;
            post.CanRemoveComments = _SafeGetBoolean(jsonComments, "can_remove") ?? false;
            post.CommentCount      = _SafeGetInt32(jsonComments, "count") ?? 0;

            if (jsonComments != null && post.CommentCount != 0)
            {
                JSON_ARRAY jsonCommentList;
                if (jsonComments.TryGetTypedValue("comment_list", out jsonCommentList))
                {
                    var commentNodes = from JSON_OBJECT jsonComment in jsonCommentList
                                       let comment = _DeserializeComment(jsonComment)
                                                     where (comment.Post = post) != null
                                                     select comment;

                    post.RawComments = new FBMergeableCollection <ActivityComment>(commentNodes);
                }
            }

            if (post.RawComments == null)
            {
                post.RawComments = new FBMergeableCollection <ActivityComment>();
            }

            // post.Comments = null;

            return(post);
        }