Exemple #1
0
        public IActionResult ReconnectFbAccount(string accessToken, long groupId, long userId, string reconnect, string profileId)
        {
            dynamic profile = FbUser.getFbUser(accessToken);


            try
            {
                string x = Convert.ToString(profile);
                _logger.LogError(x);
            }
            catch { }
            if (Convert.ToString(profile) == "Invalid Access Token")
            {
                return(Ok("Invalid Access Token"));
            }
            DatabaseRepository dbr = new DatabaseRepository(_logger, _env);

            Domain.Socioboard.Models.Facebookaccounts fbacc  = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(Convert.ToString(profile["id"]), _redisCache, dbr);
            Domain.Socioboard.Models.Facebookaccounts fbaccw = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(profileId, _redisCache, dbr);
            //fbacc = fbacc.Where(t => t.FbUserId.Contains("127471161024815")).ToList();

            try
            {
                if (fbacc.FbUserId == profileId)
                {
                    if (fbacc != null && fbacc.IsActive == true)
                    {
                        if (fbacc.UserId == userId)
                        {
                            Groups ngrp = dbr.Find <Domain.Socioboard.Models.Groups>(t => t.adminId == userId && t.id == groupId).FirstOrDefault();
                            if (ngrp == null)
                            {
                                return(Ok("Wrong Group Id"));
                            }
                            int res = Api.Socioboard.Repositories.FacebookRepository.ReFacebookAccount(profile, FbUser.getFbFriends(accessToken), dbr, userId, ngrp.id, Domain.Socioboard.Enum.FbProfileType.FacebookProfile, accessToken, reconnect, _redisCache, _appSettings, _logger);
                            if (res == 1)
                            {
                                return(Ok("Facebook account Reconnect Successfully"));
                            }
                            else
                            {
                                return(Ok("Error while Reconnecting Account"));
                            }
                        }
                    }
                }
                else
                {
                    return(Ok("Oops! login information is wrong , login the profile which has to be reconnected"));
                }
            }
            catch (Exception ex)
            {
                return(Ok("Oops! login information is wrong , login the profile which has to be reconnected"));
            }



            return(Ok());
        }
        /// <summary>
        /// Find a near event from a certain point on the map.
        /// </summary>
        /// <param name="latitude"></param>
        /// <param name="longitude"></param>
        /// <param name="radius"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task <List <Event> > findNearEventFromAPoint(double latitude, double longitude, int radius, DateTime startTime, DateTime endTime, HttpContext httpContext)
        {
            //get fbId from header of request
            String fbId = utilService.getFbIdFromHttpContext(httpContext);

            List <Event> nearEvents = await eventRepo.getFullEventListByPointInRadius(latitude, longitude, radius, startTime, endTime);

            FbUser fbUser = null;

            //Only for fb-Users
            //fill friends who attend the event
            if (fbId != null)
            {
                fbUser = await fbUserRepo.GetByFbIdAsync(fbId);
            }
            for (int i = 0; i < nearEvents.Count; i++)
            {
                if (fbUser != null)
                {
                    nearEvents[i] = await getEventAttendingFriends(fbUser, nearEvents[i]);
                }
                nearEvents[i].attending = null;
            }
            return(nearEvents);
        }
Exemple #3
0
        public static FbUser recuperarContacto(string fbUserId)
        {
            RequestService servicio = new RequestService();
            FbUser         usuario  = servicio.LlamarGet <FbUser>("https://graph.facebook.com/v3.0/" + fbUserId + "?fields=id,first_name,last_name,profile_pic,gender,locale,timezone&access_token=EAAF3NCI0yUQBAMx3ZCirrlZCuYDNoLaD092M4ncaZAYmu03C5Rku5tCPFLZBqmh2LEjD03u6fZAw3NtLhJLO7WEiJuHZCOFSmbEiZAR1DsiZAZBEWdQ9qizdz0HDJCQeH1wZBhG4HVxKddyTtyKxaMBSZCnoXeSCJY4AARmf6C1wmyIOAZDZD");

            return(usuario);
        }
Exemple #4
0
    public IList <FbUser> findFbUsers(string username)
    {
        IList <FbUser> list = new List <FbUser>();
        string         sql  = String.Format("select * from FbUser where username like '{0}'", "%" + username + "%");
        DataTable      dt   = SqlHelper.ExecuteQuery(sql);

        if (dt != null)
        {
            FbUser fbUser = null;
            foreach (DataRow row in dt.Rows)
            {
                fbUser          = new FbUser();
                fbUser.ID       = (Guid)row["id"];
                fbUser.Username = row["username"].ToString();
                fbUser.Password = row["password"].ToString();
                fbUser.Realname = row["realname"].ToString();
                fbUser.Email    = row["email"].ToString();
                fbUser.Phone    = row["phone"].ToString();
                fbUser.Address  = row["address"].ToString();
                fbUser.Zipcode  = row["zipcode"].ToString();
                fbUser.Role     = Int32.Parse(row["role"].ToString());
                list.Add(fbUser);
            }
        }
        return(list);
    }
Exemple #5
0
 /// <summary>
 /// create initial playlist rating
 /// </summary>
 ///
 /// <param name="playlist">
 /// rating to attach this rating to
 /// </param>
 ///
 /// <param name="song">
 /// song being rated
 /// </param>
 ///
 /// <param name="creator">
 /// initial creator of the rating
 /// </param>
 public PlaylistSongRating(Playlist playlist, Song song, FbUser creator)
     : this()
 {
     Song = song;
     Playlist = playlist;
     Creator = creator;
 }
Exemple #6
0
        public async Task <PendingAddFacebookPagesDto> GetPendingAddPagesAsync(string code, string redirectUri)
        {
            string userToken = _fbClient.GetUserToken(code, redirectUri);
            FbUser me        = await _fbClient.GetMe(userToken);

            IList <FbPage> pages = await _fbClient.GetPages(userToken);

            List <string> pageIds          = pages.Select(t => t.Id).ToList();
            var           facebookAccounts = _socialAccountService.FindAll()
                                             .Where(t => t.SocialUser.Type == SocialUserType.IntegrationAccount &&
                                                    t.SocialUser.Source == SocialUserSource.Facebook && pageIds.Contains(t.SocialUser.OriginalId))
                                             .ToList();

            var result = new PendingAddFacebookPagesDto
            {
                SignInAs = new FacebookSignInAsDto
                {
                    Name   = me.name,
                    Avatar = me.pic
                },
                Pages = pages.Select(t => new PendingAddFacebookPageDto
                {
                    FacebookId  = t.Id,
                    Name        = t.Name,
                    Category    = t.Category,
                    Avatar      = t.Avatar,
                    AccessToken = t.AccessToken,
                    Link        = t.Link,
                    IsAdded     = facebookAccounts.Any(m => m.SocialUser.OriginalId == t.Id)
                }).ToList()
            };

            return(result);
        }
        /// <summary>
        /// Compare FbUser friends with people attending the event to find out if friends of the FbUser attend at the event
        /// </summary>
        /// <param name="fbUser">Facebook User who have done the request</param>
        /// <param name="currentEvent">the requestet event</param>
        /// <returns>updated event with the friends attending at the event</returns>
        public async Task <Event> getEventAttendingFriends(FbUser fbUser, Event currentEvent)
        {
            List <FbUser> eventAttendingFriends = new List <FbUser>();
            List <Rsvp>   eventAttendingPeople  = currentEvent.attending;

            List <Datum> fbUserFriends;

            try
            {
                fbUserFriends = fbUser.friends.data;
            }
            catch (NullReferenceException) //fbUser doesnt have friends or the thing is empty otherwise //TODO
            {
                return(currentEvent);
            }

            if (eventAttendingPeople == null)
            {
                return(currentEvent);
            }
            for (int i = 0; i < fbUserFriends.Count; i++)
            {
                for (int j = 0; j < eventAttendingPeople.Count; j++)
                {
                    if (fbUserFriends.ElementAt(i).id == eventAttendingPeople.ElementAt(j).id)
                    {
                        eventAttendingFriends.Add(await fbUserRepo.GetByFbIdAsync(fbUserFriends.ElementAt(i).id));
                    }
                }
            }
            //store the who attend the event to event
            currentEvent.attendingFriends = eventAttendingFriends;
            return(currentEvent);
        }
