private void FriendsUsingAppCallBack(IGraphResult result)
        {
            FBLog("FriendsDataCallBack", result.RawResult);
            FacebookHelperResultType resultType = FacebookHelperResultType.ERROR;

            if (result != null && result.Error == null)
            {
                JSONObject jsonObject = JSONObject.Parse(result.RawResult);
                JSONValue  dataArray  = jsonObject.GetArray("data");

                foreach (JSONValue friend in dataArray.Array)
                {
                    string userId   = friend.Obj.GetString("id");
                    string UserName = friend.Obj.GetString("name");
                    Debug.Log("NAME " + UserName);
                    if (PreloadFriendImages)
                    {
                        LoadProfileImage(userId);
                    }
                    FacebookFriend facebookFriend = new FacebookFriend();
                    facebookFriend.Id   = userId;
                    facebookFriend.Name = UserName;
                    Friends.Add(facebookFriend);
                }

                IsFriendsLoaded = true;
                resultType      = FacebookHelperResultType.OK;
            }

            OnFriendsUsingAppAction(resultType);
        }
Esempio n. 2
0
        private void LoadPlayerInfo(JsonData playerData)
        {
            string token = (string)playerData["token"];

            TicTacToe.PlayerInfo playerInfo;
            if (token == "X")
            {
                playerInfo = playerXInfo;
            }
            else
            {
                playerInfo = playerOInfo;
            }

            if ((string)playerData["playerId"] == FacebookLogin.PlayerId)
            {
                playerInfo.name   = FacebookLogin.PlayerName;
                playerInfo.picUrl = FacebookLogin.PlayerPicUrl;
                yourToken         = token;
            }
            else
            {
                // Find your friend in your facebook list
                foreach (FacebookFriend _fbFriend in m_fbFriends)
                {
                    if (_fbFriend.playerId == (string)playerData["playerId"])
                    {
                        fbFriend = _fbFriend;
                        break;
                    }
                }
                playerInfo.name   = fbFriend.name;
                playerInfo.picUrl = fbFriend.picUrl;
            }
        }
Esempio n. 3
0
		private void LoadPlayerInfo(JsonData playerData)
		{
			string token = (string)playerData["token"];
			TicTacToe.PlayerInfo playerInfo;
			if (token == "X") playerInfo = playerXInfo;
			else playerInfo = playerOInfo;

			if ((string)playerData["playerId"] == FacebookLogin.PlayerId)
			{
				playerInfo.name = FacebookLogin.PlayerName;
				playerInfo.picUrl = FacebookLogin.PlayerPicUrl;
				yourToken = token;
			}
			else 
			{
				// Find your friend in your facebook list
				foreach (FacebookFriend _fbFriend in m_fbFriends)
				{
					if (_fbFriend.playerId == (string)playerData["playerId"])
					{
						fbFriend = _fbFriend;
						break;
					}
				}
				playerInfo.name = fbFriend.name;
				playerInfo.picUrl = fbFriend.picUrl;
			}
		}
Esempio n. 4
0
    IEnumerator getProfileTexture(FacebookFriend friend)
    {
        string url = "https://graph.facebook.com/" + friend.ID + "/picture";

        WWW www = new WWW(url);

        yield return www;

        if (www.texture != null)
        {
            // store the profile pic
            friend.ProfilePic = www.texture;

            int index = friends.IndexOf(friend) + 1;

            // get first 4 friends
            if (index <= 4 && index < friends.Count)
            {
                StartCoroutine("getProfileTexture", friends[index]);                
            }

        }
        else
        {
            Debug.Log("Error getting profile pic for " + friend.Name);
        }

    }
    IEnumerator getProfileTexture(FacebookFriend friend)
    {
        string url = "https://graph.facebook.com/" + friend.ID + "/picture";

        WWW www = new WWW(url);

        yield return(www);

        if (www.texture != null)
        {
            // store the profile pic
            friend.ProfilePic = www.texture;

            int index = friends.IndexOf(friend) + 1;

            // get first 4 friends
            if (index <= 4 && index < friends.Count)
            {
                StartCoroutine("getProfileTexture", friends[index]);
            }
        }
        else
        {
            Debug.Log("Error getting profile pic for " + friend.Name);
        }
    }
Esempio n. 6
0
        public async void UpdateCell(FacebookFriend friend)
        {
            CALayer profileImageCircle = friendImage.Layer;

            profileImageCircle.CornerRadius  = 30;
            profileImageCircle.MasksToBounds = true;
            friendImage.Image = await LoadImage(friend.ImageUrl);
        }
Esempio n. 7
0
    IEnumerator SetProfilePic(string url, FacebookFriend fbFriend)
    {
        fbFriend.picUrl = url;
        WWW www = new WWW(url);

        yield return(www);

        fbFriend.pic = www.texture;
    }
	private IEnumerator LoadProfilePicture(FacebookFriend friend, UITexture texture)
	{
		Debug.Log("Getting profile picture for friend " + friend.name);
		Texture profilePicture = null;
		yield return StartCoroutine(friend.GetProfilePicture(value => profilePicture = value));

		Debug.Log("Finished loading profile picture for friend " + friend.name);

		texture.mainTexture = profilePicture;
	}
