コード例 #1
0
        public IEnumerable <Models.User> Get()
        {
            List <Models.User> friends = new List <Models.User>();

            var token = _db.User.FirstOrDefault(c => c.UserId == WebSecurity.CurrentUserId).Services.FirstOrDefault(c => c.Provider == "facebook").Token;

            if (token != null)
            {
                FacebookAPI facebook = new FacebookAPI(token);
                dynamic     status   = facebook.GetFacebookUsersFriends();
                if (!(status is int) && status.ContainsKey("data"))
                {
                    foreach (var friend in status.data)
                    {
                        //do something here
                        string id       = friend.uid2;
                        var    username = OAuthWebSecurity.GetUserName("facebook", id);
                        if (username != null)
                        {
                            var         local_id = WebSecurity.GetUserId(username);
                            Models.User user     = _db.User.FirstOrDefault(c => c.UserId == local_id);
                            if (user != null)
                            {
                                friends.Add(user);
                            }
                        }
                    }
                }
            }


            return(friends);
        }
コード例 #2
0
    private void handleFacebookUser(string sessionKey, string userId)
    {
        log.Debug("Handling facebook user", userId);

        facebookApi = new FacebookAPI();

        facebookApi.IsDesktopApplication = false;
        facebookApi.ApplicationKey       = apikey;
        facebookApi.Secret = apisecret;

        facebookApi.SessionKey = sessionKey;
        facebookApi.UserId     = userId;

        facebookApi.ConnectToFacebook();

        FacebookId = facebookApi.GetLoggedInUser();
        Collection <Facebook.Entity.User> fb_users = facebookApi.GetUserInfo(facebook_id);

        log.Debug("Got Facebook users fb_users", fb_users);
        fb_user = fb_users[0];
        log.Debug("Facebook user fb_user", fb_user);

        IRecordList <DreamFolk> dreamFolk = DataProvider.LoadList <DreamFolk>(new FilterInfo("FacebookId", FacebookId));

        log.Debug("Got dreamFolk folk with FacebookId", FacebookId, dreamFolk);

        DreamFolk dreamPerson = null;

        if (dreamFolk.Count > 0)
        {
            dreamPerson = dreamFolk[0];
        }

        if (dreamPerson == null)
        {
            log.Warn("Creating new dreamPerson from Main.Current");
            dreamPerson = new DreamFolk(Main.Current.FbUser);
            dreamPerson.Save(true);
        }

        /*
         * else if ( dreamPerson.Birthday != Main.Current.FbUser.Birthday )
         * {
         *      log.Warn("Updating birthday dreamPerson from Main.Current");
         *      dreamPerson.Birthday = (DateTime)Main.Current.FbUser.Birthday;
         *      dreamPerson.Save(true);
         * }
         * else if ( !dreamPerson.Updated )
         */
        else
        {
            log.Warn("Updating dreamPerson");
            dreamPerson.update(fb_user);
            dreamPerson.Updated = true;
            dreamPerson.Save(true);
        }

        CurrentDreamFriend = dreamPerson;
        Now.Friends        = CurrentDreamFriend.Friends;
    }
コード例 #3
0
    public void OnButtonFindTableClicked(string _defaultId)
    {
        MyAudioManager.instance.PlaySfx(GameInformation.instance.globalAudioInfo.sfx_Click);

        if (DataManager.instance.userData.databaseId == UserData.DatabaseType.DATABASEID_FACEBOOK &&
            !FacebookAPI.IsLoggedIn())
        {
                        #if TEST
            Debug.LogError(">>> Chưa Login FB mà");
                        #endif
            if (actionLoginFbAgain == null)
            {
                actionLoginFbAgain = FacebookAPI.DoActionLoginFb(null, () => {
                    actionLoginFbAgain = null;
                });
                StartCoroutine(actionLoginFbAgain);
            }
        }

        PopupManager.Instance.CreatePopupJoinTable(_defaultId, (_id, _pass) => {
            if (!string.IsNullOrEmpty(_id))
            {
                OnFindTableClicked(_id, _pass);
            }
        }, null);
    }
コード例 #4
0
 void OnPlayNowCreateConnectionSuccess()
 {
     if (currentSubGameDetail == null)
     {
                     #if TEST
         Debug.LogError("currentMiniGameDetail is null");
                     #endif
         return;
     }
     if (DataManager.instance.userData.databaseId == UserData.DatabaseType.DATABASEID_FACEBOOK &&
         !FacebookAPI.IsLoggedIn())
     {
                     #if TEST
         Debug.LogError(">>> Chưa Login FB mà");
                     #endif
         if (actionLoginFbAgain == null)
         {
             actionLoginFbAgain = FacebookAPI.DoActionLoginFb(null, () => {
                 actionLoginFbAgain = null;
             });
             StartCoroutine(actionLoginFbAgain);
         }
         return;
     }
     GlobalRealTimeSendingAPI.SendMessagePlayNowMiniGame(currentSubGameDetail.myInfo.gameId);
 }
コード例 #5
0
        public async Task <IResponse> FacebookSignIn([FromBody] FacebookLoginModel facebookLoginModel)
        {
            ExternalLoginResponse externalLoginResponse = new ExternalLoginResponse();

            externalLoginResponse.IsModelValid = ModelState.IsValid;
            if (ModelState.IsValid)
            {
                FacebookDataModel facebookData = await FacebookAPI.GetUserLoginData(facebookLoginModel.AccessToken);

                ExternalLoginInfo info = CustomExternalLoginInfo.FromLoginModel("Facebook", facebookData);

                var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, true);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in");
                }
                externalLoginResponse.IsRegistered = result.Succeeded;
                externalLoginResponse.Result       = result;
            }
            else
            {
                externalLoginResponse.Errors = ModelState.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage));
            }
            return(externalLoginResponse);
        }
コード例 #6
0
ファイル: Connect2dNode.cs プロジェクト: vnmone/vvvv-sdk
        public void SetPluginHost(IPluginHost Host)
        {
            this.FHost = Host;

            this.FHost.CreateStringInput("Users", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinInUsers);

            //Input
            this.FHost.CreateValueInput("X In", 1, null, TSliceMode.Dynamic, TPinVisibility.True, out this.FPinInX);
            this.FPinInX.SetSubType(double.MinValue, double.MaxValue, 0.01, 0, false, false, false);

            this.FHost.CreateValueInput("Y In", 1, null, TSliceMode.Dynamic, TPinVisibility.True, out this.FPinInY);
            this.FPinInY.SetSubType(double.MinValue, double.MaxValue, 0.01, 0, false, false, false);

            //Output
            this.FHost.CreateValueOutput("X1 Out", 1, null, TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutX1);
            this.FPinOutX1.SetSubType(double.MinValue, double.MaxValue, 0.01, 0, false, false, false);

            this.FHost.CreateValueOutput("Y1 Out", 1, null, TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutY1);
            this.FPinOutY1.SetSubType(double.MinValue, double.MaxValue, 0.01, 0, false, false, false);

            this.FHost.CreateValueOutput("X2 Out", 1, null, TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutX2);
            this.FPinOutX2.SetSubType(double.MinValue, double.MaxValue, 0.01, 0, false, false, false);

            this.FHost.CreateValueOutput("Y2 Out", 1, null, TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutY2);
            this.FPinOutY2.SetSubType(double.MinValue, double.MaxValue, 0.01, 0, false, false, false);

            this.api = APIShared.API;
        }
