<commit_before>﻿using Facebook;
using JustPressPlay.Models;
using JustPressPlay.Models.Repositories;
using JustPressPlay.Utilities;
using JustPressPlay.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;

namespace JustPressPlay.Controllers
{
    public class SettingsController : Controller
    {
        // TODO: Move to site settings DB once implemented
        string appId = "295662587237899";
        string appSecret = "2456db6dc3c7c0e8e76913ab6d6e1028"; // TODO: RESET IF COMMITTED TO GIT!

        /// <summary>
        /// A player's settings
        /// </summary>
        /// <returns>GET: /Settings</returns>
        public ActionResult Index()
        {
            UserSettingsViewModel model = UserSettingsViewModel.Populate(WebSecurity.CurrentUserId);
            return View(model);
        }

        /*
        [HttpGet]
        public ActionResult ConnectFacebook()
        {
            FacebookConnectionViewModel model = new FacebookConnectionViewModel();
            return View(model);
        }*/

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ConnectFacebook(FacebookConnectionViewModel model)
        {
            // Save user settings to db
            using (UnitOfWork work = new UnitOfWork())
            {
                user currentUser = work.UserRepository.GetUser(WebSecurity.CurrentUserId);
                work.UserRepository.AddOrUpdateFacebookSettings(currentUser, model.NotificationsEnabled, model.AutomaticSharingEnabled);
                work.SaveChanges();
            }

            // Redirect to Facebook to ask for permissions
            string redirectAfterLoginUri = JppUriInfo.GetCurrentDomain(Request) + "/Settings/ProcessFacebookLogin"; // TODO: generate dynamically?
            string scope = string.Empty; // NOTE: No change in scope needed for notifications; apps don't need to ask permission
            if (model.AutomaticSharingEnabled)
            {
                scope += "publish_actions,";
            }
            string fbRedirectUrl = string.Format("https://www.facebook.com/dialog/oauth"
                                                 + "?client_id={0}"
                                                 + "&redirect_uri={1}",
                                                 appId, redirectAfterLoginUri); // TODO: state, response_type: https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/
            Response.Redirect(fbRedirectUrl);

            // Shouldn't ever get here; if we do, re-show the form
            return View(model);
        }

        [HttpGet]
        public string ProcessFacebookLogin()
        {
            if (Request.QueryString["error"] != null)
                return "An error occurred :("; // TODO: More robust error handling

            // Exchange code for an access token
            string code = Request.QueryString["code"];
            // Redirect to Facebook to ask for permissions
            string redirectAfterLoginUri = JppUriInfo.GetCurrentDomain(Request) + "/Settings/ProcessFacebookLogin"; // TODO: generate dynamically?
            object accessTokenGetParams = new
            {
                client_id = appId,
                redirect_uri = redirectAfterLoginUri,
                client_secret = appSecret,
                code = code
            };

            var fbClient = new FacebookClient();
            dynamic getAccessTokenResult = fbClient.Get("/oauth/access_token", accessTokenGetParams);<commit_msg>Facebook redirect URL is now generated dynamically rather than statically linking back to "/Settings/ProcessFacebookLogin"<commit_after>﻿using Facebook;
using JustPressPlay.Models;
using JustPressPlay.Models.Repositories;
using JustPressPlay.Utilities;
using JustPressPlay.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;

namespace JustPressPlay.Controllers
{
    public class SettingsController : Controller
    {
        // TODO: Move to site settings DB once implemented
        string appId = "295662587237899";
        string appSecret = "2456db6dc3c7c0e8e76913ab6d6e1028"; // TODO: RESET IF COMMITTED TO GIT!

        /// <summary>
        /// A player's settings
        /// </summary>
        /// <returns>GET: /Settings</returns>
        public ActionResult Index()
        {
            UserSettingsViewModel model = UserSettingsViewModel.Populate(WebSecurity.CurrentUserId);
            return View(model);
        }

        /*
        [HttpGet]
        public ActionResult ConnectFacebook()
        {
            FacebookConnectionViewModel model = new FacebookConnectionViewModel();
            return View(model);
        }*/

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ConnectFacebook(FacebookConnectionViewModel model)
        {
            // Save user settings to db
            using (UnitOfWork work = new UnitOfWork())
            {
                user currentUser = work.UserRepository.GetUser(WebSecurity.CurrentUserId);
                work.UserRepository.AddOrUpdateFacebookSettings(currentUser, model.NotificationsEnabled, model.AutomaticSharingEnabled);
                work.SaveChanges();
            }

            // Redirect to Facebook to ask for permissions
            string redirectAfterLoginUri = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("Default", new { Controller = "Settings", Action = "ProcessFacebookLogin" });
            string scope = string.Empty; // NOTE: No change in scope needed for notifications; apps don't need to ask permission
            if (model.AutomaticSharingEnabled)
            {
                scope += "publish_actions,";
            }
            string fbRedirectUrl = string.Format("https://www.facebook.com/dialog/oauth"
                                                 + "?client_id={0}"
                                                 + "&redirect_uri={1}",
                                                 appId, redirectAfterLoginUri); // TODO: state, response_type: https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/
            Response.Redirect(fbRedirectUrl);

            // Shouldn't ever get here; if we do, re-show the form
            return View(model);
        }

        [HttpGet]
        public string ProcessFacebookLogin()
        {
            if (Request.QueryString["error"] != null)
                return "An error occurred :("; // TODO: More robust error handling

            // Exchange code for an access token
            string code = Request.QueryString["code"];
            // Redirect to Facebook to ask for permissions
            string redirectAfterLoginUri = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("Default", new { Controller = "Settings", Action = "ProcessFacebookLogin" });
            object accessTokenGetParams = new
            {
                client_id = appId,
                redirect_uri = redirectAfterLoginUri,
                client_secret = appSecret,
                code = code
            };

            var fbClient = new FacebookClient();
            dynamic getAccessTokenResult = fbClient.Get("/oauth/access_token", accessTokenGetParams);
{'fraction_non_alphanumeric': 0.08612960195625595, 'fraction_numerical': 0.010052981931802743, 'mean_word_length': 2.047185430463576, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 40, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1461305', 'n_tokens_mistral': 1829, 'n_tokens_neox': 1732, 'n_words': 442}