Esempio n. 9
0
        public ActionResult Removeinvitation(string id)
        {
            lstdto = HttpContext.Session["fbidlist"] as List <FacebookFriend>;

            FacebookFriend frnd = new FacebookFriend();
            var            dt   = lstdto.Where(p => p.id == id).SingleOrDefault();

            frnd.id = dt.id;
            lstdto.Remove(dt);

            HttpContext.Session["fbidlist"] = lstdto;
            return(View());
        }
Esempio n. 10
0
            public static async void SetImage(Context context, ImageView iv, FacebookFriend f)
            {
                FileInfo fi = new FileInfo(System.IO.Path.Combine(baseDir, f.uid));

                if (!fi.Exists || fi.LastWriteTime < DateTime.Now.AddDays(-7))
                {
                    using (var bmp = await DownloadImageAsync(f.pic_square, f.uid))
                    {
                        iv.SetImageBitmap(bmp);
                    }
                }
                else
                {
                    using (var bmp = BitmapFactory.DecodeFile(System.IO.Path.Combine(baseDir, f.uid)))
                    {
                        iv.SetImageBitmap(bmp);
                    }
                }
            }
Esempio n. 11
0
        public async void MakeRequestForFacebookFriend()
        {
            var credentials = TestSettings.GetToken <Facebook, OAuth2Credentials>();

            if (credentials.IsTokenExpired)
            {
                throw new Exception("Expired credentials!!!");
            }

            var request = new FacebookFriend()
            {
                Since = DateTime.Today.Subtract(TimeSpan.FromDays(500)),
                Until = DateTime.Today,
                Limit = 10
            };
            var response = await new OAuthRequester(credentials)
                           .MakeOAuthRequestAsync <FacebookFriend, string>(request)
                           .ConfigureAwait(false);

            Assert.NotNull(response);
        }