コード例 #7
0
ファイル: AccountController.cs プロジェクト: msanj1/BOTFv2
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            var url = Url.Action("ExternalLoginCallback");



            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl })); //facebook 2hrs token



            FacebookToken = result.ExtraData["accesstoken"];
            Provider      = result.Provider;
            if (Provider == "facebook")
            {
                string token = FacebookAPI.GetLongtermFbToken(FacebookToken);
                FacebookToken = token;
            }

            if (!result.IsSuccessful)
            {
                return(RedirectToAction("ExternalLoginFailure"));
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                string            username  = OAuthWebSecurity.GetUserName(result.Provider, result.ProviderUserId);
                int               userId    = WebSecurity.GetUserId(username);
                FacebookScheduler scheduler = new FacebookScheduler();
                scheduler.RunScheduler(FacebookToken, userId);

                return(RedirectToLocal(returnUrl));
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                DatabaseCallsApi _api = new DatabaseCallsApi();

                var username = OAuthWebSecurity.GetUserName(result.Provider, result.ProviderUserId);
                int user_id  = WebSecurity.GetUserId(username);
                _api.AddOrUpdateService(user_id, result.Provider, FacebookToken);
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);

                return(RedirectToLocal(returnUrl));
            }
            else
            {
                // User is new, ask for their desired membership name



                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl           = returnUrl;
                return(View("ExternalLoginConfirmation", new RegisterExternalLoginModel {
                    UserName = result.UserName, ExternalLoginData = loginData
                }));
            }
        }
コード例 #8
0
        internal FacebookAuthentication(Uri loginUrl, string state, FacebookAPI fbApi)
            : this()
        {
            _previousState = state;

            wbFacebookLogin.Navigate(loginUrl);
            _fbApi = fbApi;
        }
コード例 #9
0
        public HttpResponseMessage Post(int Id, bool ArtistPost)
        {
            Proposal currProposal = _db.Proposal.FirstOrDefault(c => c.Id == Id);

            Models.Service service = _db.User.FirstOrDefault(c => c.UserId == WebSecurity.CurrentUserId).Services.FirstOrDefault(c => c.Provider == "facebook");

            if (service != null)
            {
                FacebookAPI facebook = new FacebookAPI(service.Token);

                if (service != null && currProposal != null)
                {
                    dynamic status;
                    if (ArtistPost)
                    {
                        status = facebook.InsertToArtistFeed(currProposal, WebSecurity.CurrentUserId, System.Web.HttpContext.Current.Request.UrlReferrer.ToString());
                    }
                    else
                    {
                        status = facebook.InsertToFeed(currProposal, WebSecurity.CurrentUserId, System.Web.HttpContext.Current.Request.UrlReferrer.ToString());
                    }

                    if (status is int && status == 1)
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotFound));
                    }
                    else if (status is int && status == 2)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadGateway));
                    }
                    else if (status is int && status == 3)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest));
                    }
                    else if (status is int && status == 4)
                    {
                        return(Request.CreateResponse(HttpStatusCode.Created));
                    }
                    else
                    {
                        if (ArtistPost)
                        {
                            _api.AddOrUpdateFacebookArtistPost(currProposal.Id, WebSecurity.CurrentUserId, status["id"].ToString());    //saving post id from facebook
                        }
                        else
                        {
                            _api.AddOrUpdateFacebookPost(currProposal.Id, WebSecurity.CurrentUserId, status["id"].ToString());
                        }


                        return(Request.CreateResponse(HttpStatusCode.Created));
                    }
                }
            }


            return(Request.CreateResponse(HttpStatusCode.BadRequest));
        }
コード例 #10
0
 public void ClearAllData()
 {
     DataManager.ClearData();
     PlayerPrefs.DeleteAll();
     if (FacebookAPI.IsLoggedIn())
     {
         FacebookAPI.LogOut();
     }
 }
コード例 #11
0
ファイル: GroupInfoNode.cs プロジェクト: vnmone/vvvv-sdk
        public void SetPluginHost(IPluginHost Host)
        {
            this.FHost = Host;

            this.FHost.CreateStringInput("Groups", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinInGroups);
            this.FHost.CreateStringOutput("Names", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutName);
            this.FHost.CreateStringOutput("Description", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutDescription);
            this.FHost.CreateStringOutput("Types", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutTypes);

            this.api = APIShared.API;
        }
コード例 #12
0
ファイル: MyProfileNode.cs プロジェクト: vnmone/vvvv-sdk
        public void SetPluginHost(IPluginHost Host)
        {
            this.FHost = Host;

            this.FHost.CreateStringInput("Application Key", TSliceMode.Single, TPinVisibility.True, out this.FPinInAppKey);
            this.FHost.CreateStringInput("Secret Key", TSliceMode.Single, TPinVisibility.True, out this.FPinInSecret);

            this.FHost.CreateStringOutput("Friends", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutFriends);
            this.FHost.CreateStringOutput("Groups", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutGroups);

            this.api = APIShared.API;
        }
コード例 #13
0
 void Init()
 {
     DataManager.Init();
     FacebookAPI.Init();
     MyLocalize.InitData();
     LeanTween.init();
     #if UNITY_ANDROID
     onKeyBackClicked = new List <System.Action>();
     #endif
     Application.targetFrameRate = 60;
     Screen.sleepTimeout         = SleepTimeout.NeverSleep;
 }
コード例 #14
0
 public HomeController(
     ILogger <HomeController> logger,
     ApplicationDbContext db,
     IOptions <FacebookAPI> options,
     IOptions <AppConfig> config,
     UserManager <IdentityUser> userManager)
 {
     _logger        = logger;
     _db            = db;
     _apiCredential = options.Value;
     _config        = config.Value;
     _userManager   = userManager;
 }
コード例 #15
0
        public Form1()
        {
            InitializeComponent();
            BackColor = Color.FromArgb(59, 88, 151);
            Font      = new Font("lucida grand", 14, GraphicsUnit.Pixel);

            progBarDownload.Minimum = 0;
            progBarDownload.Maximum = 0;
            progBarDownload.Step    = 1;

            facebook                    = new FacebookAPI();
            facebook.UserLogged        += new FacebookAPI.delegate_UserLoggedEventHandler(facebook_UserLogged);
            facebook.PictureDownloaded += new FacebookAPI.delegate_PicrureDownloaded(facebook_PictureDownloaded);
        }
コード例 #16
0
        public async Task <ActionResult> BandDirectory()
        {
            List <Band>             bands  = context.Bands.Include("Social").Include("Location").ToList();
            List <BandPicViewModel> models = new List <BandPicViewModel>();

            foreach (Band band in bands)
            {
                BandPicViewModel temp = new BandPicViewModel();
                temp.band        = band;
                temp.facebookUrl = await FacebookAPI.GetProfilePicture(band.Social.facebookPageId);

                models.Add(temp);
            }
            return(View(models));
        }
