Beispiel #1
0
        public async override Task <FacebookProcessResult> Process(SocialAccount socialAccount, FbHookChange change)
        {
            var    result = new FacebookProcessResult(NotificationManager);
            string token  = socialAccount.Token;

            if (IsDuplicatedMessage(change.Value.CommentId))
            {
                return(result);
            }

            FbComment  comment = FbClient.GetComment(socialAccount.Token, change.Value.CommentId);
            SocialUser sender  = await GetOrCreateFacebookUser(socialAccount.Token, comment.from.id);

            var conversation = GetConversation(change.Value.PostId);

            if (conversation == null)
            {
                return(result);
            }

            Message message = FacebookConverter.ConvertToMessage(comment);

            message.SenderId = sender.Id;
            var parent = GetParent(change.Value.PostId, comment);

            if (parent != null)
            {
                message.ParentId   = parent.Id;
                message.ReceiverId = parent.SenderId;
                bool ifParentIsComment = parent.ParentId != null;
                if (ifParentIsComment)
                {
                    message.Source = MessageSource.FacebookPostReplyComment;
                }
            }

            message.ConversationId           = conversation.Id;
            conversation.IfRead              = false;
            conversation.Status              = sender.Id != socialAccount.Id ? ConversationStatus.PendingInternal : ConversationStatus.PendingExternal;
            conversation.LastMessageSenderId = message.SenderId;
            conversation.LastMessageSentTime = message.SendTime;

            if (conversation.TryToMakeWallPostVisible(socialAccount))
            {
                result.WithNewConversation(conversation);
            }

            conversation.Messages.Add(message);

            await UpdateConversation(conversation);

            await CurrentUnitOfWork.SaveChangesAsync();

            if (!conversation.IsHidden)
            {
                result.WithNewMessage(message);
            }

            return(result);
        }
Beispiel #2
0
        public static void RegisterAuth()
        {
            var fbClient = new FbClient();

            // To let users of this site log in using their accounts from other sites such as Microsoft, Facebook, and Twitter,
            // you must update this site. For more information visit http://go.microsoft.com/fwlink/?LinkID=252166

            //OAuthWebSecurity.RegisterMicrosoftClient(
            //    clientId: "",
            //    clientSecret: "");

            //OAuthWebSecurity.RegisterTwitterClient(
            //    consumerKey: "",
            //    consumerSecret: "");

            // prod
            //OAuthWebSecurity.RegisterFacebookClient(
            //    appId: "262309163906980",
            //    appSecret: "3439950f4bf262d8041e28cdb1b7416c");

            // dev
            //OAuthWebSecurity.RegisterFacebookClient(
            //    appId: "170633953128198",
            //    appSecret: "2a94e68adc55ff563a8c4ff178a85662");

            OAuthWebSecurity.RegisterFacebookClient(
                appId: fbClient.AppId,
                appSecret: fbClient.AppSecret);

            OAuthWebSecurity.RegisterGoogleClient();
        }
Beispiel #3
0
        /// <summary>
        /// Creates uri for login dialog
        /// </summary>
        /// <param name="permissions">Array of scopes, required by application</param>
        /// <param name="redirectUrl">Callback uri which is called after dialog completes</param>
        private static Task <string> GetLoginUri(string[] permissions, string redirectUrl)
        {
            var tcs = new TaskCompletionSource <string>();

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                var loginParams = new Dictionary <string, object>();

                loginParams["client_id"]     = Session.AppId;
                loginParams["redirect_uri"]  = redirectUrl;
                loginParams["response_type"] = LOGIN_RESPONSE_TYPE;
                loginParams["display"]       = DIALOG_DISPLAY_TYPE;
                loginParams["mobile"]        = true;

                // add the 'scope' only if we have extendedPermissions.
                if (permissions.Length > 0)
                {
                    // A comma-delimited list of permissions
                    loginParams["scope"] = string.Join(",", permissions);
                }

                tcs.SetResult(FbClient.GetLoginUrl(loginParams).ToString());
            });

            return(tcs.Task);
        }