Exemple #8
0
 public RatingDetails(FbUser votingUser, short rating)
     : this()
 {
     VotingUser = votingUser;
     Rating = rating;
     OnSaving +=new RepositoryTransactionCompletin(RatingDetails_OnSaving);
 }
 /// <summary>
 ///     SaveFBData to out database.
 /// </summary>
 /// <param name="fbuser"></param>
 /// <returns>FbUser</returns>
 public async Task <FbUser> saveFbData(FbUser fbUser)
 {
     if (await facebookVerifier.authorizeRequest(fbUser.shortAccessToken, fbUser.fbId))
     {
         await fbUserRepo.InsertAsync(fbUser);
     }
     return(fbUser);
 }
 private void AssertDtoEqualToEntity(FbUser entity, UserInfoDto dto)
 {
     Assert.NotNull(dto);
     Assert.Equal(entity.name, dto.Name);
     Assert.Equal(entity.email, dto.Email);
     Assert.Equal(entity.link, dto.Link);
     Assert.Equal(entity.id, dto.OriginalId);
     Assert.Equal(entity.pic, dto.Avatar);
 }
Exemple #11
0
        public static string ComposeMessage(Domain.Socioboard.Enum.FbProfileType profiletype, string accessToken, string fbUserId, string message, string profileId, long userId, string imagePath, string link, Domain.Socioboard.Models.ScheduledMessage schmessage)
        {
            string             ret = "";
            DatabaseRepository dbr = new DatabaseRepository();
            FacebookClient     fb  = new FacebookClient();

            fb.AccessToken = accessToken;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
            var args = new Dictionary <string, object>();

            if (!string.IsNullOrEmpty(message))
            {
                args["message"] = message;
            }
            if (profiletype == Domain.Socioboard.Enum.FbProfileType.FacebookProfile)
            {
                args["privacy"] = FbUser.SetPrivacy("Public", fb, profileId);
            }
            try
            {
                if (!string.IsNullOrEmpty(imagePath))
                {
                    Uri    u         = new Uri(imagePath);
                    string filename  = string.Empty;
                    string extension = string.Empty;
                    extension = System.IO.Path.GetExtension(u.AbsolutePath).Replace(".", "");
                    var media = new FacebookMediaObject
                    {
                        FileName    = "filename",
                        ContentType = "image/" + extension
                    };
                    var    webClient = new WebClient();
                    byte[] img       = webClient.DownloadData(imagePath);
                    media.SetValue(img);
                    args["source"] = media;
                    ret            = fb.Post("v2.1/" + fbUserId + "/photos", args).ToString();
                }
                else
                {
                    if (!string.IsNullOrEmpty(link))
                    {
                        args["link"] = link;
                    }
                    ret = fb.Post("v2.1/" + fbUserId + "/feed", args).ToString();
                }

                schmessage.status = Domain.Socioboard.Enum.ScheduleStatus.Compleated;
                schmessage.url    = ret;
                dbr.Update <ScheduledMessage>(schmessage);
            }
            catch (Exception ex)
            {
                apiHitsCount = MaxapiHitsCount;
            }
            return(ret);
        }
Exemple #12
0
 protected void LoginButton_Click(object sender, EventArgs e)
 {
     if (TxtUserName.Text == "cho" && TxtUserPwd.Text == "1234")
     {
         FbUser user = new FbUser();
         user.Realname   = "cho";
         Session["user"] = user;
         Response.Redirect("Default.aspx");
     }
 }
    void SetUserInfoUI(FbUser user)
    {
        m_Connect.GetComponentInChildren <Text>().text = "Sing out";
        m_UserName.text = user.Name;
        m_UserMail.text = user.Email;

        user.GetProfileImage(FbProfileImageSize.Large, (texture) =>
        {
            m_UserAvatar.texture = texture;
        });
    }
    void UpdateAccountUI()
    {
        Fb.GetFriends(10, result =>
        {
            Debug.Log($"friends count: {result.Users.Count}");
        }, null);

        if (Fb.IsLoggedIn)
        {
            if (s_CurrentUser != null)
            {
                SetUserInfoUI(s_CurrentUser);
            }
            else
            {
                Fb.GetLoggedInUserInfo((result) =>
                {
                    if (result.IsSucceeded)
                    {
                        SetUserInfoUI(result.User);

                        Debug.Log("result.User.Id: " + result.User.Id);
                        Debug.Log("result.User.Name: " + result.User.Name);
                        Debug.Log("result.User.FirstName: " + result.User.FirstName);
                        Debug.Log("result.User.LastName: " + result.User.LastName);

                        Debug.Log("result.User.Location: " + result.User.Location);
                        Debug.Log("result.User.PictureUrl: " + result.User.PictureUrl);
                        Debug.Log("result.User.ProfileUrl: " + result.User.ProfileUrl);
                        Debug.Log("result.User.AgeRange: " + result.User.AgeRange);
                        Debug.Log("result.User.Birthday: " + result.User.Birthday);
                        Debug.Log("result.User.Gender: " + result.User.Gender);
                        Debug.Log("result.User.AgeRange: " + result.User.AgeRange);
                        Debug.Log("result.RawResult: " + result.RawResult);

                        s_CurrentUser = result.User;
                    }
                    else
                    {
                        Debug.Log("Failed to load user Info: " + result.Error);
                    }
                });
            }
        }
        else
        {
            m_Connect.GetComponentInChildren <Text>().text = "Sing in";
            m_UserName.text = "Signed out";
            m_UserMail.text = "Signed out";

            m_UserAvatar.texture = null;
        }
    }
Exemple #15
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (Session["user"] != null)
     {
         FbUser user = (FbUser)Session["user"];
         Label1.Text = "Welcome the visit of " + user.Realname;
         MultiView1.ActiveViewIndex = 1;
     }
     else
     {
         MultiView1.ActiveViewIndex = 0;
     }
 }
Exemple #16
0
    public FbUser FindFbUser(string username, string password)
    {
        FbUser        fbUser = null;
        string        sql    = String.Format("select * from FbUser where username='******' and password='******'", username, password);
        SqlDataReader sdr    = SqlHelper.ExecuteReader(sql);

        if (sdr.Read())
        {
            fbUser = new FbUser(sdr.GetGuid(0), sdr.GetString(1), sdr.GetString(2), sdr.GetString(3), sdr.GetString(4), sdr.GetString(5), sdr.GetString(6), sdr.GetString(7), sdr.GetInt32(8));
        }
        sdr.Close();
        return(fbUser);
    }
        /// <summary>
        /// fetches Facebook user from Facebooks Graph API
        /// </summary>
        /// <param name="shortAccessToken">The users access token which is needed to fetch the user from Facebook</param>
        /// <returns>the Facebook user</returns>
        private async Task <FbUser> fetchAndStoreUserDetails(string shortAccessToken)
        {
            String jsonResponse = UtilService.performGetRequest(
                new Uri(
                    "https://graph.facebook.com/v2.3/me?fields=id,email,first_name,last_name,gender,link,updated_time,verified,friends&access_token=" +
                    shortAccessToken));
            FbUser user = JsonConvert.DeserializeObject <FbUser>(jsonResponse);

            user.shortAccessToken = shortAccessToken;
            await fbUserRepo.InsertAsync(user);

            return(user);
        }