コード例 #17
0
 public AccountController(
     UserManager <ApplicationUser> userManager,
     SignInManager <ApplicationUser> signInManager,
     FacebookAPI fbapi,
     IEmailSender emailSender,
     ISmsSender smsSender,
     ILoggerFactory loggerFactory)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _fbapi         = fbapi;
     _emailSender   = emailSender;
     _smsSender     = smsSender;
     _logger        = loggerFactory.CreateLogger <AccountController>();
 }
コード例 #18
0
ファイル: SendeeManager.cs プロジェクト: jphacks/NG_1808
 // Use this for initialization
 void Start()
 {
     FacebookAPI.GetFriendsID(IDs =>
     {
         foreach (var ID in IDs)
         {
             UserPreference.GetPreferencefromID(ID, userPreference =>
             {
                 string friendsName            = userPreference.name;
                 GameObject SendeeNodeInstance = Instantiate(SendeeNodePrefab, SendeeViewContent.transform);
                 SendeeNodeInstance.SendMessage("Init", friendsName);
                 SendeeNodeInstance.SendMessage("InitID", ID);
             });
         }
     });
 }
コード例 #19
0
ファイル: UserInfoNode.cs プロジェクト: vnmone/vvvv-sdk
        public void SetPluginHost(IPluginHost Host)
        {
            this.FHost = Host;


            this.FHost.CreateStringInput("Users", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinInUsers);

            this.FHost.CreateStringOutput("First Name", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutFirstName);
            this.FHost.CreateStringOutput("Surname", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutSurname);
            this.FHost.CreateStringOutput("Birthday", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutBirthday);
            this.FHost.CreateStringOutput("Picture", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutPicture);
            this.FHost.CreateStringOutput("Status", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutStatus);
            this.FHost.CreateStringOutput("Gender", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutGender);
            this.FHost.CreateStringOutput("Interests", TSliceMode.Dynamic, TPinVisibility.True, out this.FPinOutInterests);

            this.api = APIShared.API;
        }
コード例 #20
0
 public static void Init(Facebook.Unity.AccessToken aToken)
 {
     if (_userData == null)
     {
         _userData                  = UserData.CreateInstance <UserData>();
         _userData._userId          = aToken.UserId;
         _userData._userAccessToken = aToken.TokenString;
         PlayerPrefs.SetString("user_local_ID", _userData._userId);
         PlayerPrefs.SetString("user_local_token", _userData._userAccessToken);
         Debug.Log("UserData: Create UserData");
         FacebookAPI.GetUserProfile(_userData._userId, result =>
         {
             _userData._userName = result["name"];
             PlayerPrefs.SetString("gender", result["gender"]);
         });
     }
 }
コード例 #21
0
    public void Login_OnButtonLoginFbClicked()
    {
                #if TEST
        Debug.Log("Login FB");
                #endif
        MyAudioManager.instance.PlaySfx(GameInformation.instance.globalAudioInfo.sfx_Click);

        if (actionLoginFaceBook == null)
        {
            actionLoginFaceBook = FacebookAPI.DoActionLoginFb(() => {
                CallBackLoginFb();
            }, () => {
                actionLoginFaceBook = null;
            });
            StartCoroutine(actionLoginFaceBook);
        }
    }
コード例 #22
0
        private void ProcessFacebookData(string path, Func <JSONObject, List <Task> > task)
        {
            List <Task> tasks = new List <Task>();
            var         api   = new FacebookAPI(Token);
            var         args  = new Dictionary <string, string>();

            args.Add("limit", "100");
            var results = api.Get(path, args);
            var next    = (results.Dictionary.ContainsKey("paging")) &&
                          results.Dictionary["paging"].Dictionary.ContainsKey("next")
                ? results.Dictionary["paging"].Dictionary["next"].String : null;

            do
            {
                tasks.AddRange(task(results.Dictionary["data"]));

                if (!string.IsNullOrEmpty(next))
                {
                    args = new Dictionary <string, string>();
                    args.Add("until", next.Split(new string[] { "until=" }, StringSplitOptions.RemoveEmptyEntries)[1]);
                    args.Add("limit", "100");
                    results = api.Get(path, args);
                    if (results.Dictionary.ContainsKey("paging"))
                    {
                        if (next != results.Dictionary["paging"].Dictionary["next"].String)
                        {
                            next = results.Dictionary["paging"].Dictionary["next"].String;
                        }
                        else
                        {
                            next = null; results = null;
                        }
                    }
                    else
                    {
                        next = null; results = null;
                    }
                }
                else
                {
                    results = null;
                }
            }while (results != null);
            Task.WaitAll(tasks.ToArray());
        }
コード例 #23
0
        /// <summary>
        /// Initialized Facebook session
        /// </summary>
        private void InitializeFacebook()
        {
            if (bool.Parse(CommonFunctions.GetSetting("EventsEnabled_Service_Facebook")))
            {
                _fbApi = new FacebookAPI
                {
                    IsDesktopApplication = true,
                    ApplicationKey       = _fbAppId,
                };

                // If persistent session key was found, use it, else login
                if (!string.IsNullOrEmpty(_fbAccessToken = CommonFunctions.GetSetting("Facebook_AccessToken")) && !_fbAccessToken.Equals("false"))
                {
                    _fbApi.AccessToken = _fbAccessToken;

                    try
                    {
                        string uid = _fbApi.GetLoggedInUser();

                        // If uid was not found, session is invalid
                        if (string.IsNullOrEmpty(uid))
                        {
                            _fbApi.AccessToken = "";

                            CommonFunctions.SetSetting("Facebook_AccessToken", "");

                            FacebookLogin(false);
                        }
                    }
                    catch (Exception)
                    {
                        _fbApi.AccessToken = "";

                        CommonFunctions.SetSetting("Facebook_AccessToken", "");

                        FacebookLogin(false);
                    }
                }
                else
                {
                    FacebookLogin(false);
                }
            }
        }
コード例 #24
0
        private void GetFacebookCaption(MemoryStream image)
        {
            if (CaptionWindow?.IsVisible ?? false)
            {
                return;
            }
            CaptionWindow = new FacebookCaptionView();
            CaptionWindow.CaptionWritten += async(caption) =>
            {
                string feedback = await FacebookAPI.ShareImage(image, AuthService.FacebookAccessToken, caption);

                ToastsService.Pop("Facebook sharing", feedback, Constants.FacebookIconUri);
                if (AuthService.IsLoggedIn)
                {
                    await AchievementsService.Increment(AuthService.CurrentUser.Id, AchievementMetrics.SharesOnFacebook);
                }
            };

            CaptionWindow.Show();
        }
コード例 #25
0
        public HttpResponseMessage PostComment(ViewComment comment)
        {
            if (ModelState.IsValid)
            {
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
                _db.Comment.Add(new Comment {
                    ProposalId = comment.Id, Body = comment.Body, CreatedBy = WebSecurity.CurrentUserId, CreatedDate = DateTime.UtcNow
                });
                _db.SaveChanges();

                Service  service  = _db.User.FirstOrDefault(c => c.UserId == WebSecurity.CurrentUserId).Services.FirstOrDefault(c => c.Provider == "facebook");       //get service for posting to feed
                Proposal proposal = _db.Proposal.FirstOrDefault(c => c.Id == comment.Id && c.FacebookPostId != null && c.FacebookPostId != "");
                if (service != null && proposal != null)
                {
                    FacebookAPI facebook = new FacebookAPI(service.Token);
                    int         status   = facebook.postCommentToPost(proposal.FacebookPostId, comment.Body, WebSecurity.CurrentUserId);

                    if (status == 1)
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotFound));
                    }
                    else if (status == 2)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadGateway));
                    }
                    else if (status == 3)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest));
                    }
                    //facebook.postCommentToPost();
                }



                return(response);
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
        }