Beispiel #4
0
        /// <summary>
        /// Fetches data returned by login dialog from callback uri. Creates and saves new AccessTokenData object to current session.
        /// Calls getLoginStatus internally to fill AccessTokenData with such values as FacebookId and CurrentPermissions
        /// </summary>
        /// <param name="uri">Callback uri of login dialog</param>
        private static Task <AccessTokenData> FetchLoginUriAsync(Uri uri)
        {
            var tcs = new TaskCompletionSource <AccessTokenData>();

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                var oauthResult = FbClient.ParseOAuthCallbackUrl(uri);
                if (oauthResult.IsSuccess)
                {
                    var tempToken = new AccessTokenData
                    {
                        AccessToken = oauthResult.AccessToken,
                        Expires     = oauthResult.Expires
                    };

                    tcs.SetResult(tempToken);
                }
                else
                {
                    tcs.SetException(new Exception(oauthResult.Error));
                }
            });

            return(tcs.Task);
        }
Beispiel #5
0
        public override async Task <FacebookProcessResult> Process(SocialAccount socialAccount, FbHookChange change)
        {
            var result = new FacebookProcessResult(NotificationManager);

            if (IsWallPost(change) && !socialAccount.IfConvertWallPostToConversation)
            {
                return(result);
            }
            if (!IsWallPost(change) && !socialAccount.IfConvertVisitorPostToConversation)
            {
                return(result);
            }

            string token = socialAccount.Token;

            if (IsDuplicatedMessage(MessageSource.FacebookPost, change.Value.PostId))
            {
                return(result);
            }

            FbPost post = await FbClient.GetPost(socialAccount.Token, change.Value.PostId);

            SocialUser sender = await GetOrCreateFacebookUser(socialAccount.Token, post.from.id);

            Message message = FacebookConverter.ConvertToMessage(post);

            message.SenderId = sender.Id;
            if (message.SenderId != socialAccount.Id)
            {
                message.ReceiverId = socialAccount.Id;
            }
            var conversation = new Conversation
            {
                OriginalId          = change.Value.PostId,
                Source              = ConversationSource.FacebookVisitorPost,
                Priority            = ConversationPriority.Normal,
                Status              = ConversationStatus.New,
                Subject             = GetSubject(message.Content),
                LastMessageSenderId = message.SenderId,
                LastMessageSentTime = message.SendTime
            };

            if (change.Value.Verb == "add" && message.SenderId == socialAccount.Id)
            {
                conversation.Source   = ConversationSource.FacebookWallPost;
                conversation.IsHidden = true;
            }

            conversation.Messages.Add(message);
            await AddConversation(socialAccount, conversation);

            await CurrentUnitOfWork.SaveChangesAsync();

            if (!conversation.IsHidden)
            {
                result.WithNewConversation(conversation);
            }

            return(result);
        }
Beispiel #6
0
        public static void RegisterAuth()
        {
            var fbClient = new FbClient();

            // To let users of this site log in using their accounts from other sites such as Microsoft, Facebook, and Twitter,
            // you must update this site. For more information visit http://go.microsoft.com/fwlink/?LinkID=252166

            //OAuthWebSecurity.RegisterMicrosoftClient(
            //    clientId: "",
            //    clientSecret: "");

            //OAuthWebSecurity.RegisterTwitterClient(
            //    consumerKey: "",
            //    consumerSecret: "");

            // prod
            //OAuthWebSecurity.RegisterFacebookClient(
            //    appId: "262309163906980",
            //    appSecret: "3439950f4bf262d8041e28cdb1b7416c");

            // dev
            //OAuthWebSecurity.RegisterFacebookClient(
            //    appId: "170633953128198",
            //    appSecret: "2a94e68adc55ff563a8c4ff178a85662");

            OAuthWebSecurity.RegisterFacebookClient(
                appId: fbClient.AppId,
                appSecret: fbClient.AppSecret);

            OAuthWebSecurity.RegisterGoogleClient();
        }