Esempio n. 12
0
 private async Task <ScheduleJobDef> ReadScheduleJobDefAsync(MySqlDataReader odr)
 {
     return(new ScheduleJobDef
     {
         Id = await odr.ReadMySqlIntegerAsync("id"),
         AppUserId = await odr.ReadMySqlIntegerAsync("appuser_id"),
         Name = await odr.ReadMySqlStringAsync("name"),
         FriendId = await odr.ReadMySqlIntegerAsync("friend_id"),
         FacebookCredentialId = await odr.ReadMySqlIntegerAsync("facebookcredential_id"),
         Type = await odr.ReadMySqlEnumAsync <ScheduleJobType>("type"),
         IntervalType = await odr.ReadMySqlEnumAsync <IntervalTypeEnum>("interval_type"),
         TimeFrom = await odr.ReadMySqlStringAsync("time_from"),
         TimeTo = await odr.ReadMySqlStringAsync("time_to"),
         TimeZone = await odr.ReadMySqlStringAsync("timezone_id"),
         Active = await odr.ReadMySqlBooleanAsync("active"),
         AppUser = new AppUser
         {
             Id = await odr.ReadMySqlIntegerAsync("appuser_id"),
             Email = await odr.ReadMySqlStringAsync("appuser_email"),
             Title = await odr.ReadMySqlStringAsync("appuser_title"),
             Firstname = await odr.ReadMySqlStringAsync("appuser_firstname"),
             Lastname = await odr.ReadMySqlStringAsync("appuser_lastname"),
             Disabled = await odr.ReadMySqlBooleanAsync("appuser_disabled"),
             Active = await odr.ReadMySqlBooleanAsync("appuser_active"),
             Role = await odr.ReadMySqlEnumAsync <UserRole>("appuser_role"),
         },
         Friend = new FacebookFriend
         {
             Id = await odr.ReadMySqlIntegerAsync("friend_id"),
             Name = await odr.ReadMySqlStringAsync("friend_name"),
             ProfileLink = await odr.ReadMySqlStringAsync("friend_profile_link"),
             Disabled = await odr.ReadMySqlBooleanAsync("friend_disabled"),
         },
         WeekDayIds = (await odr.ReadMySqlStringAsync("scheduleweekday_ids", string.Empty))
                      .Split(',')
                      .Where(wd => int.TryParse(wd, out int parsedId))
                      .Select(wd => Convert.ToInt32(wd))
                      .ToList(),
     });
Esempio n. 13
0
    void OnReadFriendData(string responseData, object cbPostObject)
    {
        m_fbFriends.Clear();

        // Construct our friend list using response data
        JsonData jsonFriends = JsonMapper.ToObject(responseData)["data"]["friends"];

        for (int i = 0; i < jsonFriends.Count; ++i)
        {
            JsonData       jsonFriend = jsonFriends[i];
            FacebookFriend fbFriend   = new FacebookFriend();

            fbFriend.playerId   = (string)jsonFriend["playerId"];
            fbFriend.facebookId = (string)jsonFriend["externalData"]["Facebook"]["externalId"];
            fbFriend.name       = (string)jsonFriend["externalData"]["Facebook"]["name"];
            StartCoroutine(SetProfilePic((string)jsonFriend["externalData"]["Facebook"]["pictureUrl"], fbFriend));             // Load pic

            m_fbFriends.Add(fbFriend);
        }

        // After, fetch our game list from Braincloud
        BrainCloudWrapper.GetBC().GetAsyncMatchService().FindMatches(OnFindMatchesSuccess, null, null);
    }
Esempio n. 14
0
        public ActionResult Addinvitation(string id)
        {
            FacebookFriend fdto = null;

            if (tst == 1)
            {
                HttpContext.Session["fbidlist"] = null;
                fdto    = new FacebookFriend();
                fdto.id = id;
                lstdto.Add(fdto);
                HttpContext.Session["fbidlist"] = lstdto;
                tst++;
            }
            else
            {
                lstdto = HttpContext.Session["fbidlist"] as List <FacebookFriend>;

                fdto    = new FacebookFriend();
                fdto.id = id;
                lstdto.Add(fdto);
                HttpContext.Session["fbidlist"] = lstdto;
            }
            return(View());
        }
Esempio n. 15
0
        public async Task <IActionResult> FacebookLogin(string accessToken)
        {
            //korisnik mora biti tester da bi radilo, to se može postaviti na https://developers.facebook.com/
            //dodati povratnu vezu URL na stranicu https://developers.facebook.com/
            //treba ranije pozvati https://www.facebook.com/v2.11/dialog/oauth?&response_type=token&display=popup&client_id={_appSettings.FacebookAppId}&display=popup&redirect_uri={URL_ZA_POVRATNU_VEZU}&scope=email,user_birthday,user_friends
            //proslijediti ovoj metodi access token koji se dobije pozivanjem gornjeg url-a

            // 1.generate an app access token
            var appAccessTokenResponse =
                await _client.GetStringAsync(
                    $"https://graph.facebook.com/oauth/access_token?client_id={_appSettings.FacebookAppId}&client_secret={_appSettings.FacebookAppSecret}&grant_type=client_credentials");

            var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(appAccessTokenResponse);

            // 2. validate the user access token
            var userAccessTokenValidationResponse = await _client.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={accessToken}&access_token={appAccessToken.AccessToken}");

            var userAccessTokenValidation =
                JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse);

            if (!userAccessTokenValidation.Data.IsValid)
            {
                return(BadRequest("Invalid facebook token."));
            }

            // 3. we've got a valid token so we can request user data from fb
            var userInfoResponse = await _client.GetStringAsync($"https://graph.facebook.com/v2.8/me?fields=id,email,first_name,last_name,birthday,picture,friends&access_token={accessToken}");

            var userInfo = JsonConvert.DeserializeObject <FacebookUserData>(userInfoResponse);

            var facebookFriends = new List <FacebookFriend>();

            foreach (var item in userInfo.Friends.Data)
            {
                var friend = new FacebookFriend()
                {
                    FacebookId = item.Id,
                    Name       = item.Name
                };
                facebookFriends.Add(friend);
            }

            // 4. ready to create the local user account (if necessary) and jwt
            var user = _userService.GetByEmail(userInfo.Email);

            if (user == null)
            {
                var userIn = new User()
                {
                    FirstName       = userInfo.FirstName,
                    LastName        = userInfo.LastName,
                    Username        = userInfo.Email,
                    Email           = userInfo.Email,
                    DateOfBirth     = DateTime.Parse(userInfo.DateOfBirth, CultureInfo.InvariantCulture),
                    Image           = userInfo.Picture.Data.Url,
                    FacebookId      = userInfo.Id,
                    FacebookFriends = facebookFriends
                };

                _userService.RegisterFacebook(userIn);
                user = userIn;
            }
            else
            {
                var updateFlag = false;

                if (user.FacebookId == null)
                {
                    user.FacebookId = userInfo.Id;
                    updateFlag      = true;
                }

                foreach (var item in facebookFriends)
                {
                    if (user.FacebookFriends.Contains(item) == false)
                    {
                        user.FacebookFriends = facebookFriends;
                        updateFlag           = true;
                        break;
                    }
                }

                if (updateFlag)
                {
                    _userService.UpdateFacebookUser(user.Id, user);
                }
            }

            //var jwt = await Tokens.GenerateJwt(_jwtFactory.GenerateClaimsIdentity(localUser.Username, localUser.Id.ToString()),
            //    _jwtFactory, localUser.Username, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            // return basic user info (without password) and token to store client side
            return(Ok(new
            {
                Id = user.Id,
                Username = user.Username,
                FirstName = user.FirstName,
                LastName = user.LastName,
                Token = tokenString
            }));
        }