Exemple #18
0
    public FbUser FindFbUser(int id)
    {
        FbUser        fbUser = null;
        string        sql    = String.Format("select * from FbUser where id={0}", id);
        SqlDataReader sdr    = SqlHelper.ExecuteReader(sql);

        if (sdr.Read())
        {
            fbUser = new FbUser(sdr.GetGuid(0), sdr.GetString(1), sdr.GetString(2), sdr.GetString(3), sdr.GetString(4), sdr.GetString(5), sdr.GetString(6), sdr.GetString(7), sdr.GetInt32(8));
        }
        sdr.Close();
        return(fbUser);
    }
        private void guesstclick(object sender, TappedRoutedEventArgs e)
        {
            var bitmap = new BitmapImage(new Uri("ms-appx:///Assets/Icons/guestImage.png"));

            var fbuser = new FbUser()
            {
                FbNom = "guest", ProfilePic = bitmap
            };


            SharedInformtionFbUser.sharedUser = fbuser;

            Frame.Navigate(typeof(AccLoved));
        }
        public void saveFbDataTest()
        {
            //Arrange
            AccountService account = new AccountService();
            FbUser         usr     = new FbUser();

            usr.firstName = "Laura";

            //Act
            Task <FbUser> task = account.saveFbData(usr);

            //Assert
            Assert.IsNotNull(task);
        }
        public IActionResult AddFacebookAccount(string accessToken, long groupId, long userId)
        {
            dynamic profile = FbUser.getFbUser(accessToken);

            try
            {
                string x = Convert.ToString(profile);
                _logger.LogError(x);
            }
            catch { }
            if (Convert.ToString(profile) == "Invalid Access Token")
            {
                return(Ok("Invalid Access Token"));
            }
            DatabaseRepository dbr = new DatabaseRepository(_logger, _env);

            Domain.Socioboard.Models.Facebookaccounts     fbacc       = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(Convert.ToString(profile["id"]), _redisCache, dbr);
            List <Domain.Socioboard.Models.Groupprofiles> grpProfiles = Api.Socioboard.Repositories.GroupProfilesRepository.getAllGroupProfiles(groupId, _redisCache, dbr);



            //if (grpProfiles.First().profileId == fbacc.FbUserId)
            if (fbacc != null && fbacc.IsActive == true)
            {
                if (fbacc.UserId == userId)
                {
                    return(Ok("Facebook account already added by you."));
                }
                return(Ok("Facebook account added by other user."));
            }
            else
            {
                Groups ngrp = dbr.Find <Domain.Socioboard.Models.Groups>(t => t.adminId == userId && t.id == groupId).FirstOrDefault();
                if (ngrp == null)
                {
                    return(Ok("Wrong Group Id"));
                }
                // Adding Facebook Profile
                int res = Api.Socioboard.Repositories.FacebookRepository.AddFacebookAccount(profile, FbUser.getFbFriends(accessToken), dbr, userId, ngrp.id, Domain.Socioboard.Enum.FbProfileType.FacebookProfile, accessToken, _redisCache, _appSettings, _logger);
                if (res == 1)
                {
                    return(Ok("Facebook account Added Successfully"));
                }
                else
                {
                    return(Ok("Error while Adding Account"));
                }
            }
        }
        public async void ContinueWithWebAuthenticationBroker(WebAuthenticationBrokerContinuationEventArgs args)
        {
            ObjFBHelper.ContinueAuthentication(args);
            if (ObjFBHelper.AccessToken != null)
            {
                fbclient = new Facebook.FacebookClient(ObjFBHelper.AccessToken);

                //Fetch facebook UserProfile:
                dynamic result = await fbclient.GetTaskAsync("me");

                string id     = result.id;
                string email  = result.email;
                string FBName = result.name;

                string profilePictureUrl = string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", id, "square", ObjFBHelper.AccessToken);
                // picProfile.Source = new BitmapImage(new Uri(profilePictureUrl));

                var bitmap = new BitmapImage(new Uri(profilePictureUrl));
                //Format UserProfile:
                // GetUserProfilePicture(id);
                // s= FBName;
                var fbuser = new FbUser()
                {
                    FbNom = FBName, ProfilePic = bitmap
                };

                SharedInformtionFbUser.sharedUser = fbuser;


                var rootFrame = Window.Current.Content as Frame;
                rootFrame.Navigate(typeof(AccLoved));
            }
            else
            {
                var bitmap = new BitmapImage(new Uri("ms-appx:///Assets/Icons/guestImage.png"));

                var fbuser = new FbUser()
                {
                    FbNom = "guest", ProfilePic = bitmap
                };

                SharedInformtionFbUser.sharedUser = fbuser;


                var rootFrame = Window.Current.Content as Frame;
                rootFrame.Navigate(typeof(MoodCoice));
            }
        }
        /// <summary>
        /// Checks if the users request is authenticated/authorized by proofing users access token:
        /// 1. Check if user exists in the database if not fetch the user from Fracebooks Graph API.
        /// 1.1. If user exists check if it is up to date (if not fetch user)
        /// 2. Check if it equals the users access token in the Database.
        /// 2.1. If not... inspecting access tokens (user and app access token) via Facebooks Graph API.
        /// </summary>
        /// <param name="shortAccessToken">The users access token which has to be validated</param>
        /// <param name="userPassword">The users Facebook-Id</param>
        /// <returns>true if access token is validated, otherwise false</returns>
        public async Task <bool> authorizeRequest(String userFbId, String shortAccessToken)
        {
            FbUser user = await fbUserRepo.GetByFbIdAsync(userFbId);

            //fetch user from FB if not yet in DB
            if (user == null)
            {
                user = await fetchAndStoreUserDetails(shortAccessToken);
            }
            //Update Fb User when last updated time > 60 minutes
            else
            {
                if ((DateTime.Now - user.lastUpdatedTimestamp).TotalHours > 1.00)
                {
                    user = await fetchAndStoreUserDetails(shortAccessToken);
                }
            }

            //When Users short access token is the same as the one in the Database then the user ist validated
            if (user != null && shortAccessToken == user.shortAccessToken)
            {
                return(true);
            }
            else
            {
                String appAccessToken = UtilService.performGetRequest(new Uri("https://graph.facebook.com/oauth/access_token?client_id=" + fbAppId + "&client_secret=" +
                                                                              fbAppSecret + "&grant_type=client_credentials"));

                String jsonResponse = UtilService.performGetRequest(new Uri("https://graph.facebook.com/v2.3/debug_token?input_token=" + shortAccessToken + "&" + appAccessToken));

                FbTokenInspection insp = JsonConvert.DeserializeObject <FbTokenInspection>(jsonResponse);

                if (insp.data.is_valid == true)
                {
                    if (user != null)
                    {
                        user.shortAccessToken = shortAccessToken;
                        fbUserRepo.UpdateAsync(user);
                    }
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
Exemple #24
0
        public async Task <IActionResult> FbLogin(FbUserAuthCodeDto fbUserAuthCodeDto)
        {
            string fbAuthToken = await ExchangeFbCodeToFbUserToken(fbUserAuthCodeDto.fbAuthCode);

            FbUser fbUser = await GetFbUser(fbAuthToken);

            User user = await _userManager.FindByEmailAsync(fbUser.Email);

            if (user == null)
            {
                user = new User
                {
                    UserName = fbUser.Email.Split("@")[0],
                    NickName = fbUser.Name,
                    Email    = fbUser.Email,
                    PhotoUrl = await _photoController.UploadAvatarByUrl(fbUser.Picture.Data.Url)
                };
                var result = await _userManager.CreateAsync(user);

                if (!result.Succeeded)
                {
                    return(BadRequest("User not created"));
                }

                var res = _userManager.AddToRoleAsync(user, "User").Result;
                if (!res.Succeeded)
                {
                    return(BadRequest("error on adding role for user"));
                }
            }

            // generate the jwt for the local user...
            var userForToken = await _userManager.FindByEmailAsync(user.Email);

            if (userForToken == null)
            {
                return(BadRequest("cant create user"));
            }

            string token = AppTokens.GenerateJwtToken(userForToken, _config, _userManager).Result;

            var userForReturnDto = _mapper.Map <UserForReturnDto>(userForToken);

            return(Ok(new { token = token, user = userForReturnDto }));
        }
        public virtual JsonResult AddOwner(long localBusinessId, long ownerId)
        {
            var user = Repository.Get<FbUser>(ownerId);
            if (user == null)
            {
                user = new FbUser(ownerId) {Status = UserStatus.Pending};
                Repository.Save(user);
            }

            var localBusiness = Repository.Get<LocalBusiness>(localBusinessId);
            var rslt = IsAuthorized(localBusiness);
            if(rslt != null ) return rslt ;

            localBusiness.AddOwner(user);
            Repository.SaveOrUpdate(localBusiness);

            return BuildSuccessResult(0, string.Empty);
        }
Exemple #26
0
        public List <FbUser> GetFriends(string myAccessToken)
        {
            FacebookClient client = new FacebookClient(myAccessToken);

            var     friendListData = client.Get("/me/friends");
            JObject friendListJson = JObject.Parse(friendListData.ToString());

            List <FbUser> fbUsers = new List <FbUser>();

            foreach (var friend in friendListJson["data"].Children())
            {
                FbUser fbUser = new FbUser();
                fbUser.Id   = friend["id"].ToString().Replace("\"", "");
                fbUser.Name = friend["name"].ToString().Replace("\"", "");
                fbUsers.Add(fbUser);
            }

            return(fbUsers);
        }
        private void btnPost_Click(object sender, RoutedEventArgs e)
        {
            if (client != null)
            {
                try
                {
                    //code for friend list

                    var     friendListData = client.Get("/me/friends");
                    JObject friendListJson = JObject.Parse(friendListData.ToString());

                    List <FbUser> fbUsers = new List <FbUser>();
                    foreach (var friend in friendListJson["data"].Children())
                    {
                        FbUser fbUser = new FbUser();
                        fbUser.Id   = friend["id"].ToString().Replace("\"", "");
                        fbUser.Name = friend["name"].ToString().Replace("\"", "");
                        fbUsers.Add(fbUser);
                    }



                    // code for post
                    dynamic parameters = new ExpandoObject();
                    parameters.message = txtPost.Text;
                    dynamic me = client.Get("me/permissions");
                    //dynamic me = client.Get("me?fields=picture,id,name,likes");
                    //Dictionary<string, string> data = new Dictionary<string, string>();
                    dynamic result = client.Post("me/feed", parameters);
                    var     id     = result.id;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error while performing post operation : " + ex.Message);
                }
            }
        }
Exemple #28
0
        public async Task <SocialUser> GetOrCreateFacebookUser(string token, string fbUserId)
        {
            var user = FindByOriginalId(fbUserId, SocialUserSource.Facebook);

            if (user == null)
            {
                FbUser fbUser = await _fbClient.GetUserInfo(token, fbUserId);

                user = FindByOriginalId(fbUserId, SocialUserSource.Facebook);
                if (user == null)
                {
                    user = new SocialUser
                    {
                        OriginalId   = fbUser.id,
                        Name         = fbUser.name,
                        Email        = fbUser.email,
                        OriginalLink = fbUser.link,
                        Avatar       = fbUser.pic,
                        Source       = SocialUserSource.Facebook
                    };

                    await UnitOfWorkManager.RunWithNewTransaction(CurrentUnitOfWork.GetSiteId(), async() =>
                    {
                        await InsertAsync(user);
                    });
                }
            }

            if (user.IsDeleted)
            {
                user.IsDeleted = false;
                user.Type      = SocialUserType.Customer;
                Update(user);
            }

            return(user);
        }
Exemple #29
0
    private void FacebookConstructorMethod(string clientId, string clientSecret, string redirectUri, string fields, string accessToken)
    {
        this.clientId     = clientId;
        this.clientSecret = clientSecret;
        this.accessToken  = accessToken;
        if (!String.IsNullOrEmpty(fields))
        {
            this.fields = fields;
        }
        if (redirectUri == "")
        {
            redirectUri = siteDefaults.SiteUrl;
        }
        this.redirectUri = redirectUri;

        if (HttpContext.Current.Request.QueryString != null && HttpContext.Current.Request.QueryString["code"] != "")
        {
            fbUser = GetFbUser();
        }
        else if (HttpContext.Current.Session["login"] != null && HttpContext.Current.Session["id"] != null)
        {
            //fbUser = GetFbUser();
        }
    }
Exemple #30
0
        /// <summary>
        /// find the user in the database or create a new one
        /// </summary>
        /// 
        /// <param name="fbidStr">
        /// Facebook Id of the user
        /// </param>
        ///
        /// <returns>
        /// user from the database or newly created and added user
        /// </returns>
        private FbUser FindOrCreateUser(string fbidStr)
        {
            /* parsed facebook ID */
            long fbid;

            if (!long.TryParse(fbidStr, out fbid))
            {
                return null;
            }

            var user = Repository.Get<FbUser>(fbid);
            if (user != null)
            {
                return user;
            }

            var url = string.Format(M_USER_REQUEST_URL, fbid);
            dynamic userObj = FbApp.Get(url);

            /* sanity check */
            if (userObj == null)
            {
                return null;
            }

            user = new FbUser
            {
                Id = fbid,
                FullName = userObj.name,
                Gender = userObj.gender,
                Name = userObj.username,
                LinkToProfile = userObj.link,
                JoinDate = DateTime.Now,
                Status = UserStatus.Pending
            };
            Repository.SaveOrUpdate(user);
            return user;
        }
Exemple #31
0
        private bool SaveUser(dynamic user, UserStatus userStatus)
        {
            if (user == null)
            {
                return false;
            }

            long userId;
            long.TryParse(user.id, out userId);

            var fbUser = Repository.Get<FbUser>(userId);
            try
            {
                if (fbUser == null)
                {
                    fbUser = new FbUser {Id = userId};
                }

                fbUser.Status = userStatus;
                fbUser.Name = user.name;
                fbUser.ProfileImageUrl = user.profile_imageUrl; //TODO: Find real profile image url
                fbUser.RelationshipStatus = user.relationship_status;
                //fbUser.SignificantOther =
                //    ExtractSignificantOther(user.significant_other);
                fbUser.JoinDate = DateTime.Now;
                fbUser.LinkToProfile = user.link;
                fbUser.Gender = user.gender;
                fbUser.FullName = user.name;
                fbUser.Email = user.email;
                Repository.SaveOrUpdate(fbUser);
            }
            catch (Exception)
            {
                /* Prompt user to try again as he wasn't saved correctly */
                return false;
            }
            return true;
        }
Exemple #32
0
 private void SaveUserVisit(Playlist playlist, FbUser user)
 {
     var visit= new Visit{ Playlist = playlist, User = user, VisitDate = DateTime.Now};
     Repository.Save(visit);
 }
Exemple #33
0
 private static UserPlaylistInfo GetUserInfo(
     Playlist playlist, FbUser user)
 {
     return (playlist == null) ? null : playlist.GetUserInfo(user);
 }
Exemple #34
0
 private FbUser CreateUser(long userId, UserStatus status)
 {
     var usr = Repository.Get<FbUser>(userId);
     if (usr == null)
     {
         usr = new FbUser
             {
                 Id = userId,
                 JoinDate = DateTime.Now,
                 Status = status
             };
         Repository.Save(usr);
     }
     else if(usr.Status == UserStatus.Removed)
     {
         usr.Status = status;
         Repository.Update(usr);
     }
     return usr;
 }
Exemple #35
0
        public virtual IEnumerable<PlaylistSongRating> GetRatings(
            short skip,
            short incremenet,
            SortOptions sort,
            bool descending,
            FbUser currentUser = null)
        {
            IEnumerable<PlaylistSongRating> songsRating = Ratings;
            switch (sort)
            {
                case SortOptions.None:
                    break;
                case SortOptions.DateAdded:
                    songsRating = Ratings.OrderByWithDirection(playlistRatings => playlistRatings.FacebookAddedDate, descending);
                    break;
                case SortOptions.Popularity:
                    //most voted for songs (not heighest rated songs though)
                    songsRating = Ratings.OrderByWithDirection(playlistRatings => playlistRatings.SummedNegativeRating + playlistRatings.SummedPositiveRating, descending);
                    break;
                case SortOptions.Rating:
                    songsRating = Ratings.OrderByWithDirection(playlistRatings => playlistRatings.SummedPositiveRating, descending);
                    break;
                case SortOptions.Me :
                    return songsRating = Ratings.Where(playlistRatings =>
                                                      playlistRatings.Details.Any(details => details.VotingUser == currentUser));
                default:
                    break;
            }

            return songsRating.Skip(skip).Take(incremenet);
        }
Exemple #36
0
 public virtual void AddOwner(FbUser owner)
 {
     if (!Owners.Contains(owner))
     {
         Owners.Add(owner);
         owner.Businesses.Add(this);
     }
 }
Exemple #37
0
        public static List <MongoFbPostComment> FbPostComments(string postid, string AccessToken)
        {
            apiHitsCount++;
            List <MongoFbPostComment> lstFbPOstComment = new List <MongoFbPostComment>();
            string ret = string.Empty;

            try
            {
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
                dynamic post = FbUser.getPostComments(AccessToken, postid);

                foreach (var item in post["data"])
                {
                    MongoFbPostComment fbPostComment = new MongoFbPostComment();
                    fbPostComment.Id        = MongoDB.Bson.ObjectId.GenerateNewId();
                    fbPostComment.EntryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss");
                    fbPostComment.PostId    = postid;

                    try
                    {
                        fbPostComment.CommentId = item["id"];
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                    }
                    try
                    {
                        fbPostComment.Comment = item["message"];
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                    }
                    try
                    {
                        fbPostComment.Likes = Convert.ToInt32(item["like_count"]);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                    }
                    try
                    {
                        fbPostComment.UserLikes = Convert.ToInt32(item["user_likes"]);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                    }
                    try
                    {
                        fbPostComment.Commentdate = DateTime.Parse(item["created_time"].ToString()).ToString("yyyy/MM/dd HH:mm:ss");
                    }
                    catch (Exception ex)
                    {
                        fbPostComment.Commentdate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss");
                    }
                    try
                    {
                        fbPostComment.FromName = item["from"]["name"];
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                    }
                    try
                    {
                        fbPostComment.FromId = item["from"]["id"];
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                    }
                    try
                    {
                        fbPostComment.PictureUrl = item["id"];
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                    }

                    try
                    {
                        lstFbPOstComment.Add(fbPostComment);

                        //MongoRepository fbPostRepo = new MongoRepository("MongoFbPostComment", settings);
                        //fbPostRepo.Add<MongoFbPostComment>(fbPostComment);
                    }
                    catch (Exception ex)
                    {
                        new List <MongoFbPostComment>();
                    }
                    try
                    {
                        //   AddFbPagePostCommentsLikes(objFbPageComment.CommentId, accesstoken, userid);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return(lstFbPOstComment);
        }
        public static string ComposeMessage(Domain.Socioboard.Enum.FbProfileType profiletype, string accessToken, string fbUserId, string message, string profileId, long userId, string imagePath, string link, Domain.Socioboard.Enum.MediaType mediaType, string profileName, DatabaseRepository dbr, ILogger _logger)
        {
            string         ret = "";
            FacebookClient fb  = new FacebookClient();

            fb.AccessToken = accessToken;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
            var args = new Dictionary <string, object>();

            if (!string.IsNullOrEmpty(message))
            {
                args["message"] = message;
            }
            if (profiletype == Domain.Socioboard.Enum.FbProfileType.FacebookProfile)
            {
                args["privacy"] = FbUser.SetPrivacy("Public", fb, profileId);
            }
            try
            {
                if (string.IsNullOrEmpty(link))
                {
                    if (!string.IsNullOrEmpty(imagePath))
                    {
                        if (!imagePath.Contains("mp4") && !imagePath.Contains("mov") && !imagePath.Contains("mpeg") && !imagePath.Contains("wmv") && !imagePath.Contains("avi") && !imagePath.Contains("flv") && !imagePath.Contains("3gp"))
                        {
                            Uri    u         = new Uri(imagePath);
                            string filename  = string.Empty;
                            string extension = string.Empty;
                            extension = System.IO.Path.GetExtension(u.AbsolutePath).Replace(".", "");
                            var media = new FacebookMediaObject
                            {
                                FileName    = "filename",
                                ContentType = "image/" + extension
                            };
                            var    webClient = new WebClient();
                            byte[] img       = webClient.DownloadData(imagePath);
                            media.SetValue(img);
                            args["source"] = media;
                            ret            = fb.Post("v2.7/" + fbUserId + "/photos", args).ToString();
                        }
                        else
                        {
                            Uri    u         = new Uri(imagePath);
                            string filename  = string.Empty;
                            string extension = string.Empty;
                            filename = imagePath.Substring(imagePath.IndexOf("get?id=") + 7);
                            if (!string.IsNullOrWhiteSpace(filename))
                            {
                                extension = filename.Substring(filename.IndexOf(".") + 1);
                            }
                            var media = new FacebookMediaObject
                            {
                                FileName    = filename,
                                ContentType = "video/" + extension
                            };
                            //byte[] img = System.IO.File.ReadAllBytes(imagepath);
                            var    webClient = new WebClient();
                            byte[] img       = webClient.DownloadData(imagePath);
                            media.SetValue(img);
                            args["title"]       = message;
                            args["description"] = message;
                            args["source"]      = media;
                            ret = fb.Post("v2.7/" + fbUserId + "/videos", args).ToString();//v2.1
                        }
                    }
                    else
                    {
                        args["message"] = message;
                        ret             = fb.Post("v2.7/" + fbUserId + "/feed", args).ToString();
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(link))
                    {
                        args["link"] = link;
                    }
                    if (!string.IsNullOrEmpty(imagePath))
                    {
                        args["picture"] = imagePath.Replace("&amp;", "&");
                    }
                    ret = fb.Post("v2.7/" + fbUserId + "/feed", args).ToString();//v2.1
                }
                ScheduledMessage scheduledMessage = new ScheduledMessage();
                scheduledMessage.createTime = DateTime.UtcNow;
                scheduledMessage.picUrl     = "https://graph.facebook.com/" + fbUserId + "/picture?type=small";//imagePath;
                scheduledMessage.profileId  = profileId;
                if (profiletype == Domain.Socioboard.Enum.FbProfileType.FacebookProfile)
                {
                    scheduledMessage.profileType = Domain.Socioboard.Enum.SocialProfileType.Facebook;
                }
                else
                {
                    scheduledMessage.profileType = Domain.Socioboard.Enum.SocialProfileType.FacebookFanPage;
                }
                scheduledMessage.scheduleTime      = DateTime.UtcNow;
                scheduledMessage.shareMessage      = message;
                scheduledMessage.userId            = userId;
                scheduledMessage.status            = Domain.Socioboard.Enum.ScheduleStatus.Compleated;
                scheduledMessage.url               = imagePath;//"https://graph.facebook.com/"+ fbUserId + "/picture?type=small";
                scheduledMessage.mediaType         = mediaType;
                scheduledMessage.socialprofileName = profileName;
                dbr.Add <ScheduledMessage>(scheduledMessage);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                _logger.LogError(ex.StackTrace);
            }
            return(ret);
        }
Exemple #39
0
 public virtual void RemoveOwner(FbUser owner)
 {
     if (Owners.Contains(owner))
     {
         Owners.Remove(owner);
         owner.Businesses.Remove(this);
     }
 }
Exemple #40
0
        //http://aabs.wordpress.com/2008/01/18/c-by-contract-using-expression-trees/
        static void Main(string[] args)
        {
            Console.WriteLine("Creating Tables...");

            var sessionFactory = new SessionFactory();

            Console.WriteLine("Finished Creating Tables!");
            Console.WriteLine("inserting new data...");
            IRepository repository = new NHibernateRepository(sessionFactory);
            foreach (var str in ConfigurationManager.ConnectionStrings)
            {
                if (!str.ToString().Contains("server=localhost") &&
                    !str.ToString().Contains(".\\SQLEXPRESS") &&
                    !str.ToString().Equals(String.Empty))
                {
                    Console.WriteLine("WTF? Don't run this on a remote server!");
                    Console.ReadKey();
                    return;
                }
            }
            try
            {
                repository.BeginTransaction();

                //stas 664118894
                var fbUser1 = new FbUser { Id = 585701767, JoinDate = DateTime.Now, Name = "anna", Status = UserStatus.Joined };
                var fbUser2 = new FbUser { Id = 806905557, JoinDate = DateTime.Now, Name = "stas", Status = UserStatus.Joined };
                var fbUser3 = new FbUser { Id = 716712905, JoinDate = DateTime.Now, Name = "dror", Status = UserStatus.Joined };
                //var fbUser3 = new FbUser { Id = 806905557, JoinDate = DateTime.Now, Name = "ran", Status = UserStatus.Joined };
                var fbUser4 = new FbUser { Id = 100000431166374, JoinDate = DateTime.Now, Name = "yadid", Status = UserStatus.Joined };

                repository.Save(fbUser1);
                repository.Save(fbUser2);
                repository.Save(fbUser3);
                repository.Save(fbUser4);

                var localBusiness1 = new LocalBusiness
                {
                    AddressCity = "Yehud",
                    AddressStreet = "Levi Eschol 1",
                    Category = "Music",
                    CreatedDate = DateTime.Now,
                    FacebookUrl = "http://www.facebook.com/pages/%D7%A7%D7%95%D7%9C%D7%95%D7%9C%D7%95/178456328876503",
                    FanPageId = 186841648018387,
                    //FanPageId = 258829897475960,
                    LastModified = DateTime.Now,
                    Name = "קולולו",
                    PublishUserContentToWall = false,
                    PublishAdminContentToWall = true,
                    Owners = new List<FbUser> { fbUser1, fbUser2, fbUser3, fbUser4 }
                };

                var uriBusiness = new LocalBusiness
                    {
                        AddressCity = "Faraway city",
                        AddressStreet = "Back alley",
                        Category = "Music",
                        CreatedDate = DateTime.Now,
                        FacebookUrl =
                            "https://www.facebook.com/pages/%D7%96%D7%9E%D7%A8-test/245866165438909",
                        FanPageId = 245866165438909,
                        FBFanPageAccessToken = "157721837628308|afd07c5be8ae8e01047a1156.1-662326561|juC8P9wsNLP5XirWXPCzEMF7qPU",
                        ImageUrl =
                            "https://fbcdn-profile-a.akamaihd.net/static-ak/rsrc.php/v1/yA/r/gPCjrIGykBe.gif",
                        LastModified = DateTime.Now,
                        Name = "זמר טסט",
                        PublishUserContentToWall = true,
                        PublishAdminContentToWall = true,
                        Owners =
                            new List<FbUser>
                                {fbUser1, fbUser2, fbUser3, fbUser4}
                    };

                var uriRadio = new Playlist
                    {
                        Name = "Radio Uri",
                        Description = "",
                        Image = "",
                        CreationDate = DateTime.Now,
                        LastModifiedDate = DateTime.Now,
                        NextPlayDate = DateTime.Parse("23/07/2013 08:55:00"),
                        IsUserModifyable = true,
                        NumOfSongsLimit = 5
                    };

                uriBusiness.AddPlaylist(uriRadio);
                uriBusiness.ImportPlaylist = uriRadio;
                repository.Save(uriBusiness);

                var radio1 = new Playlist
                {
                    Name = "Kululu-FM",
                    Description = "",
                    Image = "",
                    CreationDate = DateTime.Now,
                    LastModifiedDate = DateTime.Now,
                    NextPlayDate = DateTime.Parse("23/07/2012 08:55:00"),
                    IsUserModifyable = true,
                    NumOfSongsLimit = 5
                };

                localBusiness1.AddPlaylist(radio1);
                localBusiness1.ImportPlaylist = radio1;
                repository.Save(localBusiness1);

                var localBusiness2 = new LocalBusiness()
                {
                    Owners = new List<FbUser> { fbUser1 },
                    AddressCity = "Haifa",
                    AddressStreet = "Rauel Wallenberg",
                    Category = "Music",
                    CreatedDate = DateTime.Now,
                    FacebookUrl = "http://www.facebook.com/pages/%D7%A7%D7%95%D7%9C%D7%95%D7%9C%D7%95/178456328876503",
                    FanPageId = 1,
                    ImageUrl = "http://profile.ak.fbcdn.net/hprofile-ak-snc4/195725_178456328876503_4279627_n.jpg",
                    LastModified = DateTime.Now,
                    PublishAdminContentToWall = true,
                    PublishUserContentToWall = false,
                    Name = "Kululu Test"
                };

                var radio2 = new Playlist
                {
                    Description = "",
                    Image = "",
                    CreationDate = DateTime.Now,
                    LastModifiedDate = DateTime.Now,
                    Name = "Radius-100FM",
                    NextPlayDate = DateTime.Parse("25/07/2011"),
                    IsUserModifyable = true,
                    NumOfSongsLimit = 10
                };

                localBusiness2.AddPlaylist(radio2);
                repository.Save(localBusiness2);

                var playlistSongRating = SaveSong(repository, radio1, fbUser1, "Cee Lo Green", "Bright Lights Bigger City", 231, "UBhdIcb84Hw", 1, "http://userserve-ak.last.fm/serve/126s/62075863.png");
                //radio1.AddRating(song, fbUser3, -1);
                radio1.RateSong(playlistSongRating, fbUser4, 1);
                radio1.RateSong(playlistSongRating, fbUser2, 1);
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);
                uriRadio.RateSong(playlistSongRating, fbUser4, 1);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "מוש בן ארי", "סתכל לי בעיניים", 249, "HwgVLsnaAoU", 1, "http://userserve-ak.last.fm/serve/126s/20443621.jpg");
                //radio1.AddRating(song, fbUser3, 1);
                radio1.RateSong(playlistSongRating, fbUser4, 1);
                radio1.RateSong(playlistSongRating, fbUser2, 1);
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);
                uriRadio.RateSong(playlistSongRating, fbUser4, 1);
                uriRadio.RateSong(playlistSongRating, fbUser2, 1);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "J.LO FT. Pitbull", "On The Floor", 267, "t4H_Zoh7G5A", 1, null);
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "גלעד שגב", "חנה'לה התבלבלה", 214, "vAlFB4Z7P2Y", 1, "http://userserve-ak.last.fm/serve/126s/163895.jpg");
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "Adele", "Someone Like You", 306, "7AW9C3-qWug", 1, "http://userserve-ak.last.fm/serve/126s/58297847.png");
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                SaveSong(repository, radio1, fbUser1, "Britney Spears", "Till The World Ends", 236, "qzU9OrZlKb8", 1, "http://userserve-ak.last.fm/serve/126s/59558187.png");
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                SaveSong(repository, radio1, fbUser1, "Enrique Iglesias", "Tonight", 299, "Jx2yQejrrUE", 1, "http://userserve-ak.last.fm/serve/126s/65262750.png");
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "Pitbull", "Give Me Everything", 267, "EPo5wWmKEaI", 1, "http://userserve-ak.last.fm/serve/126s/64990460.png");
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                //radio1.AddRating(song, fbUser3, -1);
                radio1.RateSong(playlistSongRating, fbUser4, 1);
                radio1.RateSong(playlistSongRating, fbUser2, -1);
                uriRadio.RateSong(playlistSongRating, fbUser4, 1);
                uriRadio.RateSong(playlistSongRating, fbUser2, -1);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "Lady Gaga", "Born This Way", 440, "wV1FrqwZyKw", 1, "http://userserve-ak.last.fm/serve/126s/63387017.png");
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "ברי סחרוף", "זמן של מספרים", 303, "PCwDDGYely0", 1, "http://userserve-ak.last.fm/serve/126s/784256.jpg");
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "Depeche Mode", "Personal Jesus (The Stargate Mix)", 252, "3xLvArgSp3k", 1, "http://userserve-ak.last.fm/serve/126s/2126897.jpg");
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "Diddy Dirty Money ft. Skylar Grey", "Coming Home", 251, "k-ImCpNqbJw", 1, null);
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "The Black Eyed Peas", "Just Can't Get Enough", 236, "OrTyD7rjBpw", 1, "http://userserve-ak.last.fm/serve/126s/65970878.png");
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "Bob Sinclar & Raffaella Carrà", "Far l'Amore", 220, "rSmdeqxxLLk", 1, "http://userserve-ak.last.fm/serve/126s/26932877.jpg");
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "Jessie J ft. B.o.B.", "Price Tag", 247, "qMxX-QOV9tI", 1, null);
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                //radio1.AddRating(song, fbUser3, -1);
                radio1.RateSong(playlistSongRating, fbUser4, -1);
                radio1.RateSong(playlistSongRating, fbUser2, -1);
                uriRadio.RateSong(playlistSongRating, fbUser4, -1);
                uriRadio.RateSong(playlistSongRating, fbUser2, -1);
                //radio2.AddRating(song, fbUser3, 1);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "Lady Gaga", "The Edge Of Glory", 328, "QeWBS0JBNzQ", 1, "http://userserve-ak.last.fm/serve/126s/63387017.png");
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                //SaveSong(repository, radio1, fbUser1, "הפרוייקט של עידן רייכל - אִמָּא, אַבָּא וכל הַשְּׁאָר", "D98E89oUo6o", 1);
                playlistSongRating = SaveSong(repository, radio1, fbUser1, "אדיר גץ", "איך היא רוקדת", 236, "Pu2s7bboV9M", 1, "http://userserve-ak.last.fm/serve/126s/51539323.jpg");
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "שלומי סרנגה", "זה רק נדמה לך", 218, "MaZIYKtIfnM", 1, "http://userserve-ak.last.fm/serve/126s/83144.jpg");
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                playlistSongRating = SaveSong(repository, radio1, fbUser1, "מאור כהן", "ישראל", 183, "svjdhfKJbUc", 1, "http://userserve-ak.last.fm/serve/126s/311813.jpg");
                uriRadio.AddSong(playlistSongRating.Song, fbUser1, true);

                //radio2.RateSong(song, fbUser2, 1);
                //radio2.AddRating(song, fbUser3, 1);

                repository.CommitTransaction();
            }
            catch (Exception e)
            {
                repository.RollbackTransaction();
                repository.CloseSession();

                Console.WriteLine("*** Failure ({0}): {1}", e.GetType(), e.Message);
            }
            Console.WriteLine("Finished!");
            Console.ReadKey();
        }