Beispiel #7
0
        /// <summary>
        /// Fetches data returned by dialog from callback uri
        /// </summary>
        /// <param name="uri">Callback uri of dialog</param>
        private static Task <object> FetchDialogUriAsync(Uri uri)
        {
            var tcs = new TaskCompletionSource <object>();

            Deployment.Current.Dispatcher.BeginInvoke(() => tcs.SetResult(FbClient.ParseDialogCallbackUrl(uri)));

            return(tcs.Task);
        }
        public void MarkRequestsConsumed(string requestId)
        {
            if (String.IsNullOrEmpty(requestId))
            {
                return;
            }

            FbClient.Delete(String.Format("{0}_{1}", requestId, FacebookWebContext.Current.UserId));
        }
        public MeDTO GetMe()
        {
            dynamic me = FbClient.Get(FacebookHelper.MeQuery);

            if (me != null)
            {
                return(_builder.BuildMe(me));
            }

            return(null);
        }
        public async Task VerifyPost(string PostId)
        {
            var db = new SoLoudContext();

            Post post = db.Posts.FirstOrDefault(x => x.Id == PostId);

            if (post == null)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content = new StringContent("No Post with such id")
                });
            }
            else if (post.PostStatus.Equals(PostStatus.Verified))
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Post already verified")
                });
            }

            var user = db.Users.Include("Claims").FirstOrDefault(x => x.Id == post.UserId);

            if (user == null)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.ExpectationFailed)
                {
                    Content = new StringContent(String.Format("Post is connected to user with id {0} but no such user was found", post.UserId))
                });
            }

            var FbClaim = user.Claims.FirstOrDefault(x => x.ClaimType == SoloudClaimTypes.FacebookAccessToken.ToString() && x.UserId == user.Id);

            if (FbClaim == null)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.ExpectationFailed)
                {
                    Content = new StringContent(String.Format("No saved fb token was found for user with id {0}", user.Id))
                });
            }

            var EncryptedFbToken = FbClaim.ClaimValue;
            var DecryptedFbToken = AESThenHMAC.SimpleDecryptWithPassword(EncryptedFbToken, EncryptionKey);

            var fbClient = new FbClient(DecryptedFbToken);

            var fbResponse = await fbClient.MultiphotoStory(post.Photos.ToList(), post.Text, post.PlaceId);

            post.VerifiedAt = DateTimeOffset.Now;
            //post.IsVerified = true;
            post.PostStatus = PostStatus.Verified;
            post.FacebookId = fbResponse.id;
            db.SaveChanges();
        }
 private void WebBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
 {
     try
     {
         var callback = webBrowser.Source;
         var oauth    = FbClient.ParseOAuthCallbackUrl(callback);
         FbClient.AccessToken = oauth.AccessToken;
         FbAccountLoggedIn    = true;
         browserWindow.Close();
         MessageBox.Show("Authentication successful. You can now post recipes to Facebook.");
     }
     catch (Exception ex)
     {
         return;
     }
 }
        public IEnumerable <FacebookFriendDTO> GetFriends()
        {
            dynamic friends = FbClient.Get(FacebookHelper.FriendsQuery);
            var     data    = friends.data as IEnumerable <dynamic>;

            var results = new List <FacebookFriendDTO>();

            data.ForEach(f => {
                if (f.installed != null && f.installed)
                {
                    results.Add(_builder.BuildFacebookFriend(f));
                }
            });

            return(results);
        }
Beispiel #13
0
        protected override bool ReleaseHandle()
        {
            if (IsClosed)
            {
                return(true);
            }

            IntPtr[]   statusVector = new IntPtr[IscCodes.ISC_STATUS_LENGTH];
            BlobHandle @ref         = this;

            FbClient.isc_close_blob(statusVector, ref @ref);
            handle = @ref.handle;
            var exception = FesConnection.ParseStatusVector(statusVector, Charset.DefaultCharset);

            return(exception == null || exception.IsWarning);
        }
