Example #1
0
 public InternalController(RoomService roomService, ILogger <InternalController> logger, SpotifyAccessService spotifyAccessService, DevicePersistenceService devicePersistenceService)
 {
     _roomService              = roomService;
     _logger                   = logger;
     _spotifyAccessService     = spotifyAccessService;
     _devicePersistenceService = devicePersistenceService;
 }
Example #2
0
 public RoomService(IHubContext <RoomHub, IRoomHubInterface> roomHubContext, ILogger <RoomService> logger, ILoggerFactory loggerFactory, SpotifyAccessService spotifyAccessService)
 {
     _roomHubContext       = roomHubContext;
     this._logger          = logger;
     _loggerFactory        = loggerFactory;
     _spotifyAccessService = spotifyAccessService;
     _rooms           = new Dictionary <string, PartyRoom>();
     _memberRoomCache = new Dictionary <string, PartyRoom>();
 }
Example #3
0
 public RoomService(IHubContext <RoomHub, IRoomHubInterface> roomHubContext, ILogger <RoomService> logger, ILoggerFactory loggerFactory, SpotifyAccessService spotifyAccessService,
                    UserScoreService userScoreService, StatisticsService statisticsService, DevicePersistenceService devicePersistenceService)
 {
     _roomHubContext           = roomHubContext;
     _logger                   = logger;
     _loggerFactory            = loggerFactory;
     _spotifyAccessService     = spotifyAccessService;
     _userScoreService         = userScoreService;
     _statisticsService        = statisticsService;
     _devicePersistenceService = devicePersistenceService;
     _rooms           = new Dictionary <string, PartyRoom>();
     _memberRoomCache = new Dictionary <string, PartyRoom>();
 }
Example #4
0
        public PartyRoom(string roomId, ILogger logger, SpotifyAccessService spotifyAccessService)
        {
            _logger = logger;
            _spotifyAccessService = spotifyAccessService;
            RoomId          = roomId;
            _members        = new List <RoomMember>();
            _roomEvents     = new List <IRoomEvent>();
            _timeSinceEmpty = CustomFutureDateTimeOffset;

            _handledUntil    = DateTimeOffset.Now;
            _currentDjNumber = -1;
            _currentTrack    = null;
            CurrentRoomState = new RoomState();
        }
Example #5
0
        public PartyRoom(string roomId, ILogger logger, SpotifyAccessService spotifyAccessService, UserScoreService userScoreService)
        {
            _logger = logger;
            _spotifyAccessService = spotifyAccessService;
            _userScoreService     = userScoreService;
            RoomId          = roomId;
            _members        = new List <RoomMember>();
            _roomEvents     = new List <IRoomEvent>();
            _timeSinceEmpty = _customFutureDateTimeOffset;
            _roomRetries    = new List <Func <Task> >();

            _handledUntil    = DateTimeOffset.Now;
            _currentDjNumber = -1;
            _currentTrack    = null;
            CurrentRoomState = new RoomState();

            UpdateReactionTotals(false);
        }
Example #6
0
        public PartyRoom(string roomId, ILogger logger, SpotifyAccessService spotifyAccessService, UserScoreService userScoreService, StatisticsService statisticsService, DevicePersistenceService devicePersistenceService)
        {
            _logger = logger;
            _spotifyAccessService     = spotifyAccessService;
            _userScoreService         = userScoreService;
            _statisticsService        = statisticsService;
            _devicePersistenceService = devicePersistenceService;
            RoomId      = roomId;
            _members    = new List <RoomMember>();
            _roomEvents = new List <IRoomEvent>();
            _timeSinceLastSongPlayed = DateTimeOffset.Now;
            _roomRetries             = new List <Func <Task> >();

            _handledUntil    = DateTimeOffset.Now;
            _currentDjNumber = -1;
            _currentTrack    = null;
            CurrentRoomState = new RoomState();

            UpdateReactionTotals(false);
        }