Exemple #41
0
        /// <summary>
        /// is the current usere admin of relevant fan page?
        /// </summary>
        ///
        /// <param name="user">
        /// user to be mapped
        /// </param>
        ///
        /// <param name="playlist">
        /// playlist with which current operation is executed
        /// </param>
        ///
        /// <param name="privileges">
        /// additional information: user privileges to be set in returned
        /// object
        /// </param>
        ///
        /// <param name="loggedInUserInfo">
        /// cookie information about currently logged in user
        /// </param>
        ///
        /// <returns>
        /// mapped user object with additional information
        /// </returns>
        public static UserDTO Map(FbUser user,
            FbCookieInfo loggedInUserInfo,
            Playlist playlist,
            UserPrivileges privileges = UserPrivileges.None)
        {
            if (user == null)
            {
                return null;
            }

            var userDTO = MemberDTOFactory.Map<UserDTO>(user, playlist);

            userDTO.role = privileges.ToString();
            userDTO.IsPageAdmin = loggedInUserInfo.IsAdmin;
            userDTO.HasLikedPage = loggedInUserInfo.HasLikedPage;

            if (playlist == null)
            {
                return userDTO;
            }

            if (loggedInUserInfo.IsAdmin)
            {
                userDTO.name = playlist.LocalBusiness.Name;
                userDTO.FBID = playlist.LocalBusiness.FanPageId;
            }

            // TODO: test this assumption: We're assuming that since a user
            // doesn't have a score, it means he didn't even add a song
            // since he didn't add a song, that's why we can set numOfSongsAdded to playlist's max
            if (userDTO.score == 0)
            {
                userDTO.numOfSongsLeft = playlist.NumOfSongsLimit;
            }
            else
            {
                var userInfo = user.PlaylistsInfo.FirstOrDefault(p => p.Playlist == playlist);
                //TODO: remove redundant NumOfVotes column
                userDTO.numOfVotes = userInfo.NumOfVotes;
                userDTO.numOfSongsLeft = playlist.GetNumOfSongsLeft(user);
            }

            return userDTO;
        }