Beispiel #14
0
        /// <summary>
        /// Creates uri for specific dialog
        /// </summary>
        /// <param name="dialogType">Name of dialog, which is added to URI query parameters</param>
        /// <param name="redirectUrl">Callback uri which is called after dialog completes</param>
        /// <param name="dialogOptions">Dictionary of additional options which will be added to dialog URI as query parameters</param>
        private static Task <string> GetDialogUri(string dialogType, string redirectUrl, Dictionary <string, object> dialogOptions)
        {
            var tcs = new TaskCompletionSource <string>();

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                var appId = Session.AppId;
                dialogOptions["client_id"]    = appId;
                dialogOptions["redirect_uri"] = redirectUrl;
                dialogOptions["display"]      = DIALOG_DISPLAY_TYPE;
                dialogOptions["mobile"]       = true;

                tcs.SetResult(FbClient.GetDialogUrl(dialogType, dialogOptions).ToString());
            });

            return(tcs.Task);
        }
Beispiel #15
0
        public void graphApi(string options)
        {
            var args        = JsonHelper.Deserialize <List <string> >(options);
            var apiPath     = args[0];
            var permissions = JsonHelper.Deserialize <string[]>(args[1]);

            Deployment.Current.Dispatcher.BeginInvoke(async() =>
            {
                if (string.IsNullOrEmpty(CurrentTokenData.AccessToken))
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "No active sessions found"));
                    return;
                }

                if (CurrentTokenData.NeedNewPermissions(permissions))
                {
                    var permError = new PermissionsError
                    {
                        Code = "permissions_missing",
                        Uri  =
                            await GetDialogUri("oauth", LOGIN_REDIRECT_URI, new Dictionary <string, object>
                        {
                            { "auth_type", "rerequest" },
                            { "response_type", LOGIN_RESPONSE_TYPE },
                            { "scope", string.Join(",", permissions) }
                        })
                    };

                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, permError));
                    return;
                }

                await Session.CheckAndExtendTokenIfNeeded();

                try
                {
                    dynamic result = await FbClient.GetTaskAsync(apiPath);
                    DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result.ToString()));
                }
                catch (Exception ex)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, ex.Message));
                }
            });
        }
    protected override bool ReleaseHandle()
    {
        Contract.Requires(FbClient != null);

        if (IsClosed)
        {
            return(true);
        }

        var statusVector = new IntPtr[IscCodes.ISC_STATUS_LENGTH];
        var @ref         = this;

        FbClient.isc_rollback_transaction(statusVector, ref @ref);
        handle = @ref.handle;
        var exception = FesConnection.ParseStatusVector(statusVector, Charset.DefaultCharset);

        return(exception == null || exception.IsWarning);
    }
Beispiel #17
0
        protected override bool ReleaseHandle()
        {
            Contract.Requires(FbClient != null);

            if (IsClosed)
            {
                return(true);
            }

            IntPtr[]        statusVector = new IntPtr[IscCodes.ISC_STATUS_LENGTH];
            StatementHandle @ref         = this;

            FbClient.isc_dsql_free_statement(statusVector, ref @ref, IscCodes.DSQL_drop);
            handle = @ref.handle;

            var exception = FesConnection.ParseStatusVector(statusVector, Charset.DefaultCharset);

            return(exception == null || exception.IsWarning);
        }
 public void Share(object propertiesObject)
 {
     if (!FbAccountLoggedIn)
     {
         try
         {
             BrowserWindow browser = new BrowserWindow();
             browserWindow = browser;
             webBrowser    = browser.webBrowser;
             browser.Show();
             var uri = GetLoginUrl();
             browser.webBrowser.Navigate(uri);
             browser.webBrowser.LoadCompleted += WebBrowser_LoadCompleted;
         }
         catch (Exception e)
         {
             MessageBox.Show("Unexpected error during web navigation: " + e.Message, "Navigation error");
         }
     }
     else
     {
         var parameters   = new Dictionary <string, object>();
         var recipeToPost = propertiesObject as Recipe;
         if (recipeToPost == null)
         {
             return;
         }
         parameters["message"] = recipeToPost.Description;
         try
         {
             FbClient.Post("me/feed", parameters);
             MessageBox.Show("Recipe posted.", "Post");
         }
         catch (Exception e)
         {
             MessageBox.Show("Unexpected error during post action: " + e.Message, "Post error");
         }
     }
 }