Example #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <AppDbContext>(options =>
            {
                options.UseSqlite("Data Source=pugetsound.sqlite");
            });

            services.AddSingleton <UserScoreService>();
            services.AddSingleton <RoomService>();

            services.AddControllersWithViews(configure =>
            {
                configure.Conventions.Add(new RouteTokenTransformerConvention(new LowerCaseParameterTransformer()));
            });

            services.AddSignalR();

            services.AddSingleton(serviceProvider =>
            {
                var logger = serviceProvider.GetService <ILogger <SpotifyAccessService> >();
                var sas    = new SpotifyAccessService(logger);
                sas.SetAccessKeys(Configuration["SpotifyClientId"], Configuration["SpotifyClientSecret"]);
                return(sas);
            });

            services.AddAuthentication(o => o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.Events = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = async context =>
                    {
                        var sas = context.HttpContext.RequestServices.GetService <SpotifyAccessService>();

                        //check to see if user is authenticated first
                        if (context.Principal.Identity.IsAuthenticated)
                        {
                            try
                            {
                                /*
                                 * big thanks to https://stackoverflow.com/questions/52175302/handling-expired-refresh-tokens-in-asp-net-core
                                 * see https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
                                 * could be useful to debug https://stackoverflow.com/questions/18924996/logging-request-response-messages-when-using-httpclient
                                 */

                                //get the users tokens
                                var tokens       = context.Properties.GetTokens().ToList();
                                var refreshToken = tokens.First(t => t.Name == "refresh_token");
                                var accessToken  = tokens.First(t => t.Name == "access_token");
                                var exp          = tokens.First(t => t.Name == "expires_at");
                                var expires      = DateTime.Parse(exp.Value);

                                //check to see if the token has expired
                                if (expires < DateTime.Now)
                                {
                                    //token is expired, let's attempt to renew
                                    var tokenResponse = await sas.TryRefreshTokenAsync(refreshToken.Value);

                                    //set new token values
                                    if (string.IsNullOrWhiteSpace(tokenResponse.refresh_token))
                                    {
                                        refreshToken.Value = tokenResponse.refresh_token;
                                    }
                                    accessToken.Value = tokenResponse.access_token;

                                    //set new expiration date
                                    var newExpires = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResponse.expires_in);
                                    exp.Value      = newExpires.ToString("o", CultureInfo.InvariantCulture);

                                    //set tokens in auth properties
                                    context.Properties.StoreTokens(tokens);

                                    //trigger context to renew cookie with new token values
                                    context.ShouldRenew = true;
                                }

                                // set new api
                                sas.StoreMemberApi(context.Principal.Claims.GetSpotifyUsername(), accessToken.Value.FromAccessToken(), expires);

                                // store latest tokens
                                sas.StoreToken(context.Principal.Claims.GetSpotifyUsername(), refreshToken.Value);
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine(e);
                                context.RejectPrincipal();
                            }
                        }
                    }
                };
            })
            .AddSpotify(options =>
            {
                var scopes = Scope.AppRemoteControl
                             | Scope.UserReadPlaybackState
                             | Scope.UserModifyPlaybackState
                             | Scope.PlaylistModifyPrivate
                             | Scope.PlaylistReadPrivate
                             | Scope.PlaylistModifyPublic
                             | Scope.PlaylistReadCollaborative
                             | Scope.UserLibraryRead
                             | Scope.UserLibraryModify
                             | Scope.UserReadPrivate
                             | Scope.UserReadCurrentlyPlaying;
                options.Scope.Add(scopes.GetStringAttribute(","));
                options.ClientId                = Configuration["SpotifyClientId"];
                options.ClientSecret            = Configuration["SpotifyClientSecret"];
                options.CallbackPath            = "/callback";
                options.Events.OnRemoteFailure  = context => Task.CompletedTask;  // TODO handle rip
                options.SaveTokens              = true;
                options.Events.OnTicketReceived = context => Task.CompletedTask;  // maybe add log?
                options.Events.OnCreatingTicket = context =>
                {
                    var username = context.Principal.Claims.GetSpotifyUsername();
                    var sas      = context.HttpContext.RequestServices.GetService <SpotifyAccessService>();
                    sas.StoreToken(username, context.RefreshToken);
                    sas.StoreMemberApi(username, context.AccessToken.FromAccessToken());
                    return(Task.CompletedTask);
                };
            });
        }
 public InternalController(RoomService roomService, ILogger <InternalController> _logger, SpotifyAccessService spotifyAccessService)
 {
     _roomService          = roomService;
     this._logger          = _logger;
     _spotifyAccessService = spotifyAccessService;
 }