コード例 #26
0
        //Gathers comments from a few specified facebook and reddit accounts to use as training data
        private void GatherTrainingData()
        {
            List <string> conservativeComments = new List <string>();
            List <string> liberalComments      = new List <string>();

            RedditAPI   rd = new RedditAPI();
            FacebookAPI fb = new FacebookAPI();

            //TODO: Check if these still work with the changes to GetPosts
            conservativeComments.AddRange(fb.GetPostMessages("DonaldTrump"));
            conservativeComments.AddRange(fb.GetPostMessages("VicePresidentPence"));
            conservativeComments.AddRange(fb.GetPostMessages("100000544532899"));
            conservativeComments.AddRange(fb.GetPostMessages("100001387924004"));
            conservativeComments.AddRange(fb.GetPostMessages("100001351601986"));
            conservativeComments.AddRange(fb.GetPostMessages("100007241612747"));

            conservativeComments.AddRange(rd.GetCommentsText("JackalSpat"));
            conservativeComments.AddRange(rd.GetCommentsText("neemarita"));
            conservativeComments.AddRange(rd.GetCommentsText("AVDLatex"));
            conservativeComments.AddRange(rd.GetCommentsText("optionhome"));
            conservativeComments.AddRange(rd.GetCommentsText("2481632641282565121k"));

            liberalComments.AddRange(fb.GetPostMessages("100007731198419"));
            liberalComments.AddRange(fb.GetPostMessages("1534242220"));
            liberalComments.AddRange(fb.GetPostMessages("1521723653"));
            liberalComments.AddRange(fb.GetPostMessages("100001884654096"));
            liberalComments.AddRange(fb.GetPostMessages("hillaryclinton"));

            liberalComments.AddRange(rd.GetCommentsText("Mentoman72"));
            liberalComments.AddRange(rd.GetCommentsText("jereddit"));
            liberalComments.AddRange(rd.GetCommentsText("TheHeckWithItAll"));
            liberalComments.AddRange(rd.GetCommentsText("bustopher-jones"));
            liberalComments.AddRange(rd.GetCommentsText("TheSelfGoverned"));
            liberalComments.AddRange(rd.GetCommentsText("Splatypus"));

            string liberalPath      = System.Web.Hosting.HostingEnvironment.MapPath(@"~/Data/liberal_training.txt");
            string conservativePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/Data/conservative_training.txt");

            File.WriteAllLines(liberalPath, liberalComments.ToArray());
            File.WriteAllLines(conservativePath, conservativeComments.ToArray());
        }
コード例 #27
0
    public void OnClickLogOut()
    {
        MyAudioManager.instance.PlaySfx(GameInformation.instance.globalAudioInfo.sfx_Click);
        PopupManager.Instance.CreatePopupDialog(MyLocalize.GetString(MyLocalize.kWarning)
                                                , MyLocalize.GetString("System/AskForLogOut")
                                                , string.Empty
                                                , MyLocalize.GetString(MyLocalize.kOk)
                                                , MyLocalize.GetString(MyLocalize.kCancel)
                                                , () => {
            DataManager.instance.userData = new UserData();
            DataManager.instance.userData.InitData();

            DataManager.instance.parentUserData = new UserData();

            DataManager.instance.achievementData = new AchievementData();
            DataManager.instance.achievementData.InitData();

            DataManager.instance.dailyRewardData.ResetLoginData();
            DataManager.instance.subsidyData.ResetLoginData();

            DataManager.instance.installAppData = new InstallAppData();
            DataManager.instance.installAppData.InitData();

            DataManager.instance.purchaseReceiptData = new PurchaseReceiptData();
            DataManager.instance.purchaseReceiptData.InitData();

            DataManager.instance.remindRating_GoldUserCatched = 0;

            if (FacebookAPI.IsLoggedIn())
            {
                FacebookAPI.LogOut();
            }

            HomeManager.getGoldAndGemInfoAgain = true;
            HomeManager.hasShowTopAndBottomBar = false;
            HomeManager.myCurrentState         = HomeManager.State.LogOutAndBackToLoginScreen;
            SceneLoaderManager.instance.LoadScene(MyConstant.SCENE_HOME);
        }, null);
    }
コード例 #28
0
        public SocialNetworkingSearchResult Search(string searchParameters, int page)
        {
            List <SocialNetworkingItem> list;

            try
            {
                var        api       = new FacebookAPI();
                var        engineURL = GetEngineUrl();
                JSONObject json      = api.Get(engineURL + searchParameters + "&type=post&limit=100");

                list = SocialNetworkingItemList(json);
                return(new SocialNetworkingSearchResult()
                {
                    SocialNetworkingItems = list, SocialNetworkingName = Name
                });
            }
            catch (Exception e)
            {
                Logger.Log.Error(e);
            }
            return(null);
        }
コード例 #29
0
        public HttpResponseMessage Delete(Viewdelete delete)
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);



            if (delete.isFacebook)
            {
                Service service = _db.User.FirstOrDefault(c => c.UserId == WebSecurity.CurrentUserId).Services.FirstOrDefault(c => c.Provider == "facebook");
                if (service != null)
                {
                    FacebookAPI facebook = new FacebookAPI(service.Token);
                    int         status   = facebook.deleteComment(delete.Id.ToString(), delete.PostId); //delete comment from a post on facebook
                    if (status == 1)
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotFound));
                    }
                    else if (status == 2)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadGateway));
                    }
                    else if (status == 3)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest));
                    }
                }
            }
            else
            {
                int     id      = Convert.ToInt32(delete.Id);
                Comment comment = _db.Comment.FirstOrDefault(c => c.Id == id);
                _db.Comment.Remove(comment);
                _db.SaveChanges();
            }
            return(response);
        }
コード例 #30
0
        public async Task <ActionResult> ViewBandProfile(int bandId)
        {
            Band band = GetBand(bandId);
            BandProfileViewModel model   = new BandProfileViewModel();
            SocialMediaIds       socials = GetBandSocials(band.socialId);

            model.band             = band;
            model.facebookImageUrl = await FacebookAPI.GetProfilePicture(socials.facebookPageId);

            model.facebookPermalinks = await FacebookAPI.GetPermaUrlFromPost(socials.facebookPageId);

            model.youtubeUrls = await GetYoutubeUrls(band);

            //model.facebookPermalinks = new List<string>(); // place holder for less API calls
            //model.youtubeUrls = new List<string>();

            model.reviews = GetBandReviews(band);
            model.score   = AverageReviews(model.reviews);
            model.gigs    = GetGigViewModel(GetGigs(band));



            return(View(model));
        }