Beispiel #19
0
        public async override Task <FacebookProcessResult> Process(SocialAccount socialAccount, FbHookChange change)
        {
            var result = new FacebookProcessResult(NotificationManager);

            if (!socialAccount.IfConvertMessageToConversation)
            {
                return(result);
            }

            IList <FbMessage> fbMessages = await FbClient.GetMessagesFromConversationId(socialAccount.Token, change.Value.ThreadId, 10);

            string[]       orgiginalIds    = fbMessages.Select(t => t.Id).ToArray();
            List <Message> existedMessages = MessageService.FindAll().Where(t => t.Source == MessageSource.FacebookMessage && orgiginalIds.Contains(t.OriginalId)).ToList();

            // remove duplicated messages.
            fbMessages = fbMessages.Where(t => !existedMessages.Any(m => m.OriginalId == t.Id)).OrderByDescending(t => t.SendTime).ToList();

            foreach (var fbMessage in fbMessages)
            {
                await Process(result, fbMessage, socialAccount, change);
            }

            return(result);
        }
Beispiel #20
0
        public static Usage GetUsage(Setting setting, HttpRequest request, string oaTenantId)
        {
            var tenant = GetObject(setting, request, oaTenantId);

            return(FbClient.GetUsage(setting, tenant));
        }
Beispiel #21
0
 public IHttpActionResult PublishFacebookComment([MaxLength(2000)] string message, string parentId, string token)
 {
     FbClient.PublishComment(token, parentId, message);
     return(Ok());
 }
Beispiel #22
0
/*
 *      /// <summary>
 *      /// Initializes a new instance of the FacebookLayer class
 *      /// </summary>
 *      public FacebookLayer()
 *      {
 *          this.Auth = new Authorizer();
 *
 *          if (this.Auth.Authorize())
 *          {
 *              this.FbClient = new FacebookClient(CurrentSession.AccessToken);
 *              this.User = new FacebookUser();
 *              try
 *              {
 *                  var me = (IDictionary<string, object>) this.FbClient.Get("me");
 *
 *                  this.User.FacebookId = (string) me["id"];
 *                  this.User.FacebookName = (string) me["first_name"];
 *              }
 *              catch
 *              {
 *                  this.IsAccessTokenValid = false;
 *                  return;
 *              }
 *
 *              this.IsAccessTokenValid = true;
 *              IDictionary<string, object> friendsData = (IDictionary<string, object>) this.FbClient.Get("me/friends");
 *              this.facebookData = new FacebookData(this.User, friendsData);
 *              this.SortedFriends = this.facebookData.SortedFriends;
 *          }
 *      }
 */

        /// <summary>
        /// Initializes a new instance of the FacebookLayer class using authorization
        /// </summary>
        /// <param name="auth">authorization instance</param>
        public FacebookLayer(Authorizer auth)
        {
            this.Auth = auth;

            if (auth.Authorize())
            {
                this.FbClient = new FacebookClient(CurrentSession.AccessToken);
                this.User     = new FacebookUser();
                try
                {
                    var me = (IDictionary <string, object>) this.FbClient.Get("me");

                    this.User.FacebookId   = (string)me["id"];
                    this.User.FacebookName = (string)me["first_name"];
                }
                catch
                {
                    this.IsAccessTokenValid = false;
                    return;
                }

                this.IsAccessTokenValid = true;
                IDictionary <string, object> friendsData = (IDictionary <string, object>)FbClient.Get("me/friends");
                facebookData = new FacebookData(User, (IList <object>)friendsData["data"]);
            }
        }
Beispiel #23
0
 public static List <FB_Message> GetChat(FbClient client, string chat_id)
 {
     return(client.FetchThreadMessages(chat_id).GetAwaiter().GetResult());
 }