Esempio n. 16
0
	void OnPickOpponent(FacebookFriend fbFriend)
	{
		m_state = eState.STARTING_MATCH;
		bool yourTurnFirst = Random.Range(0, 100) < 50;

		// Setup our summary data. This is what we see when we query
		// the list of games. So we want to store information about our
		// facebook ids so we can lookup our friend's picture and name
		JsonData summaryData = new JsonData();
		summaryData["players"] = new JsonData();
		{
			// Us
			JsonData playerData = new JsonData();
			playerData["playerId"] = FacebookLogin.PlayerId;
			playerData["facebookId"] = FB.UserId;
			if (yourTurnFirst)
				playerData["token"] = "X"; // First player has X
			else
				playerData["token"] = "O";
			summaryData["players"].Add(playerData);
		}
		{
			// Our friend
			JsonData playerData = new JsonData();
			playerData["playerId"] = fbFriend.playerId;
			playerData["facebookId"] = fbFriend.facebookId;//fbFriend.facebookId;
			if (!yourTurnFirst)
				playerData["token"] = "X"; // First player has X
			else
				playerData["token"] = "O";
			summaryData["players"].Add(playerData);
		}

		// Setup our match State. We only store where Os and Xs are in
		// the tic tac toe board. 
		JsonData matchState = new JsonData();
		matchState["board"] = "#########"; // Empty the board. # = nothing, O,X = tokens

		// Setup our opponent list. In this case, we have just one opponent.
		//JsonData opponentIds = new JsonData();

		// Create the match
		BrainCloudWrapper.GetBC().AsyncMatchService.CreateMatchWithInitialTurn(
			"[{\"platform\":\"BC\",\"id\":\"" + fbFriend.playerId + "\"}]", 	// Opponents
			matchState.ToJson(),	// Current match state
			"A friend has challenged you to a match of Tic Tac Toe.",	// Push notification Message
			null,	// Match id. Keep empty, we let brainCloud generate one
			(yourTurnFirst) ? FacebookLogin.PlayerId : fbFriend.playerId, // Which turn it is. We picked randomly
			summaryData.ToJson(),	// Summary data
			OnCreateMatchSuccess,
			OnCreateMatchFailed,
			null);
	}
Esempio n. 17
0
	IEnumerator SetProfilePic(string url, FacebookFriend fbFriend)
	{
		fbFriend.picUrl = url;
		WWW www = new WWW(url);
		yield return www;
		fbFriend.pic = www.texture;
	}
Esempio n. 18
0
	void OnReadFriendData(string responseData, object cbPostObject) 
	{
		m_fbFriends.Clear();

		// Construct our friend list using response data
		JsonData jsonFriends = JsonMapper.ToObject(responseData)["data"]["friends"];
		for (int i = 0; i < jsonFriends.Count; ++i)
		{
			JsonData jsonFriend = jsonFriends[i];
			FacebookFriend fbFriend = new FacebookFriend();

			fbFriend.playerId = (string)jsonFriend["playerId"];
			fbFriend.facebookId = (string)jsonFriend["externalData"]["Facebook"]["externalId"];
			fbFriend.name = (string)jsonFriend["externalData"]["Facebook"]["name"];
			StartCoroutine(SetProfilePic((string)jsonFriend["externalData"]["Facebook"]["pictureUrl"], fbFriend)); // Load pic

			m_fbFriends.Add(fbFriend);
		}

		// After, fetch our game list from Braincloud
		BrainCloudWrapper.GetBC().GetAsyncMatchService().FindMatches(OnFindMatchesSuccess, null, null);
	}