Exemple #42
0
 public virtual UserPlaylistInfo GetUserInfo(FbUser user)
 {
     var usrPlylistInfo = UserInfo.FirstOrDefault(info => info.User == user);
     if (usrPlylistInfo == null && !IsOwner(user.Id)) //admins don't need this connection to the playlist
     {
         usrPlylistInfo = new UserPlaylistInfo
             {
                 NumOfSongsUsed = 0,
                 User = user,
                 Points = 0,
                 LastEntrance = DateTime.Now
             };
         AddUserInfo(usrPlylistInfo);
     }
     return usrPlylistInfo;
 }
Exemple #43
0
	void ConstructUsers(List<object> usersData, ref List<FbUser> users)
	{
		users = new List<FbUser>(16);
		foreach (Dictionary<string, object> user in usersData)
		{
			FbUser newUser = new FbUser();
			newUser.firstName = user["first_name"] as string;
			newUser.id = user["id"] as string;
			newUser.pictureUrl = ((user["picture"] as Dictionary<string, object>)["data"] as Dictionary<string, object>)["url"] as string;
			
			users.Add(newUser);	
		}
	}
Exemple #44
0
        public virtual PlaylistSongRating DetachSong(PlaylistSongRating playlistSongRating, FbUser user)
        {
            if (playlistSongRating != null)
            {
                Ratings.Remove(playlistSongRating);
                NumberOfVotes -= playlistSongRating.Details.Count(detail=>detail.Rating!=0);
                NumberOfVotes -= Math.Abs(playlistSongRating.AdminRating);
                NumberOfSongs--;

                //TODO: enhance this efficiency, move this to nhibernate layer. Currently alright for this usage, but might be heavy.
                foreach (var detail in playlistSongRating.Details.Select(_detail=>_detail.VotingUser))
                {
                    var userPlaylistInfo = detail.PlaylistsInfo.FirstOrDefault(pInfo => pInfo.Playlist == this);
                    if(userPlaylistInfo!= null)
                        userPlaylistInfo.NumOfVotes--;
                }

                //we don't reward the owner of the playlist, it's not fair
                if (playlistSongRating.IsOwner(user.Id))
                {
                    RewardUser(user, UserPlaylistInfo.Operation.DeleteSong);
                    if (playlistSongRating.Details.Any(details => 
                        details.VotingUser == user
                        && details.Rating!=0))
                    {
                        RewardUser(user, UserPlaylistInfo.Operation.RemoveSongRating);
                    }
                }
            }
            return playlistSongRating;
        }