Beispiel #24
0
 public static List <FB_Thread> GetChats(FbClient client)
 {
     return(client.fetchThreadList().GetAwaiter().GetResult());
 }
Beispiel #25
0
        // ReSharper restore InconsistentNaming, UnusedMember.Global

        #region Private methods

        /// <summary>
        /// Updates an AccessTokenData object with data fetched from FB API.
        /// Updates ActiveSession with updated AccessTokenData object.
        /// Uses CurrentAccessTokenData if parameter is null
        /// </summary>
        /// <param name="tempToken">AccessTokenData object to update</param>
        /// <returns>LoginStatus object</returns>
        private static Task <LoginStatus> UpdateAndGetLoginStatus(AccessTokenData tempToken = null)
        {
            var tcs = new TaskCompletionSource <LoginStatus>();

            Deployment.Current.Dispatcher.BeginInvoke(async() =>
            {
                if (tempToken != null)
                {
                    CurrentTokenData = tempToken;
                }

                if (string.IsNullOrEmpty(CurrentTokenData.AccessToken))
                {
                    tcs.SetResult(new LoginStatus {
                        Status = "unknown"
                    });
                    return;
                }

                await Session.CheckAndExtendTokenIfNeeded();

                if (CurrentTokenData.CurrentPermissions.Count == 0 || string.IsNullOrEmpty(CurrentTokenData.FacebookId))
                {
                    // Create a copy of existing access token data to update it with new values
                    var newTokenData = CurrentTokenData.Clone();

                    try
                    {
                        var result =
                            (JsonObject)
                            await
                            FbClient.GetTaskAsync("debug_token",
                                                  new { input_token = CurrentTokenData.AccessToken });

                        var data = (JsonObject)result.ToDictionary(pair => pair.Key, pair => pair.Value)["data"];

                        var userId = (string)data.ToDictionary(pair => pair.Key, pair => pair.Value)["user_id"];
                        newTokenData.FacebookId = userId;

                        var actualPermissions = (JsonArray)data.ToDictionary(pair => pair.Key, pair => pair.Value)["scopes"];
                        foreach (var actualPermission in actualPermissions)
                        {
                            newTokenData.CurrentPermissions.Add((string)actualPermission);
                        }

                        Session.ActiveSession.CurrentAccessTokenData = newTokenData;
                    }
                    catch
                    {
                        // No need to fail here, just return a loginStatus object without userID
                    }
                }

                var loginStatus = new LoginStatus
                {
                    Status       = "connected",
                    AuthResponse = new AuthResponse
                    {
                        AccessToken = CurrentTokenData.AccessToken,
                        ExpiresIn   = CurrentTokenData.Expires,
                        UserId      = CurrentTokenData.FacebookId
                    }
                };

                tcs.SetResult(loginStatus);
            });

            return(tcs.Task);
        }
Beispiel #26
0
        public static string Create(Setting setting, HttpRequest request, OaTenant oaTenant)
        {
            var tenant = GetObject(setting, request, oaTenant);

            return(FbClient.Create(setting, tenant));
        }
 public void Post(string action, object args)
 {
     FbClient.Post(action, args);
 }
Beispiel #28
0
 public IHttpActionResult PublishFacebookPost(string pageId, [MaxLength(2000)] string message, string token)
 {
     FbClient.PublishPost(pageId, token, message);
     return(Ok());
 }
Beispiel #29
0
        public static string GetAdminLogin(Setting setting, HttpRequest request, string oaTenantId)
        {
            var tenant = GetObject(setting, request, oaTenantId);

            return(FbClient.GetAdminLogin(setting, tenant));
        }
Beispiel #30
0
        public static void Delete(Setting setting, HttpRequest request, string oaTenantId)
        {
            var tenant = GetObject(setting, request, oaTenantId);

            FbClient.Delete(setting, tenant);
        }
Beispiel #31
0
        public static void Update(Setting setting, HttpRequest request, OaTenant oaTenant)
        {
            var tenant = GetObject(setting, request, oaTenant);

            FbClient.Update(setting, tenant);
        }