Esempio n. 19
0
    void OnPickOpponent(FacebookFriend fbFriend)
    {
        m_state = eState.STARTING_MATCH;
        bool yourTurnFirst = Random.Range(0, 100) < 50;

        // Setup our summary data. This is what we see when we query
        // the list of games. So we want to store information about our
        // facebook ids so we can lookup our friend's picture and name
        JsonData summaryData = new JsonData();

        summaryData["players"] = new JsonData();
        {
            // Us
            JsonData playerData = new JsonData();
            playerData["playerId"]   = FacebookLogin.PlayerId;
            playerData["facebookId"] = FB.UserId;
            if (yourTurnFirst)
            {
                playerData["token"] = "X";                 // First player has X
            }
            else
            {
                playerData["token"] = "O";
            }
            summaryData["players"].Add(playerData);
        }
        {
            // Our friend
            JsonData playerData = new JsonData();
            playerData["playerId"]   = fbFriend.playerId;
            playerData["facebookId"] = fbFriend.facebookId;            //fbFriend.facebookId;
            if (!yourTurnFirst)
            {
                playerData["token"] = "X";                 // First player has X
            }
            else
            {
                playerData["token"] = "O";
            }
            summaryData["players"].Add(playerData);
        }

        // Setup our match State. We only store where Os and Xs are in
        // the tic tac toe board.
        JsonData matchState = new JsonData();

        matchState["board"] = "#########";         // Empty the board. # = nothing, O,X = tokens

        // Setup our opponent list. In this case, we have just one opponent.
        //JsonData opponentIds = new JsonData();

        // Create the match
        BrainCloudWrapper.GetBC().AsyncMatchService.CreateMatchWithInitialTurn(
            "[{\"platform\":\"BC\",\"id\":\"" + fbFriend.playerId + "\"}]", // Opponents
            matchState.ToJson(),                                            // Current match state
            "A friend has challenged you to a match of Tic Tac Toe.",       // Push notification Message
            null,                                                           // Match id. Keep empty, we let brainCloud generate one
            (yourTurnFirst) ? FacebookLogin.PlayerId : fbFriend.playerId,   // Which turn it is. We picked randomly
            summaryData.ToJson(),                                           // Summary data
            OnCreateMatchSuccess,
            OnCreateMatchFailed,
            null);
    }
	private IEnumerator BuildRank()
	{
		transform.FindChild("Loading").gameObject.SetActive(true);

		yield return StartCoroutine(DBHandler.GetTopUsers(value => topUsers = value));

		UIGrid grid = GetComponentInChildren<UIGrid>();
		
		for(byte i = 0; i < topUsers.Count; i++)
		{
			FacebookFriend user = topUsers[i];
			
			GameObject rank;
			if(user.rank == 1)
				rank = Instantiate(goldRank) as GameObject;
			else if(user.rank == 2)
				rank = Instantiate(silverRank) as GameObject;
			else if(user.rank == 3)
				rank = Instantiate(cooperRank) as GameObject;
			else
				rank = Instantiate(normalRank) as GameObject;
			
			UILabel nomeLabel = rank.transform.FindChild("Name").GetComponent<UILabel>();
			UILabel scoreLabel = rank.transform.FindChild("Score").GetComponent<UILabel>();
			UILabel rankLabel = rank.transform.FindChild("Rank").GetComponent<UILabel>();
			UITexture picture = rank.transform.FindChild("Picture").GetComponent<UITexture>();
			
			nomeLabel.text = user.name;
			scoreLabel.text = Localization.Get("SCORE") + ": " + user.score;
			rankLabel.text = "Rank #" + user.rank;
			StartCoroutine(LoadProfilePicture(user, picture));
			
			rank.transform.parent = grid.transform;
			rank.transform.localScale = Vector3.one;
		}

		bool isInTop10 = false;
		foreach(FacebookFriend topUser in topUsers)
		{
			if(topUser.id == FacebookController.User.id)
			{
				isInTop10 = true;
				break;
			}
		}

		if(!isInTop10)
		{
			FacebookFriend player = new FacebookFriend(FacebookController.User.id,
			                                           FacebookController.User.firstname + " " + FacebookController.User.lastname,
			                                           FacebookController.User.score,
			                                           FacebookController.User.rank);

			GameObject rank = Instantiate(normalRank) as GameObject;
			
			UILabel nomeLabel = rank.transform.FindChild("Name").GetComponent<UILabel>();
			UILabel scoreLabel = rank.transform.FindChild("Score").GetComponent<UILabel>();
			UILabel rankLabel = rank.transform.FindChild("Rank").GetComponent<UILabel>();
			UITexture picture = rank.transform.FindChild("Picture").GetComponent<UITexture>();
			
			nomeLabel.text = player.name;
			scoreLabel.text = Localization.Get("SCORE") + ": " + player.score;
			rankLabel.text = "Rank #" + player.rank;
			StartCoroutine(LoadProfilePicture(player, picture));
			
			rank.transform.parent = grid.transform;
			rank.transform.localScale = Vector3.one;
		}
		
		grid.GetComponent<UIGrid>().Reposition();

		transform.FindChild("Loading").gameObject.SetActive(false);
	}
Esempio n. 21
0
    // http://answers.unity3d.com/questions/959943/deserialize-facebook-friends-result.html
    void DisplayFriends(IResult result)
    {
        friendList.Clear();

        current = this;

        var dict = Json.Deserialize(result.RawResult) as Dictionary<string, object>;
        var theList = new List<object>();
        theList = (List<object>)(dict["data"]);

        int friendCount = theList.Count;
        
        for (int i = 0; i < friendCount; i++)
        {
            string friendFBID = GetDataValueForKey((Dictionary<string, object>)(theList[i]), "id");
            string first_name = GetDataValueForKey((Dictionary<string, object>)(theList[i]), "first_name");
            string last_name = GetDataValueForKey((Dictionary<string, object>)(theList[i]), "last_name");
            
            FacebookFriend fwend = new FacebookFriend();
            fwend.name = first_name + " " + last_name;
            fwend.id = friendFBID;

            current.friendList.Add(fwend);
        }

    }