Exemple #45
0
        /// <summary>
        /// process single wall post with link
        /// </summary>
        ///
        /// <param name="fp">
        /// fan page this post belongs to
        /// </param>
        ///
        /// <param name="post">
        /// facebook post as recevied from facebook API
        /// </param>
        ///
        /// <param name="user">
        /// user posting this link
        /// </param>
        ///
        ///<returns></returns>
        private PlaylistSongRatingAndLikes ProcessLink(
            LocalBusiness fp,
            dynamic post,
            FbUser user = null)
        {
            var name = post.ContainsKey("name") ?
                (string)post["name"] : string.Empty;

            var caption = post.ContainsKey("caption") ?
                (string)post["caption"] : string.Empty;

            var id = post.ContainsKey("id") ?
                (string)post["id"] : string.Empty;

            // TODO: move this to some method
            var link = GetVideoLink(post);

            var addedDate = Convert.ToDateTime(post["created_time"]);

            var from = post["from"];
            var fromId = from.ContainsKey("id") ? from["id"] : 0;

            var numOfComments = (int)post["comments"]["count"];

            var numOfLikes = post.ContainsKey("likes") ?
                (int)post["likes"]["count"] : 0;
            var message = post.ContainsKey("message") ?
                post["message"] : null;

            var description = post.ContainsKey("description") ?
                post["description"] : null;

            /* if not record was found and localbusiness doesn't allow import
             * of new content, exit */
            if (!ShouldImport(fp))
            {
                return null;
            }

            /* try to find this song in the database or create one */
            if (user == null)
            {
                user = FindOrCreateUser(fromId);
            }

            var song = FindOrCreateSong(link, name, caption) as Song;
            if (song == null)
            {
                return null;
            }

            // song doesn't exist in DB yet
            if (song.Id == 0)
            {
                Repository.Save(song);
            }

            var rating = Repository.Query<PlaylistSongRating>()
                .Where(r => r.Playlist == fp.ImportPlaylist)
                .Where(r => r.FBPostId == id)
                .FirstOrDefault();

            /* if this rating is already stored in the database, do nothing */
            if (rating == null)
            {
                rating = fp.ImportPlaylist.AddSong(song, user, true, 0);
                rating.FBMessage = message;
                rating.FBDescription = description;
                rating.Origin = Origin.Facebook;
                rating.FBPostId = id;
                rating.FacebookAddedDate = addedDate;
            }
            else
            {
                Logger.InfoFormat(
                    "The song with the {0} FBPostId already exists under this FbPostId {1}",
                    id,
                    rating.FBPostId);
            }

            rating.NumOfComments = numOfComments;
            Repository.SaveOrUpdate(rating);
            Repository.SaveOrUpdate(fp.ImportPlaylist);

            return new PlaylistSongRatingAndLikes
                {
                    PlaylistSongRating = rating,
                    NumOfLikes = numOfLikes
                };
        }