コード例 #31
0
	// Obtem as informacoes do Facebook no servidor
	private IEnumerator getLoginResult(string auth, object state, LoginCallback callback)
	{
		// Numero maximo de tentativas
		int max_attempts = 5;
		
		WWW conn = null;
		
		WWWForm form = new WWWForm();
		form.AddField("device", SystemInfo.deviceUniqueIdentifier.Replace("-", ""));
		form.AddField("authentication", auth);
		
		while (max_attempts > 0)
		{
			conn = new WWW(Flow.URL_BASE + "login/facebook/fbinfo.php", form);
			yield return conn;
			
			if (conn.error != null || conn.text != "") break;
			
			max_attempts--;
			
			yield return new WaitForSeconds(1);
		}
		
		if (max_attempts == 0 || conn.error != null)
		{
			Debug.LogError("Server error: " + conn.error);
			yield break;
		}
		
		JSonReader reader = new JSonReader();
		IJSonObject data = reader.ReadAsJSonObject(conn.text);
		
		if (data == null || data.Contains("error"))
		{
			Debug.LogError("Json error: " + conn.text);
			yield break;
		}
		
		GameToken.save(data);
		
		// Verifica se houve erro
		if (data.Contains("fb_error_reason") && data["fb_error_reason"].ToString() == "user_denied")
		{
			// Up Top Fix Me
			//GameGUI.game_native.showMessage("Error", "You need to authorize our app on Facebook.");
			
			// Redireciona para o login caso necessario
			// Up Top Fix Me
			//if (Scene.GetCurrent() != GameGUI.components.login_scene)
				//Scene.Login.Load(Info.firstScene);
			
			yield break;
		}
		
		// Salva o token do Facebook
		Save.Set(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString(), data["fbtoken"].ToString(), true);		
		
		// Atualiza token da FacebookAPI
		FacebookAPI facebook = new FacebookAPI();
		facebook.UpdateToken();
		if (callback != null) callback(state);
	}
コード例 #32
0
    // Funcao para pegar a foto do usuario
    // Retorna foto como Texture
	public IEnumerator GetPicture(string _facebookId, FacebookAPI.Picture type, FacebookAPI.GetPictureCallback callback, int tries = 0)
	{
        // Se ja estiver cacheada as informacoes, somente enviar para o callback
		if (users.ContainsKey(_facebookId) && users[_facebookId].picture != null)
        {
            // Cacheia todos os tamanhos de fotos possiveis (square, small, etc) e retorna pro callback somente
            // se tiver cacheado o tamanho de foto correto solicitado
			if (type == FacebookAPI.Picture.Square && users[_facebookId].picture.square != null)
			{
                if (callback != null)
                    callback(null, _facebookId, users[_facebookId].picture.square);
                yield break;
            }
			else if (type == FacebookAPI.Picture.Large && users[_facebookId].picture.large != null)
			{
                if (callback != null)
                    callback(null, _facebookId, users[_facebookId].picture.large);
                yield break;
            }
			else if (type == FacebookAPI.Picture.Small && users[_facebookId].picture.small != null)
			{
                if (callback != null)
                    callback(null, _facebookId, users[_facebookId].picture.small);
                yield break;
            }
			else if (type == FacebookAPI.Picture.Medium && users[_facebookId].picture.medium != null)
			{
                if (callback != null)
                    callback(null, _facebookId, users[_facebookId].picture.medium);
                yield break;
            }
		}

        // Caso contrario, fazer uma conexão ao facebook para pegar as informacoes
        // Cria URL do request
		string url = GRAPH_URL + _facebookId + "/picture/?";
		if (_facebookId == "me")
			url += "access_token=" + WWW.EscapeURL(facebookToken) + "&";
		url += "type=" + type.ToString().ToLower();
		WWW getPicture = new WWW(url);
		yield return getPicture;

        // Se houver algum erro, enviar erro para o callback
		if (getPicture.error != null)
        {
			if (callback != null) 
				callback(getPicture.error, _facebookId, null);
		}

        // Caso contrario, validar foto recebida
        else
        {
            // Checa se a foto não esta no formato de GIF (formato não suportado pela Unity3D)
			if (getPicture.text.StartsWith("GIF"))
            {
				if (callback != null)
					callback("User images are GIF format!", _facebookId, null);
				yield break;
            }

            // Cacheia as informacoes recebidas
			Texture picture = getPicture.texture;
			FacebookAPI.User user = (users.ContainsKey(_facebookId)) ? users[_facebookId] : new FacebookAPI.User();
			if (user.picture == null)
                user.picture = new FacebookAPI.User.Picture();
			if (type == FacebookAPI.Picture.Square)
				user.picture.square = picture;
			else if (type == FacebookAPI.Picture.Large)
				user.picture.large = picture;
			else if (type == FacebookAPI.Picture.Small)
				user.picture.small = picture;
			else user.picture.medium = picture;

            // Envia pro callback
			if (callback != null) 
				callback(null, _facebookId, picture);
		}
		yield break;
	}
コード例 #33
0
		public GenerateState(string facebookId, Dictionary<string, string> parameters, FacebookAPI.WallPostCallback callback, int tries = 0)
		{ stateType = StateType.WallPost; globalFacebookId = facebookId; wallParameters = parameters; wallPostCallback = callback;  this.tries = tries; }