Esempio n. 22
0
    // Use this for initialization
    void Start()
    {
        options = new Options();

        ConfirmationScript[] sdsdfd = GameObject.FindObjectsOfType<ConfirmationScript>();

        ticketQueue = new CustomerQueue(11, 38.5f, 6.8f, 0);

        #region Find Objects
        theTileManager = GameObject.Find("TileManagement").GetComponent<TileManager>();

        GameObject custStatus = GameObject.Find("Customer Status");
        movementScript.customerStatus = custStatus;
        GameObject[] tmpArray = GameObject.FindGameObjectsWithTag("Floor Tile");
        steps = GameObject.Find("Steps");
        mouseDrag.staffAttributePanel = GameObject.Find("Staff Attributes");
        #endregion

        Customer.tiles = floorTiles;

        #region Hide Objects on Start
        custStatus.SetActive(false);

        shopController.redCarpet.SetActive(false);
        mouseDrag.staffAttributePanel.SetActive(false);
        #endregion

        #region Add Delegate references
        mouseDrag.getStaffJobById += GetStaffJobById;
        mouseDrag.changeStaffJob += UpdateStaffJob;
        movementScript.addToQueueTickets += AddToQueueTickets;
        movementScript.getQueueTicketsSize += GetTicketQueueSize;
        movementScript.addToQueueFood += AddToQueueFood;
        movementScript.getQueueFoodSize += GetFoodQueueSize;
        #endregion

        #region Facebook stuff
        GameObject pnlNoFriends = GameObject.Find("pnlNoFriends");

        try
        {
            string fbUserID = FBScript.current.id;
            if (fbUserID.Length > 0)
            {
                cmdFriends.SetActive(true);
                facebookProfile = new FacebookFriend();
                facebookProfile.name = FBScript.current.firstname + " " + FBScript.current.surname;
                facebookProfile.id = FBScript.current.id;
                facebookProfile.friends = FBScript.current.friendList;

                if (facebookProfile.friends.Count > 0)
                {
                    pnlNoFriends.SetActive(false);
                }
                else
                {
                    pnlNoFriends.SetActive(true);
                }

                for (int i = 0; i < facebookProfile.friends.Count; i++)
                {
                    GameObject go = (GameObject)Instantiate(friendObject.gameObject, new Vector3(0, 0, 0), Quaternion.identity);
                    go.transform.SetParent(popupController.friendList, false);

                    Text[] textComponents = go.GetComponentsInChildren<Text>();
                    textComponents[0].text = facebookProfile.friends[i].name;

                    Button[] buttonComponents = go.GetComponentsInChildren<Button>();
                    string idToSend = facebookProfile.friends[i].id;
                    string nameToSend = facebookProfile.friends[i].name;
                    buttonComponents[0].onClick.AddListener(() => ViewFriendsCinema(idToSend, nameToSend));
                    buttonComponents[1].onClick.AddListener(() => ViewFriendsCinema(idToSend, nameToSend));

                }
            }
            else
            {
                pnlNoFriends.SetActive(true);
                // if the user has not logged into Facebook, hide the facebook friends button
                cmdFriends.SetActive(false);
            }
        }
        catch (Exception) { }
        #endregion

        // this will change depending on starting upgrade levels and other queues etc

        #region Load / New Game

        if (ButtonScript.friendData != null)
        {
            GameObject.Find("Bottom Panel").SetActive(false);
            GameObject.Find("lblOwnerName").GetComponent<Text>().text = ButtonScript.owner + "'s Cinema";
            ButtonScript.dataCopy = ButtonScript.loadGame;
            ButtonScript.loadGame = ButtonScript.friendData;
            ButtonScript.friendData = null;
        }
        else
        {
            GameObject.Find("FriendPanel").SetActive(false);
        }

        // get Player data. If not null, load game
        if (ButtonScript.loadGame == null)
        {
            financeController.Inititalise(45000, 4);

            carpetColour = GetColourFromID(1);

            customerController.reputation = new Reputation();
            customerController.reputation.Initialise();

            OtherObjectScript.CreateStaffSlot(1, new Vector3(37.8f, 12.3f, 0));

            #region Floor Tiles
            floorTiles = new GameObject[40, 80];

            // initialise the floor tiles
            for (int i = 0; i < tmpArray.Length; i++)
            {
                string name = tmpArray[i].name;

                string[] tmp = name.Split('~');
                int x = int.Parse(tmp[1]);
                int y = int.Parse(tmp[2]);

                tmpArray[i].GetComponent<SpriteRenderer>().color = carpetColour;
                tmpArray[i].GetComponent<SpriteRenderer>().sprite = ColourBackground;
                //tmpArray[i].GetComponent<SpriteRenderer>().sprite = profilePicture;   // for funny times, uncomment this line

                floorTiles[x, y] = tmpArray[i];
            }
            #endregion

            for (int i = 0; i < 1; i++)
            {
                Vector3 pos = floorTiles[i * 11, 0].transform.position;
                ShopController.theScreens.Add(new ScreenObject((i + 1), 0));
                ShopController.theScreens[i].SetPosition((int)pos.x, (int)pos.y);
            }
            ShopController.theScreens[0].Upgrade();
            ShopController.theScreens[0].UpgradeComplete();
            // NYAH

            NextDay(false, false);

            // do staff intro thing here
            popupController.ShowPopup(99, "Welcome!!! This is your cinema!\nLets get started by hiring some staff shall we?");

            foodArea = null;

        }
        else
        {
            statusCode = 0;

            PlayerData data = ButtonScript.loadGame;

            carpetColour = new Color(data.carpetColour[0], data.carpetColour[1], data.carpetColour[2]);

            shopController.LoadDecorations(data.hasRedCarpet, data.posters);

            isMarbleFloor = data.marbleFloor;
            customerController.reputation = data.reputation;
            foodArea = data.foodArea;

            options.Load(data.options);

            int boxLevel = data.boxOfficeLevel;
            OtherObjectScript.CreateStaffSlot(1, new Vector3(37.8f, 12.3f, 0));

            for (int i = 0; i < boxLevel - 1; i++)
            {
                OtherObjectScript.UpgradeBoxOffice();
            }

            #region Floor Tiles
            // initialise the floor tiles
            floorTiles = new GameObject[40, 80];

            for (int i = 0; i < tmpArray.Length; i++)
            {
                string name = tmpArray[i].name;

                string[] tmp = name.Split('~');
                int x = int.Parse(tmp[1]);
                int y = int.Parse(tmp[2]);

                tmpArray[i].GetComponent<SpriteRenderer>().color = carpetColour;
                if (!isMarbleFloor)
                {
                    tmpArray[i].GetComponent<SpriteRenderer>().sprite = ColourBackground;
                }
                else
                {
                    tmpArray[i].GetComponent<SpriteRenderer>().sprite = marbleSquares[UnityEngine.Random.Range(0, 3)];
                }

                floorTiles[x, y] = tmpArray[i];
            }
            #endregion

            ShopController.theScreens = new List<ScreenObject>(data.theScreens);

            SaveableStaff[] s = data.staffMembers;

            for (int i = 0; i < s.Length; i++)
            {
                int id = s[i].index;
                string name = s[i].name;
                Transform transform = staffPrefab;
                int dayHired = s[i].dayHired;
                int tID = s[i].transformID;
                int[] attributes = s[i].attributes;
                float[,] cols = s[i].colourArrays;
                int hair = s[i].hairStyleID;
                int extras = s[i].extrasID;

                GameObject go = GameObject.Find("AppearanceController");
                AppearanceScript aS = go.GetComponent<AppearanceScript>();

                Sprite hairSprite = null;
                Sprite extraSprite = null;

                if (hair != 9)
                {
                    hairSprite = aS.hairStyles[hair];
                }
                if (extras != 5)
                {
                    extraSprite = aS.extraImages[extras];
                }
                Color[] c = new Color[3];

                for (int colID = 0; colID < 3; colID++)
                {
                    c[colID] = new Color(cols[colID, 0], cols[colID, 1], cols[colID, 2]);
                }

                StaffMember newStaff = new StaffMember(id, name, transform, dayHired, tID, hairSprite);
                newStaff.SetColours(c, hair, extras);
                newStaff.SetSprites(hairSprite, extraSprite);
                newStaff.SetAttributes(attributes);

                int x = 35 + (2 * (newStaff.GetIndex() % 6)); ;
                int y = 2 * (newStaff.GetIndex() / 6);

                staffMembers.Add(newStaff);
                CreateStaff(newStaff, x, y);
            }

            filmShowings = new List<FilmShowing>(data.filmShowings);
            currDay = data.currentDay;
            numScreens = ShopController.theScreens.Count;
            financeController.Inititalise(data.totalCoins, data.numPopcorn);
            ShopController.otherObjects = new List<OtherObject>(data.otherObjects);

            NextDay(false, false);
            currDay--; // needed for some reason

            // hopefully un-breaks things
            for (int i = 0; i < ShopController.theScreens.Count; i++)
            {
                Vector3 pos = new Vector3(ShopController.theScreens[i].GetX(), ShopController.theScreens[i].GetY(), 0);
                ShopController.theScreens[i].SetPosition((int)pos.x, (int)(pos.y));
            }

            // sort staff appearance
            GameObject[] staffs = GameObject.FindGameObjectsWithTag("Staff");
            for (int i = 0; i < staffs.Length; i++)
            {
                SpriteRenderer[] srs = staffs[i].GetComponentsInChildren<SpriteRenderer>();
                srs[0].color = staffMembers[i].GetColourByIndex(0);
                srs[1].color = staffMembers[i].GetColourByIndex(2);
                srs[2].color = staffMembers[i].GetColourByIndex(2);
                srs[3].color = staffMembers[i].GetColourByIndex(1);
                srs[4].color = staffMembers[i].GetColourByIndex(1);

                srs[3].sprite = staffMembers[i].GetHairStyle();
                srs[4].sprite = staffMembers[i].GetExtras();
            }

            shopController.ShowPosters(0);
            shopController.ShowPosters(1);

            if (popcornSpent > 0)
            {
                financeController.RemovePopcorn(Controller.popcornSpent);
                financeController.popcornLabel.text = financeController.GetNumPopcorn().ToString();
                Controller.popcornSpent = 0;
                DoAutosave();
            }

            string fbID = FBScript.current.id;

            try
            {
                if (isOwned)
                {
                    Gifting g = new Gifting();
                    List<String> gifts = g.GetGifts(fbID);

                    if (gifts.Count > 0)
                    {

                        List<int> counts = new List<int>();
                        List<string> names = new List<string>();

                        // group together - i.e. Susan McDonaldman: 3
                        for (int i = 0; i < gifts.Count; i++)
                        {

                            bool found = false;

                            for (int checkLoop = 0; checkLoop < names.Count; checkLoop++)
                            {
                                if (names[checkLoop].Equals(gifts[i]))
                                {
                                    found = true;
                                    counts[checkLoop]++;
                                    break;
                                }
                            }

                            if (!found)
                            {
                                names.Add(gifts[i]);
                                counts.Add(1);
                            }
                        }

                        financeController.AddPopcorn(gifts.Count);

                        for (int i = 0; i < names.Count; i++)
                        {
                            // add the element / objects
                            Transform t = Instantiate(giftObject, new Vector2(0, 0), Quaternion.identity) as Transform;
                            // set parent to the element container

                            Transform giftContainer = GameObject.Find("GiftContainer").transform;

                            t.SetParent(giftContainer);
                            // change the values
                            Text[] txts = t.GetComponentsInChildren<Text>();
                            txts[0].text = names[i];
                            txts[1].text = counts[i].ToString();
                        }

                        // show the popup
                        GameObject giftPanel = GameObject.Find("GiftList");
                        giftPanel.GetComponent<Canvas>().enabled = true;

                        DoAutosave();

                    }

                }
            }
            catch (Exception)
            {
                popupController.ShowPopup(0, "Error getting Gifts");
            }
        }

        #endregion

        // create some test screens
        for (int i = 0; i < ShopController.theScreens.Count; i++)
        {
            Vector3 pos = new Vector3(ShopController.theScreens[i].GetX(), ShopController.theScreens[i].GetY() * 0.8f, 0);

            // change pos and element here
            pos.y += 0.8f;

            shopController.AddScreen(ShopController.theScreens[i], pos, height);

            SetTiles(2, (int)(ShopController.theScreens[i].GetX()), (int)(ShopController.theScreens[i].GetY()), 11, 15);
        }

        // do same for other objects
        for (int i = 0; i < ShopController.otherObjects.Count; i++)
        {
            Vector3 pos = new Vector3(ShopController.otherObjects[i].xPos, ShopController.otherObjects[i].yPos * 0.8f, 0);

            DimensionTuple t = shopController.GetBounds(ShopController.otherObjects[i].type);

            shopController.AddObject(pos, i, height, ShopController.otherObjects[i].type, true);

            SetTiles(2, (int)(ShopController.otherObjects[i].xPos), (int)(ShopController.otherObjects[i].yPos), t.width, t.height);
        }

        //createColourPicker();

        if (updateTileState != null)
        {
            updateTileState(33, 0, 14, 16, 1, true);
            updateTileState(33, 16, 14, 4, 2, true);
        }

        GameObject[] pointers = GameObject.FindGameObjectsWithTag("Pointer");

        for (int i = 0; i < pointers.Length; i++)
        {
            pointers[i].GetComponent<Transform>().GetComponent<SpriteRenderer>().enabled = false;
        }

        dayLabel.text = "DAY: " + currDay.ToString();

        // create staff slots for food area if not null
        if (foodArea != null)
        {
            GameObject go = GameObject.FindGameObjectWithTag("Food Area");
            Vector2 pos = go.transform.position;

            for (int i = 0; i < foodArea.tableStatus + 1; i++) {
                OtherObjectScript.CreateStaffSlot(2, pos + new Vector2(3 + (2.5f * i), 7.95f));
            }

            if (foodArea.tableStatus == 1)
            {
                foodQueue.Upgrade();
            }
        }

        NewShowTimes();
    }