Exemple #46
0
        private void RewardUser(FbUser user,UserPlaylistInfo.Operation options, bool isAdmin = false)
        {
            if (isAdmin || user == null)
            {
                return;
            }

            var userInfo = GetUserInfo(user);
            if (userInfo != null)
            {
                userInfo.UpdateUserScore(options);
            }
        }
Exemple #47
0
 private void UpdateAggregatedInfo(RatingStatus ratingStatus, FbUser ratingUser, bool isNewSong, bool isAdmin = false)
 {
     switch (ratingStatus)
     {
         case RatingStatus.AddedNewEmptyRating:
             if (isNewSong)
             {
                 NumberOfSongs++;
                 RewardUser(ratingUser, UserPlaylistInfo.Operation.AddSong, isAdmin);
             }
             break;
         case RatingStatus.AddedNewRating:
             if (isNewSong)
             {
                 NumberOfSongs++;
                 NumberOfVotes++;
                 RewardUser(ratingUser, UserPlaylistInfo.Operation.AddSong, isAdmin);
             }
             else
             {
                 NumberOfVotes++;
             }
             RewardUser(ratingUser, UserPlaylistInfo.Operation.RateSong, isAdmin);
             break;
         case RatingStatus.AddedRating:
             RewardUser(ratingUser, UserPlaylistInfo.Operation.RateSong, isAdmin);
             NumberOfVotes++;
             break;
         case RatingStatus.RemovedRating:
             NumberOfVotes--;
             RewardUser(ratingUser, UserPlaylistInfo.Operation.RemoveSongRating, isAdmin);
             break;
         default:
             break;
     }
 }
Exemple #48
0
        public virtual PlaylistSongRating AddSong(Song song, FbUser user, bool addedByAdmin, short rating = 1)
        {
            var playlistSongRating = new PlaylistSongRating
            {
                Playlist = this,
                Song = song,
                Creator = user
            };
            Ratings.Add(playlistSongRating);

            var palylistSongRating = RateSong(playlistSongRating, user, rating, addedByAdmin, true);

            if (addedByAdmin)
            {
                palylistSongRating.IsAddedByAdmin = true;
            }

            return palylistSongRating;
        }
Exemple #49
0
        /// <summary>
        /// add single rating to the database or update it with new value
        /// </summary>
        ///
        /// <param name="song">
        /// song to add the rating to
        /// </param>
        ///
        /// <param name="ratingUser">
        /// who's adding this rating?
        /// </param>
        ///
        /// <param name="rating">
        /// rating value: either 1 or -1
        /// </param>
        ///
        /// <returns>
        /// A boolean indicating if rating was in the right input range (between -1 to 1)
        /// </returns>
        public virtual PlaylistSongRating RateSong(PlaylistSongRating playlistSongRating, FbUser ratingUser, short rating,  bool isAddedByAdmin = false, bool isNewSong = false)
        {
            if (PlaylistSongRating.IsRatingValueInvalid(rating))
            {
                return null;
            }

            RatingStatus ratingType = RatingStatus.NothingNew;
            //var currentStatistics = GetCurrentStatistics(song);

            if (isAddedByAdmin) //if admin votes the song give it a special treatment
            {                   
                if (playlistSongRating.AdminRating != 0 && rating == 0)    //admin just cleared his vote
                {
                    ratingType = RatingStatus.RemovedRating;
                }

                if (playlistSongRating.AdminRating == 0 && rating != 0) //admin switched between positive and negative score
                {                                                     
                    ratingType = RatingStatus.AddedNewRating;
                }

                if (playlistSongRating.AdminRating == 0 && rating == 0) //admin added song but didn't rate it (can be achieved through harvesting)
                {
                    ratingType = RatingStatus.AddedNewEmptyRating;
                }

                playlistSongRating.SetAdminRating(playlistSongRating.AdminRating, rating, isNewSong);
                playlistSongRating.AdminRating = rating;
            }
            else 
            {
                ratingType = playlistSongRating.AddRating(ratingUser, rating);
            }

            //note: AddRating also adds points to user as well as advances the NumberOfVotes and NumberOfSongs counters
            UpdateAggregatedInfo(ratingType, ratingUser, isNewSong, isAddedByAdmin);
            return playlistSongRating;
        }