コード例 #34
0
ファイル: Login.cs プロジェクト: uptopgames/baseproject
	// Processa o resultado da conexao de login
	private void connectionResult(string error, WWW data)
	{
		//Debug.Log("resultado chegou");
		JSonReader reader = new JSonReader();
		IJSonObject json = null;
		
		//Debug.Log("data: "+data.text);
		
		// Tenta ler o retorno
		if (data == null) error = "json_error";
		else
		{
			try
			{
				if (error == null) json = reader.ReadAsJSonObject(data.text);
			}
			catch (JSonReaderException)
			{
				error = "json_error";
			}
		}
		
		// Verifica se houve erro
		if (error == null && json.Contains("error")) error = json["error"].ToString();
		
		Flow.game_native.stopLoading();
		
		// Trata o erro
		if (error != null)
		{
			switch (error)
			{
				case "empty_email": error = "Please inform an e-mail."; break;
				case "invalid_email": error = "Invalid e-mail. Please try another account."; break;
				default: error = GameJsonAuthConnection.DEFAULT_ERROR_MESSAGE; break;
			}
			Flow.game_native.showMessage("Error", error);
			
			return;
		}
		
		if (json.Contains("ask") && json["ask"].ToString() == "password")
		{			
			passwordDialog.SetActive(true);
			UIManager.instance.FocusObject = passwordField;
			
			return;
		}
		
		Debug.Log(json);
		
		GameToken.save(json);
		Save.Set(PlayerPrefsKeys.EMAIL.ToString(), email,true);
		Save.Set(PlayerPrefsKeys.PASSWORD.ToString(), password, true);
		
		Save.Set(PlayerPrefsKeys.NAME.ToString(), json["username"].ToString(),true);
		Save.Set(PlayerPrefsKeys.ID.ToString(), json["user_id"].ToString(),true);
		
		if(!json["first_name"].IsNull) Save.Set(PlayerPrefsKeys.FIRST_NAME.ToString(), json["first_name"].ToString(), true);
		if(!json["last_name"].IsNull) Save.Set(PlayerPrefsKeys.LAST_NAME.ToString(), json["last_name"].ToString(), true);
		if(!json["location"].IsNull) Save.Set(PlayerPrefsKeys.LOCATION.ToString(), json["location"].ToString(), true);
		if(!json["gender"].IsNull) Save.Set(PlayerPrefsKeys.GENDER.ToString(), json["gender"].ToString(), true);
		if(!json["birthday"].IsNull)
		{
			string day, month, year;
			string[] separator = {"-"};
			string[] birthday = json["birthday"].StringValue.Split(separator,System.StringSplitOptions.None);
			
			day = birthday[2];
			month = birthday[1];
			year = birthday[0];
			
			Save.Set(PlayerPrefsKeys.DATE_DAY.ToString(), day,true);
			Save.Set(PlayerPrefsKeys.DATE_MONTH.ToString(), month,true);
			Save.Set(PlayerPrefsKeys.DATE_YEAR.ToString(), year,true);
		}
		
		
		
		// Verifica se possui Facebook
		if (json.Contains("fbtoken") && json.Contains("facebook_id"))
		{
			Save.Set(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString(), json["fbtoken"].ToString(), true);
			Save.Set(PlayerPrefsKeys.FACEBOOK_ID.ToString(), json["facebook_id"].ToString(), true);
		}
		
		// Atualiza token da FacebookAPI
		if (Save.HasKey(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString())) 
		{
			FacebookAPI facebook = new FacebookAPI();
			facebook.SetToken(Save.GetString(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString()));
		}
		
		ConfigManager.offlineUpdater.UpdateOfflineItems();
		
		// Verifica se e uma conta nova
		if (json["new_account"].ToString() != "0")
		{						
			//messageOkDialog.transform.FindChild("ConfirmButtonPanel").FindChild("ConfirmButton").GetComponent<UIButton>().methodToInvoke = "BringInInvite";
			Flow.game_native.showMessage("Hello!", "Hi! You've registered with us! We've emailed you your password.");
			return;
		}
		
		
		
		
		
		// Redireciona a proxima cena
		
		panelManager.BringIn("MultiplayerScenePanel");
	}
コード例 #35
0
ファイル: Main.cs プロジェクト: damienjoldersma/DreamSpell
    private void handleFacebookUser(string sessionKey, string userId )
    {
        log.Debug("Handling facebook user",userId);

            facebookApi = new FacebookAPI();

            facebookApi.IsDesktopApplication = false;
            facebookApi.ApplicationKey = apikey;
            facebookApi.Secret = apisecret;

            facebookApi.SessionKey = sessionKey;
            facebookApi.UserId = userId;

            facebookApi.ConnectToFacebook();

            FacebookId = facebookApi.GetLoggedInUser();
            Collection<Facebook.Entity.User> fb_users = facebookApi.GetUserInfo(facebook_id);
            log.Debug("Got Facebook users fb_users",fb_users);
            fb_user = fb_users[0];
            log.Debug("Facebook user fb_user",fb_user);

            IRecordList<DreamFolk> dreamFolk = DataProvider.LoadList<DreamFolk>(new FilterInfo("FacebookId",FacebookId));
            log.Debug("Got dreamFolk folk with FacebookId",FacebookId,dreamFolk);

            DreamFolk dreamPerson = null;
            if ( dreamFolk.Count > 0 ) dreamPerson = dreamFolk[0];

            if ( dreamPerson == null )
            {
                log.Warn("Creating new dreamPerson from Main.Current");
                dreamPerson = new DreamFolk(Main.Current.FbUser);
                dreamPerson.Save(true);
            }
            /*
            else if ( dreamPerson.Birthday != Main.Current.FbUser.Birthday )
            {
                log.Warn("Updating birthday dreamPerson from Main.Current");
                dreamPerson.Birthday = (DateTime)Main.Current.FbUser.Birthday;
                dreamPerson.Save(true);
            }
            else if ( !dreamPerson.Updated )
            */
            else
            {
                log.Warn("Updating dreamPerson");
                dreamPerson.update(fb_user);
                dreamPerson.Updated = true;
                dreamPerson.Save(true);
            }

            CurrentDreamFriend = dreamPerson;
            Now.Friends = CurrentDreamFriend.Friends;
    }
コード例 #36
0
	public IEnumerator OpenInvite(FacebookAPI.InviteCallback callback, int tries = 0)
	{
			string url = DIALOG_URL + "apprequests?";
			url += "app_id=" + facebookId + "&";
			url += "message=" + WWW.EscapeURL("Invite your friends and got coins!") + "&";
			url += "title=" + WWW.EscapeURL("Sea Combat") + "&";
			url += "redirect_uri=" + WWW.EscapeURL(Flow.URL_BASE +
						"login/facebook/invite.php?" +
							"token=" + PlayerPrefs.GetString("token") + "&" +
							"device=" + SystemInfo.deviceUniqueIdentifier.Replace("-", "") + "&" +
							"close=" + (Info.IsPlatform(Info.Platform.Android) ? "1" : "0")
			);
		
			// Up Top Fix Me (dialog)		
			//GameGUI.game_native.openUrlInline(url);
			Flow.game_native.openUrlInline(url);

            // Como nao tem como receber o callback do navegador do Prime31
            // enviar callback de sucesso (mesmo se o usuario nao estiver postado)
			if (callback != null)
				callback(null);
		
		yield break;
	}
コード例 #37
0
        // Constructor para cada tipo de funcao (GetInfo, GetPicture, WallPost, etc..)
		public GenerateState(string facebookId, FacebookAPI.GetInfoCallback callback, int tries = 0)
		{ stateType = StateType.GetInfo; globalFacebookId = facebookId; getInfoCallback = callback; this.tries = tries; }
コード例 #38
0
	// Funcao para pegar informacoes do usuario
    // Retorna FacebookId, Nome, Sobrenome, e Login
	public IEnumerator GetInfo(string _facebookId, FacebookAPI.GetInfoCallback callback, int tries = 0)
	{
        // Se ja estiver cacheada as informacoes, somente enviar para o callback
		if (users.ContainsKey(_facebookId) && users[_facebookId].firstName != null)
        {
			if (callback != null)
				callback(null, _facebookId, users[_facebookId].firstName, users[_facebookId].lastName, users[_facebookId].userName);
			yield break;
		}
        // Caso contrario, fazer uma conexão ao facebook para pegar as informacoes
        else
        {
            // Cria URL do request
			string url = GRAPH_URL + _facebookId + "/?";
			if (_facebookId == "me")
				url += "access_token=" + WWW.EscapeURL(facebookToken) + "&";
			url += "fields=username,first_name,last_name";
			WWW getInfo = new WWW(url);
			yield return getInfo;

            // Se houver algum erro, enviar erro para o callback
			if (getInfo.error != null)
            {
				if (callback != null) 
					callback(getInfo.error, _facebookId, null, null, null);
			}

            // Caso contrario, decodar JSON recebido
            else
            {
				IJSonObject data = getInfo.text.ToJSon();
				
				// Se o JSON recebido for invalido, retornar e enviar para o callback
				if (data.IsEmpty() || data.IsError())
				{
					if (callback != null) 
						callback("Invalid JSon: " + getInfo.text, _facebookId, null, null, null);
					
					yield break;
				}
				
                // Cacheia as informacoes recebidas
				FacebookAPI.User user = (users.ContainsKey(_facebookId)) ?
                    users[_facebookId] : new FacebookAPI.User();
				user.facebookId = _facebookId;
				user.firstName = data.GetString("first_name");
				user.lastName = data.GetString("last_name");
				user.userName = data.GetString("username");

                // Envia pro callback
				if (callback != null) 
					callback(null, _facebookId, user.firstName, user.lastName, user.userName);
			}
		}
		yield break;
	}