Esempio n. 23
0
        public async Task <List <FacebookFriend> > Friends(string token, string nextPageToken = "")
        {
            List <FacebookFriend> rs   = new List <FacebookFriend>();
            List <Parameter>      para = this.DefaultParamater(HttpMethod.Get, token);

            para.Add(new Parameter()
            {
                Name  = "fields",
                Value = "name"
            });
            if (!string.IsNullOrEmpty(nextPageToken))
            {
                List <Parameter> parameterList1 = para;
                Parameter        parameter1     = new Parameter();
                parameter1.Name = "after";
                string str = nextPageToken;
                parameter1.Value = str;
                parameterList1.Add(parameter1);
                List <Parameter> parameterList2 = para;
                Parameter        parameter2     = new Parameter();
                parameter2.Name  = "limit";
                parameter2.Value = 20;
                parameterList2.Add(parameter2);
            }
            FacebookFriendData facebookFriendData = await this._webApiHelper.GetAsync <FacebookFriendData>(this.GraphUrl, "me/friends", para, "");

            FacebookFriendData friends             = facebookFriendData;
            FacebookFriendData facebookFriendData1 = friends;

            if (facebookFriendData1?.Data == null)
            {
                return(rs);
            }
            foreach (FacebookFriend facebookFriend in friends.Data)
            {
                FacebookFriend friend = facebookFriend;
                friend.Avatar = $"{GraphUrl}/{ friend.Id}/picture";
                rs.Add(friend);
            }
            FacebookPagingData paging = friends.Paging;
            string             str1;

            if (paging == null)
            {
                str1 = null;
            }
            else
            {
                FacebookPagingCursorData cursors = paging.Cursors;
                str1 = cursors != null ? cursors.After : (string)null;
            }
            if (!string.IsNullOrEmpty(str1))
            {
                List <FacebookFriend> facebookFriendList1 = rs;
                List <FacebookFriend> facebookFriendList2 = await this.Friends(token, friends.Paging.Cursors.After);

                IEnumerable <FacebookFriend> collection = (IEnumerable <FacebookFriend>)facebookFriendList2;
                facebookFriendList1.AddRange(collection);
            }
            return(rs);
        }