Exemple #50
0
 private static PlaylistSongRating SaveSong(IRepository repository, Playlist playlist, FbUser votingUser,
     string artistName, string songName, double duration, string videoId, short rating, string imageUrl)
 {
     var song = new Song
         {
             Name = songName,
             ArtistName = artistName,
             Duration = duration,
             VideoID = videoId,
             ImageUrl = imageUrl
         };
     repository.Save(song);
     var playlistRating = playlist.AddSong(song, votingUser, playlist.IsOwner(votingUser.Id));
     repository.SaveOrUpdate(playlistRating);
     return playlistRating;
 }
Exemple #51
0
        /// <summary>
        /// adds rating to the song
        /// </summary>
        ///
        /// <param name="user">
        /// user adding current rating
        /// </param>
        ///
        /// <param name="rating">
        /// value of the rating added
        /// </param>
        ///
        /// <returns>
        /// A boolean indicating if rating was in the right input range
        /// (between -1 to 1)
        /// </returns>
        ///
        /// <remarks>
        /// if the user already has the rating for the song in specified
        /// playlist, update the rating. If the previous rating had value and
        /// the current one does not (rating = 0), decrease number of points
        /// of the user.
        /// if previous rating has been 0, and current one is not, add points
        /// to the user.
        /// if this is the first rating of the user, increase number of points
        /// for the user.
        /// 
        /// Note: Do not use this method for page \ admin rating
        /// </remarks>
        public virtual RatingStatus AddRating(FbUser user, short rating)
        {
            if (IsRatingValueInvalid(rating))
            {
                return RatingStatus.Error;
            }

            var songRating = Details.FirstOrDefault(lookupSongRating => lookupSongRating.VotingUser.Id == user.Id);
            if (songRating == null)
            {
                InsertNewSongRating(user, rating);
                return RatingStatus.AddedNewRating;
            }
            else
            {
                RatingStatus ratingStatus = RatingStatus.NothingNew;
                if (songRating.Rating != 0 && rating == 0)
                {
                    ratingStatus = RatingStatus.RemovedRating;
                }
                else if (songRating.Rating == 0 && rating != 0)
                {
                    ratingStatus= RatingStatus.AddedRating;
                }
                UpdatePlaylistSongRating(songRating, rating);
                return ratingStatus;
            }
        }
 // POST api/users
 public void Post([FromBody] FbUser user)
 {
     // Save user
 }
Exemple #53
0
 void InsertNewSongRating(FbUser user, short rating)
 {
     RatingDetails songRating = new RatingDetails(user, rating);
     AddPlaylistSongRating(songRating);
 }
Exemple #54
0
        public static string ComposeMessage(Domain.Socioboard.Enum.FbProfileType profiletype, string accessToken, string fbUserId, string message, string profileId, long userId, string imagePath, string link, Domain.Socioboard.Enum.MediaType mediaType, string profileName, DatabaseRepository dbr, ILogger _logger)
        {
            string         ret = "";
            FacebookClient fb  = new FacebookClient();

            fb.AccessToken = accessToken;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
            var args = new Dictionary <string, object>();

            if (!string.IsNullOrEmpty(message))
            {
                args["message"] = message;
            }
            if (profiletype == Domain.Socioboard.Enum.FbProfileType.FacebookProfile)
            {
                args["privacy"] = FbUser.SetPrivacy("Public", fb, profileId);
            }
            try
            {
                if (string.IsNullOrEmpty(link))
                {
                    if (!string.IsNullOrEmpty(imagePath))
                    {
                        if (!imagePath.Contains("mp4") && !imagePath.Contains("mov") && !imagePath.Contains("mpeg") && !imagePath.Contains("wmv") && !imagePath.Contains("avi") && !imagePath.Contains("flv") && !imagePath.Contains("3gp"))
                        {
                            Uri    u         = new Uri(imagePath);
                            string filename  = string.Empty;
                            string extension = string.Empty;
                            extension = System.IO.Path.GetExtension(u.AbsolutePath).Replace(".", "");
                            var media = new FacebookMediaObject
                            {
                                FileName    = "filename",
                                ContentType = "image/" + extension
                            };
                            var    webClient = new WebClient();
                            byte[] img       = webClient.DownloadData(imagePath);
                            media.SetValue(img);
                            args["source"] = media;
                            ret            = fb.Post($"{FbConstants.FacebookApiVersion}/" + fbUserId + "/photos", args).ToString();
                        }
                        else
                        {
                            Uri    u         = new Uri(imagePath);
                            string filename  = string.Empty;
                            string extension = string.Empty;
                            filename = imagePath.Substring(imagePath.IndexOf("get?id=") + 7);
                            if (!string.IsNullOrWhiteSpace(filename))
                            {
                                extension = filename.Substring(filename.IndexOf(".") + 1);
                            }
                            var media = new FacebookMediaObject
                            {
                                FileName    = filename,
                                ContentType = "video/" + extension
                            };
                            //byte[] img = System.IO.File.ReadAllBytes(imagepath);
                            var    webClient = new WebClient();
                            byte[] img       = webClient.DownloadData(imagePath);
                            media.SetValue(img);
                            args["title"]       = message;
                            args["description"] = message;
                            args["source"]      = media;
                            ret = fb.Post($"{FbConstants.FacebookApiVersion}/" + fbUserId + "/videos", args).ToString();//v2.1
                        }
                    }
                    else
                    {
                        args["message"] = message;
                        ret             = fb.Post($"{FbConstants.FacebookApiVersion}/" + fbUserId + "/feed", args).ToString();
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(link))
                    {
                        args["link"] = link;
                    }
                    if (!string.IsNullOrEmpty(imagePath))
                    {
                        args["picture"] = imagePath.Replace("&amp;", "&");
                    }
                    ret = fb.Post($"{FbConstants.FacebookApiVersion}/" + fbUserId + "/feed", args).ToString();//v2.1
                }
                UpdatePublishedDetails(profiletype, fbUserId, message, profileId, userId, imagePath, mediaType, profileName, dbr);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                _logger.LogError(ex.StackTrace);
            }
            return(ret);
        }
Exemple #55
0
        public virtual bool DoesRatingExist(Song song, FbUser ratingUser)
        {
            var currentStatistics = GetCurrentStatistics(song);

            if (currentStatistics == null)
            {
                return false;
            }
            return currentStatistics.Details.Any(_details => _details.VotingUser.Id == ratingUser.Id);
        }
Exemple #56
0
        /// <summary>
        /// get number of songs used by current user
        /// </summary>
        ///
        /// <param name="user">
        /// user to test
        /// </param>
        ///
        /// <returns>
        /// number of songs left for the user to vote on
        /// </returns>
        public virtual int GetNumOfSongsLeft(FbUser user)
        {
            var numOfSongsUsed = 0;

            if (IsSongsLimitDaily)
            {
                numOfSongsUsed = Ratings.Where(
                        r => r.CreationTime > DateTime.Now.AddDays(-1))
                    .Where(r => r.Creator == user)
                    .Count();
            }
            else
            {
                var userInfo = UserInfo.FirstOrDefault(ui => ui.User == user);
                if (userInfo != null)
                {
                    numOfSongsUsed = userInfo.NumOfSongsUsed;
                }
            }
            return NumOfSongsLimit  - numOfSongsUsed;
        }
Exemple #57
0
        public virtual bool HasUserRatedSong(Song song, FbUser CurrentUser)
        {
            var queriedWeddingSongsStats =
                Ratings.Where(weddingSongsStas => weddingSongsStas.Song.Id == song.Id).FirstOrDefault();

            if (queriedWeddingSongsStats == null)
            {
                return false;
            }

            var ratedSong = 
                    queriedWeddingSongsStats.Details.ToList()
                                            .Where(songRating => songRating.VotingUser.Id == CurrentUser.Id)
                                            .FirstOrDefault();
            return (ratedSong != null);
        }