コード例 #39
0
		public GenerateState(FacebookAPI.InviteCallback callback, int tries = 0)
		{ stateType = StateType.OpenInvite; inviteCallback = callback;  this.tries = tries; }
コード例 #40
0
		public GenerateState(string _pageId, FacebookAPI.IsLikedPageCallback callback, int tries = 0)
		{ stateType = StateType.IsLikedPage; pageId = _pageId; isLikedPageCallback = callback;  this.tries = tries; }
コード例 #41
0
		public GenerateState(string facebookId, int score, FacebookAPI.SetScoreCallback callback, int tries = 0)
		{ stateType = StateType.SetScore; globalFacebookId = facebookId; setScore = score; setScoreCallback = callback;  this.tries = tries; }
コード例 #42
0
ファイル: AccountController.cs プロジェクト: msanj1/BOTF
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {

                        // Insert name into the profile table
                       UserProfile profile = db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
                       //need to check to see if it is facebook or twitter
                        if (provider == "twitter")
                        {

                            if (Session["AccessToken"] != null && Session["AccessTokenSecret"] != null) //used to distinugish between facebook and twitter regisration
                            {
                                //"9kCMAgidv1NzN8TfMVgZw", "RimlGsenvejdoRlw0NSazYzXJBO6olF2IBMJcw11Uc"
                                //creating new tweetsharp service
                                TwitterService service = new TwitterService(Settings.Settings.TwitterConsumerKey, Settings.Settings.TwitterConsumerSecret, Session["AccessToken"].ToString(), Session["AccessTokenSecret"].ToString());
                                TwitterUser me = service.VerifyCredentials();
                                ContextDb _db = new ContextDb();
                                Models.User temp = new Models.User { UserId = profile.UserId, Email = model.Email, Image = me.ProfileImageUrl, Name =me.Name, RemainingProposals = 1, RemainingVotes = 3 };
                                temp = _db.User.Add(temp);
                                _db.SaveChanges();
                                CheckChanceState(temp.UserId);
                                DatabaseCallsApi _api = new DatabaseCallsApi();
                                _api.AddOrUpdateService(temp.UserId, "twitter", Session["AccessToken"].ToString(), Session["AccessTokenSecret"].ToString());
                                Session.Remove("AccessToken");
                                Session.Remove("AccessTokenSecret");
                            }

                        }
                        else
                        {
                            //setting new facebook service
                            FacebookAPI facebook = new FacebookAPI(FacebookToken);
                            dynamic facebookData = facebook.GetUsersData();
                            if (facebookData != null)
                            {

                                ContextDb _db = new ContextDb();

                                Models.User temp = new Models.User { UserId = profile.UserId, Email = facebookData.email.ToString(), Image = facebookData.picture["data"]["url"].ToString(), Name = facebookData.name.ToString(), RemainingProposals = 1, RemainingVotes = 3 };
                                temp = _db.User.Add(temp);
                                _db.SaveChanges();
                                CheckChanceState(temp.UserId);
                                DatabaseCallsApi _api = new DatabaseCallsApi();
                                _api.AddOrUpdateService(temp.UserId, Provider, FacebookToken);

                            }
                        }

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
コード例 #43
0
    // Funcao para setar score ao usuario
	public IEnumerator SetScore(string _facebookId, int score, FacebookAPI.SetScoreCallback callback, int tries = 0)
	{
        // Cria URL do request
		string url = GRAPH_URL + _facebookId + "/scores?";
		url += "score=" + score.ToString() + "&";
		url += "access_token=";
		url += ((_facebookId == "me") ? WWW.EscapeURL(facebookToken) :
			WWW.EscapeURL(facebookId + "|" + facebookSecret)) + "&";
		url += "method=post";
		WWW _score = new WWW(url);
		yield return _score;

        // Se houver algum erro, enviar erro para o callback
		if (_score.error != null)
        {
			if (callback != null)
				callback(_score.error, _facebookId, score);
			yield break;
		}

        // Caso contrario, validar conexão
        else
        {
			if (callback != null)
            {
                // Se realmente estiver setado o score, enviar para o callback
				if (_score.text == "true")
					callback(null, _facebookId, score);

                // Caso contrario, enviar erro para o callback
				else callback("Failed to post score.", _facebookId, score);
			}
		}
		yield break;		
	}
コード例 #44
0
ファイル: Login.cs プロジェクト: uptopgames/baseproject
	// Obtem as informacoes do Facebook no servidor
	private IEnumerator getFacebookInfo()
	{
		Debug.Log("pegando info face");
		// Numero maximo de tentativas
		int max_attempts = 5;
		
		WWW conn = null;
		
		WWWForm form = new WWWForm();
		form.AddField("device", SystemInfo.deviceUniqueIdentifier.Replace("-", ""));
		form.AddField("authentication", authentication);
		
		while (max_attempts > 0)
		{
			conn = new WWW(Flow.URL_BASE + "login/facebook/fbinfo.php", form);
			yield return conn;
			
			if (conn.error != null || conn.text != "") break;
			
			max_attempts--;
			
			yield return new WaitForSeconds(1);
		}
		
		Flow.game_native.stopLoading();
		
		if (max_attempts == 0 || conn.error != null)
		{
			Debug.LogError("Server error: " + conn.error);
			Flow.game_native.showMessage("Error", GameJsonAuthConnection.DEFAULT_ERROR_MESSAGE);
			
			yield break;
		}
		
		JSonReader reader = new JSonReader();
		IJSonObject data = reader.ReadAsJSonObject(conn.text);
		
		if (data == null || data.Contains("error"))
		{
			Debug.LogError("Json error: " + conn.text);
			Flow.game_native.showMessage("Error", GameJsonAuthConnection.DEFAULT_ERROR_MESSAGE);
			
			yield break;
		}
		
		Debug.Log("data: " + data);
		
		GameToken.save(data);
		Save.Set(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString(), data["fbtoken"].ToString(), true);
		Save.Set(PlayerPrefsKeys.NAME.ToString(), data["username"].ToString(),true);
		Save.Set(PlayerPrefsKeys.ID.ToString(), data["user_id"].ToString(),true);
		if(!data["email"].IsNull) Save.Set(PlayerPrefsKeys.EMAIL.ToString(), data["email"].ToString(), true);
		if(!data["first_name"].IsNull) Save.Set(PlayerPrefsKeys.FIRST_NAME.ToString(), data["first_name"].ToString(), true);
		if(!data["last_name"].IsNull) Save.Set(PlayerPrefsKeys.LAST_NAME.ToString(), data["last_name"].ToString(), true);
		if(!data["location"].IsNull) Save.Set(PlayerPrefsKeys.LOCATION.ToString(), data["location"].ToString(), true);
		if(!data["gender"].IsNull) Save.Set(PlayerPrefsKeys.GENDER.ToString(), data["gender"].ToString(), true);
		
		if(!data["birthday"].IsNull)
		{
			string day, month, year;
			string[] separator = {"-"};
			string[] birthday = data["birthday"].StringValue.Split(separator,System.StringSplitOptions.None);
			
			day = birthday[2];
			month = birthday[1];
			year = birthday[0];
			
			Save.Set(PlayerPrefsKeys.DATE_DAY.ToString(), day,true);
			Save.Set(PlayerPrefsKeys.DATE_MONTH.ToString(), month,true);
			Save.Set(PlayerPrefsKeys.DATE_YEAR.ToString(), year,true);
		}
		
		// Atualiza token da FacebookAPI
		if (Save.HasKey(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString())) {
			FacebookAPI facebook = new FacebookAPI();
			facebook.SetToken(Save.GetString(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString()));
		}
		
		Save.SaveAll();
		
		ConfigManager.offlineUpdater.UpdateOfflineItems();
		
		CheckLogin();
	}
コード例 #45
0
    // Funcao para fazer uma postagem no mural do usuario/amigo
    // Retorna ID do post se nao for feito por dialogo
	public IEnumerator WallPost(string _facebookId, Dictionary<string, string> parameters, FacebookAPI.WallPostCallback callback, int tries = 0)
	{
        // Cria URL do request
		bool isDialog = (parameters != null && parameters.ContainsKey("dialog")) ? true : false;
		string url = (isDialog) ? DIALOG_URL : GRAPH_URL;
		if (!isDialog) url += _facebookId + "/";
		url += "feed/?";
		
        // Se for dialogo, adiciona redirecionamento para php aonde fecha o browser nativo do Prime31
        // e informacoes extras para fazer o post
		if (isDialog)
        {
			url += "app_id=" + facebookId + "&";
			url += "redirect_uri=" + WWW.EscapeURL(Flow.URL_BASE + "login/tables/input_share.php?" +
				//"app_id=" + Info.appId + "&token=" + WWW.EscapeURL(Save.GetString(PlayerPrefsKeys.TOKEN.ToString())) +"&device=" + GameInfo.device()) + "&";
				"app_id=" + Info.appId + "&token=" + WWW.EscapeURL(Save.GetString(PlayerPrefsKeys.TOKEN.ToString())) +"&device=" + SystemInfo.deviceUniqueIdentifier.Replace("-", "")) + "&";
			if (_facebookId != "me")
                url += "to=" + WWW.EscapeURL(_facebookId) + "&";
		}
        else url += "method=post&";
		
        // Checa se os parametros enviados nao sao nulos e adiciona no form
		if (parameters != null)
        {
			if (parameters.ContainsKey("message"))
				url += "message=" + WWW.EscapeURL(parameters["message"]) + "&";
			if (parameters.ContainsKey("name"))
				url += "name=" + WWW.EscapeURL(parameters["name"]) + "&";
			if (parameters.ContainsKey("link"))
				url += "link=" + WWW.EscapeURL(parameters["link"]) + "&";
			if (parameters.ContainsKey("description"))
				url += "description=" + WWW.EscapeURL(parameters["description"]) + "&";
			if (parameters.ContainsKey("picture"))
				url += "picture=" + WWW.EscapeURL(parameters["picture"]) + "&";
		}

        // Se for nulo, enviar erro para o callback
        else
        {
			if (callback != null)
				callback(NULL_PARAMETERS, facebookId, parameters, null);
			Debug.LogWarning(NULL_PARAMETERS);
			yield break;
		}

        // Access token do usuario
		url += "access_token=" + WWW.EscapeURL(facebookToken);
		
        // Se nao for dialogo, fazer o post
		if (!isDialog)
        {
			WWW wallPost = new WWW(url);
			yield return wallPost;

            // Se houver algum erro, enviar erro para o callback
			if (wallPost.error != null)
            {
                // Envia para o callback
				if (callback != null)
					callback(wallPost.error, _facebookId, parameters, null);

                // Cacheia a conexão atual para tentar novamente apos o "giro"
				Login(
                    new GenerateState(_facebookId, parameters, callback)
                    , HandleState
                );
				yield break;
			}

            // Caso contrario, decodar JSON recebido
            else
            {
				IJSonObject data = wallPost.text.ToJSon();
				
				// Se o JSON recebido for invalido, retornar e enviar para o callback
				if (data.IsEmpty() || data.IsError())
				{
					if (callback != null) 
						callback("Invalid JSon: " + wallPost.text, _facebookId, parameters, null);
					
					yield break;
				}
				
                // Envia ID do post para o callback
				if (callback != null)
					callback(null, _facebookId, parameters, data.GetString("id"));
			}
		}

        // Se for dialogo, abrir a url no navegador do Prime31
        else
        {
			// Up Top Fix me (dialog)
			//GameGUI.game_native.openUrlInline(url);
			Flow.game_native.openUrlInline(url);
			
			
			tempFace = _facebookId;
			tempParams = parameters;
			tempCallback = callback;
			
			if(_facebookId == "me") 
			{
				new GameJsonAuthConnection(Flow.URL_BASE+"login/tables/check_share.php",GetShareData).connect();
			}
			else
			{
				if (callback != null) callback(null, _facebookId, parameters, null);
			}
            // Como nao tem como receber o callback do navegador do Prime31
            // enviar callback de sucesso (mesmo se o usuario nao estiver postado)
			
		}
		yield break;
	}
コード例 #46
0
    // Funcao para checar se o usuario curtiu alguma pagina
	public IEnumerator IsLikedPage(string pageId, FacebookAPI.IsLikedPageCallback callback, int tries = 0)
	{
        // Cria URL do request
		string url = GRAPH_URL + "me/likes/" + pageId + "/?";
		url += "access_token=" + facebookToken;
		WWW like = new WWW(url);
		yield return like;

        // Se houver algum erro, enviar erro para o callback
		if (like.error != null)
        {
			if (callback != null)
				callback(like.error, false, pageId);
			yield break;
		}

        // Caso contrario, decodar JSON recebido e validar conexão
        else
        {
			IJSonObject data = like.text.ToJSon();
			
			// Se o JSON recebido for invalido, retornar e enviar para o callback
			if (data.IsEmpty() || data.IsError())
			{
				if (callback != null) 
					callback("Invalid JSon: " + like.text, false, pageId);
				
				yield break;
			}
			
            // Valida conexão e envia para o callback
			if (callback != null)
                callback(null,
					(
						data.Contains("data") &&
						data["data"].Count > 0 &&
						data["data"][0].GetString("id") == pageId
					),
				pageId);
		}
		yield break;
	}
コード例 #47
0
		public GenerateState(string facebookId, FacebookAPI.Picture type, FacebookAPI.GetPictureCallback callback, int tries = 0)
		{ stateType = StateType.GetPicture; globalFacebookId = facebookId; getPictureType = type; getPictureCallback = callback;  this.tries = tries; }