Esempio n. 1
0
        public JsonResult GetGamesList(string letter)
        {
            string        search    = letter.ToLower();
            List <string> gameNames = new List <string>();

            using (BacklogDataContext db = new BacklogDataContext())
            {
                List <Game> games = db.Games.AsNoTracking().Where(m => m.Name.ToLower().StartsWith(search)).ToList();

                for (int i = 0; i < games.Count; i++)
                {
                    gameNames.Add(games[i].Name);
                }

                string gamesList = JsonConvert.SerializeObject(gameNames);


                return(Json(gamesList, JsonRequestBehavior.AllowGet));
            }
        }
Esempio n. 2
0
        public JsonResult CompletedGame(int gameId, bool completed)
        {
            string user = User.Identity.Name;

            using (BacklogDataContext db = new BacklogDataContext())
            {
                Backlog backloggedGame = db.Backlogs.FirstOrDefault(m => m.UserName == user && m.GameId == gameId);

                Backlog updatedEntry = new Backlog();
                updatedEntry.UserName        = user;
                updatedEntry.GameId          = gameId;
                updatedEntry.Completed_Game  = completed;
                updatedEntry.Platinum_Status = backloggedGame.Platinum_Status;
                updatedEntry.PlayTime        = backloggedGame.PlayTime;
                updatedEntry.InsertionTime   = DateTime.Now;

                db.Backlogs.Remove(backloggedGame);
                db.Backlogs.Add(updatedEntry);
                db.SaveChanges();

                return(Json("{\"success\": true}", JsonRequestBehavior.AllowGet));
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Inserts a game into a person's Google Calendar.
        /// </summary>
        private void AddCalendarEvent(CalendarService service, Schedule schedule, Game game)
        {
            int    gameId = game.Id;
            string user   = User.Identity.Name;

            // Get gamelogger calendar or make one if it doesn't exist
            IList <CalendarListEntry> calendars = service.CalendarList.List().Execute().Items;

            // Delete previous calendar and create a new one
            for (int i = 0; i < calendars.Count; i++)
            {
                if (calendars[i].Summary == "GameLogger")
                {
                    service.Calendars.Delete(calendars[i].Id).Execute();
                }
            }

            // Create new calendar
            Calendar calendar = new Calendar();

            calendar.Summary  = "GameLogger";
            calendar.TimeZone = "America/New_York";

            var    newCal = service.Calendars.Insert(calendar).Execute();
            string calId  = newCal.Id;

            // Insert event
            EventsResource eventRes = new EventsResource(service);

            Event calEvent = new Event();

            EventDateTime Start = new EventDateTime();
            EventDateTime End   = new EventDateTime();

            double gameLength = game.Main_Story_Length;

            int currPlayTime = 0;

            // If game does not have a length specified in the database then assume it will take 12 hours to beat.
            if (gameLength <= 0)
            {
                gameLength = 12;
            }

            // Get user's current playtime on the game and subtract the game's length from the playtime
            using (BacklogDataContext blDb = new BacklogDataContext())
            {
                Backlog bl = blDb.Backlogs.First(m => m.GameId == gameId && m.UserName == user);

                if (bl != null)
                {
                    currPlayTime = ((int)bl.PlayTime / 60);
                }
            }

            gameLength -= (currPlayTime);

            int daysToFinish = (int)Math.Ceiling(gameLength / 8);

            List <int> freeDays = new List <int>();

            // Get free days. TODO: make this less messy
            if (schedule.Monday == true)
            {
                freeDays.Add(1);
            }
            if (schedule.Tuesday == true)
            {
                freeDays.Add(2);
            }
            if (schedule.Wednesday == true)
            {
                freeDays.Add(3);
            }
            if (schedule.Thursday == true)
            {
                freeDays.Add(4);
            }
            if (schedule.Friday == true)
            {
                freeDays.Add(5);
            }
            if (schedule.Saturday == true)
            {
                freeDays.Add(6);
            }
            if (schedule.Sunday == true)
            {
                freeDays.Add(7);
            }

            int weekOffset = 0;

            // Find the next available day to play
            if (freeDays.Count > 0)
            {
                for (int x = 0; x < daysToFinish; x++)
                {
                    // Set start date. TODO: make this less messy
                    for (int i = 0; i < freeDays.Count; i++)
                    {
                        // Set event times
                        if (freeDays[i] == 1)
                        {
                            DateTime today         = DateTime.Today;
                            int      daysUntilNext = ((int)DayOfWeek.Monday - (int)today.DayOfWeek + 7) % 7;
                            DateTime next          = today.AddDays(daysUntilNext + (weekOffset * 7));
                            Start.Date = next.ToString("yyyy-MM-dd");
                            End.Date   = Start.Date;
                            daysToFinish--;
                        }
                        else if (freeDays[i] == 2)
                        {
                            DateTime today         = DateTime.Today;
                            int      daysUntilNext = ((int)DayOfWeek.Tuesday - (int)today.DayOfWeek + 7) % 7;
                            DateTime next          = today.AddDays(daysUntilNext + (weekOffset * 7));
                            Start.Date = next.ToString("yyyy-MM-dd");
                            End.Date   = Start.Date;
                            daysToFinish--;
                        }
                        else if (freeDays[i] == 3)
                        {
                            DateTime today         = DateTime.Today;
                            int      daysUntilNext = ((int)DayOfWeek.Wednesday - (int)today.DayOfWeek + 7) % 7;
                            DateTime next          = today.AddDays(daysUntilNext + (weekOffset * 7));
                            Start.Date = next.ToString("yyyy-MM-dd");
                            End.Date   = Start.Date;
                            daysToFinish--;
                        }
                        else if (freeDays[i] == 4)
                        {
                            DateTime today         = DateTime.Today;
                            int      daysUntilNext = ((int)DayOfWeek.Thursday - (int)today.DayOfWeek + 7) % 7;
                            DateTime next          = today.AddDays(daysUntilNext + (weekOffset * 7));
                            Start.Date = next.ToString("yyyy-MM-dd");
                            End.Date   = Start.Date;
                            daysToFinish--;
                        }
                        else if (freeDays[i] == 5)
                        {
                            DateTime today         = DateTime.Today;
                            int      daysUntilNext = ((int)DayOfWeek.Friday - (int)today.DayOfWeek + 7) % 7;
                            DateTime next          = today.AddDays(daysUntilNext + (weekOffset * 7));
                            Start.Date = next.ToString("yyyy-MM-dd");
                            End.Date   = Start.Date;
                            daysToFinish--;
                        }
                        else if (freeDays[i] == 6)
                        {
                            DateTime today         = DateTime.Today;
                            int      daysUntilNext = ((int)DayOfWeek.Saturday - (int)today.DayOfWeek + 7) % 7;
                            DateTime next          = today.AddDays(daysUntilNext + (weekOffset * 7));
                            Start.Date = next.ToString("yyyy-MM-dd");
                            End.Date   = Start.Date;
                            daysToFinish--;
                        }
                        else if (freeDays[i] == 7)
                        {
                            DateTime today         = DateTime.Today;
                            int      daysUntilNext = ((int)DayOfWeek.Sunday - (int)today.DayOfWeek + 7) % 7;
                            DateTime next          = today.AddDays(daysUntilNext + (weekOffset * 7));
                            Start.Date = next.ToString("yyyy-MM-dd");
                            End.Date   = Start.Date;
                            daysToFinish--;
                        }

                        // Set event information and insert
                        calEvent.Summary     = "GameLogger";
                        calEvent.Start       = Start;
                        calEvent.End         = End;
                        calEvent.ColorId     = "3";
                        calEvent.Description = "Playing " + game.Name;

                        // Insert event
                        eventRes.Insert(calEvent, calId).Execute();

                        if (daysToFinish <= 0)
                        {
                            break;
                        }
                    }

                    weekOffset++;
                }
            }
        }
Esempio n. 4
0
        public JsonResult GetBacklogInfo()
        {
            string user = User.Identity.Name;

            List <BackloggedGame> backloggedGames = new List <BackloggedGame>();
            List <Backlog>        backlogs        = new List <Backlog>();
            List <Game>           games           = new List <Game>();
            BackloggedGame        currPlaying     = new BackloggedGame();

            using (BacklogDataContext db = new BacklogDataContext())
            {
                // Select all games in a user's backlog
                backlogs = db.Backlogs.AsNoTracking().Where(m => m.UserName == user).ToList();

                if (backlogs.Count > 0)
                {
                    games = db.Games.AsNoTracking().ToList();

                    for (int i = 0; i < backlogs.Count; i++)
                    {
                        // Get game information
                        int  gameid = backlogs[i].GameId;
                        Game game   = games.First(m => m.Id == gameid);

                        // Pass all game and backlog information into new object
                        BackloggedGame backloggedGame = new BackloggedGame();
                        backloggedGame.Id                  = game.Id;
                        backloggedGame.Name                = game.Name;
                        backloggedGame.BoxArt              = game.Box_Art;
                        backloggedGame.DetailsUrl          = game.Details_Url;
                        backloggedGame.MainStoryLength     = game.Main_Story_Length;
                        backloggedGame.MainExtraLength     = game.Main_Extra_Length;
                        backloggedGame.CompletionistLength = game.Completionist_Length;
                        backloggedGame.CombinedLength      = game.Combined_Length;
                        backloggedGame.ReviewScore         = game.IGDB_Review_Score;
                        backloggedGame.CompletedGame       = backlogs[i].Completed_Game;
                        backloggedGame.PlatinumStatus      = backlogs[i].Platinum_Status;
                        backloggedGame.PlayTime            = backlogs[i].PlayTime;

                        backloggedGames.Add(backloggedGame);
                    }

                    if (games.Count == 0)
                    {
                        return(Json("{\"success\": false}", JsonRequestBehavior.AllowGet));
                    }
                }
                else
                {
                    return(Json("{\"success\": false}", JsonRequestBehavior.AllowGet));
                }
            }

            // Get game user is currently playing TODO: make this less messy
            using (PlayingDataContext db = new PlayingDataContext())
            {
                PlayedGame playing = db.PlayedGames.FirstOrDefault(m => m.UserName == user);

                if (playing != null)
                {
                    for (int i = 0; i < games.Count; i++)
                    {
                        if (games[i].Id == playing.GameId)
                        {
                            BackloggedGame newGame = new BackloggedGame();
                            newGame.Id                  = games[i].Id;
                            newGame.Name                = games[i].Name;
                            newGame.BoxArt              = games[i].Box_Art;
                            newGame.DetailsUrl          = games[i].Details_Url;
                            newGame.MainStoryLength     = games[i].Main_Story_Length;
                            newGame.MainExtraLength     = games[i].Main_Extra_Length;
                            newGame.CompletionistLength = games[i].Completionist_Length;
                            newGame.CombinedLength      = games[i].Combined_Length;
                            newGame.ReviewScore         = games[i].IGDB_Review_Score;

                            currPlaying = newGame;
                        }
                    }

                    for (int i = 0; i < backlogs.Count; i++)
                    {
                        if (currPlaying.Id == backlogs[i].GameId)
                        {
                            currPlaying.CompletedGame  = backlogs[i].Completed_Game;
                            currPlaying.PlatinumStatus = backlogs[i].Platinum_Status;
                            currPlaying.PlayTime       = backlogs[i].PlayTime;
                        }
                    }
                }
            }

            // Backlog statistics
            double backlogLength  = 0;
            int    currGameLength = (int)currPlaying.MainStoryLength;

            if (currGameLength < 0)
            {
                currGameLength = 12;
            }

            // Percentage statistics
            int    numCompleted                = 0;
            double percentageCompleted         = 0;
            double percentageCompletedCurrGame = 0;

            // General game statistics
            int numShortGames = 0;
            int numMedGames   = 0;
            int numLongGames  = 0;

            for (int i = 0; i < backloggedGames.Count; i++)
            {
                double gameLength = backloggedGames[i].MainStoryLength;

                // If game doesn't have a length listed in the database, assume it will take 12 hours to finish
                if (gameLength < 0)
                {
                    gameLength = 12;
                }

                // Get number of completed games
                if (backloggedGames[i].CompletedGame)
                {
                    numCompleted++;
                }

                if (backloggedGames[i].MainStoryLength <= 8)
                {
                    numShortGames++;
                }
                else if (backloggedGames[i].MainStoryLength >= 40)
                {
                    numLongGames++;
                }
                else
                {
                    numMedGames++;
                }

                backlogLength += gameLength;
            }

            // Calculate percent of games completed and percent of current game completed
            percentageCompleted = Math.Round(((double)numCompleted / backloggedGames.Count) * 100, 1);

            if (currGameLength <= 0)
            {
                currGameLength = 1;
            }

            percentageCompletedCurrGame = Math.Round((double)((currPlaying.PlayTime) / (currGameLength * 60)) * 100, 1);

            // Invalid value check
            if (percentageCompletedCurrGame < 0 || Double.IsNaN(percentageCompletedCurrGame))
            {
                percentageCompletedCurrGame = 0;
            }

            // Get most played game
            List <BackloggedGame> sortedPlaytime = backloggedGames.OrderByDescending(m => m.PlayTime).ToList();

            // Create json response
            string jsonStatistics = "{";

            jsonStatistics += "\"" + "num_backlogged_games\"" + ":" + backloggedGames.Count + ",";
            jsonStatistics += "\"" + "finish_backlog_time\"" + ":" + backlogLength + ",";
            jsonStatistics += "\"" + "num_completed\"" + ":" + numCompleted + ",";
            jsonStatistics += "\"" + "perc_completed\"" + ":" + percentageCompleted + ",";
            jsonStatistics += "\"" + "curr_game_name\"" + ":" + "\"" + currPlaying.Name + "\"" + ",";
            jsonStatistics += "\"" + "curr_game_length\"" + ":" + currGameLength + ",";
            jsonStatistics += "\"" + "curr_game_play_time\"" + ":" + (currPlaying.PlayTime / 60) + ",";
            jsonStatistics += "\"" + "perc_completed_curr_game\"" + ":" + percentageCompletedCurrGame + ",";
            jsonStatistics += "\"" + "num_short\"" + ":" + numShortGames + ",";
            jsonStatistics += "\"" + "num_med\"" + ":" + numMedGames + ",";
            jsonStatistics += "\"" + "num_long\"" + ":" + numLongGames + ",";

            jsonStatistics += "\"" + "most_played\"" + ":" + "[";
            jsonStatistics += "{\"" + "name\"" + ":" + "\"" + sortedPlaytime[0].Name + "\","; // first most played game
            jsonStatistics += "\"" + "play_time\"" + ":" + sortedPlaytime[0].PlayTime + "}";

            if (sortedPlaytime.Count > 1)
            {
                if (sortedPlaytime[1] != null)
                {
                    jsonStatistics += ",{\"" + "name\"" + ":" + "\"" + sortedPlaytime[1].Name + "\","; // second most played game
                    jsonStatistics += "\"" + "play_time\"" + ":" + sortedPlaytime[1].PlayTime + "},";
                }
            }

            if (sortedPlaytime.Count > 2)
            {
                if (sortedPlaytime[2] != null)
                {
                    jsonStatistics += "{\"" + "name\"" + ":" + "\"" + sortedPlaytime[2].Name + "\","; // third most played game
                    jsonStatistics += "\"" + "play_time\"" + ":" + sortedPlaytime[2].PlayTime + "}";
                }
            }

            jsonStatistics += "]}";

            return(Json(jsonStatistics, JsonRequestBehavior.AllowGet));
        }
        public JsonResult GetGames()
        {
            var manager     = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new GameLoggerIden.Models.ApplicationDbContext()));
            var CurrentUser = manager.FindById(User.Identity.GetUserId());

            // If current user has a Steam account linked
            if (CurrentUser.Logins.Count > 0)
            {
                for (int q = 0; q < CurrentUser.Logins.Count; q++)
                {
                    if (CurrentUser.Logins.ToList()[q].LoginProvider == "Steam")
                    {
                        string url    = string.Format("http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=BAC162F90A60259B7E7EB20A4EB46B63&steamid={0}&include_appinfo=1&format=json", this.GetSteamID());
                        string result = null;

                        using (var client = new WebClient())
                        {
                            result = client.DownloadString(url);
                        }

                        JObject jsonResults = JObject.Parse(result);
                        JObject steamGames  = JObject.Parse(jsonResults.GetValue("response").ToString());

                        JArray games = JArray.Parse(steamGames.GetValue("games").ToString());

                        using (BacklogDataContext db = new BacklogDataContext())
                        {
                            List <Game> dbGames = db.Games.AsNoTracking().ToList();

                            // Loop through all of user's Steam games and add them to backlog
                            for (int i = 0; i < games.Count; i++)
                            {
                                // Get game name
                                string gameName = games[i]["name"].ToString();

                                // Check to see if game exists in database
                                //Game dbGame = db.Games.AsNoTracking().FirstOrDefault(u => u.Name == gameName);
                                for (int x = 0; x < dbGames.Count; x++)
                                {
                                    if (dbGames[x].Name == gameName)
                                    {
                                        Game dbGame = dbGames[x];

                                        // Add game to backlog if it doesn't already exist
                                        if (dbGame != null)
                                        {
                                            Backlog backlogEntry = db.Backlogs.Find(User.Identity.Name, dbGame.Id); // Check to see if current user has this game in their backlog

                                            // If game doesn't exist in backlog, add it
                                            if (backlogEntry == null)
                                            {
                                                // Get game playtime
                                                int playTime = 0;
                                                Int32.TryParse(games[i]["playtime_forever"].ToString(), out playTime);

                                                // Add game to backlog
                                                Backlog newGame = new Backlog();
                                                newGame.GameId   = dbGame.Id;
                                                newGame.PlayTime = playTime;
                                                newGame.UserName = User.Identity.Name;

                                                Backlog userGame = db.Backlogs.Add(newGame);
                                            }
                                            else // If game exists in backlog already, update playtime
                                            {
                                                // Get game playtime
                                                int playTime = 0;
                                                Int32.TryParse(games[i]["playtime_forever"].ToString(), out playTime);

                                                backlogEntry.PlayTime = playTime;
                                            }
                                        }
                                    }
                                }
                            }

                            db.SaveChanges();
                        }

                        return(Json("{\"success\": true}", JsonRequestBehavior.AllowGet));
                    }
                }
            }

            return(Json("{\"success\": false}", JsonRequestBehavior.AllowGet));
        }
Esempio n. 6
0
        /// <summary>
        /// Displays the list of games that a user has already completed.
        /// </summary>
        /// <param name="page">An integer that represents what page in a user's backlog list to start at.</param>
        public ActionResult Completed(int?page)
        {
            string user = User.Identity.Name;

            using (BacklogDataContext db = new BacklogDataContext())
            {
                // Get all of a user's game
                IQueryable <Backlog> query = db.Backlogs.AsNoTracking();
                var totalCount             = query.Count();

                query = query
                        .Where(b => b.UserName == user && b.Completed_Game == true);

                var pager = new Pager(query.Count(), page, 30); // Pager used to only display a subset of games at any given moment

                // Order results by most recent
                query = query.OrderByDescending(o => o.InsertionTime).ThenByDescending(o => o.PlayTime);

                // Get the games based on what page of games is currently selected
                query = query.Skip((pager.CurrPage - 1) * pager.NumResults).Take(pager.NumResults);

                var data = query.Select(backlog => new
                {
                    GameID    = backlog.GameId,
                    Completed = backlog.Completed_Game,
                    Platinum  = backlog.Platinum_Status,
                    PlayTime  = backlog.PlayTime
                }).ToList();

                // Create a List of all the games in the backlog with their relevant data
                List <BackloggedGame> backloggedGames = new List <BackloggedGame>();

                for (int i = 0; i < data.Count; i++)
                {
                    int  id   = data[i].GameID;
                    Game game = db.Games.First(g => g.Id == id); // Get game with specific id

                    // Get all relevant information about a game and add it to list
                    BackloggedGame newGame = new BackloggedGame();
                    newGame.Id                  = game.Id;
                    newGame.Name                = game.Name;
                    newGame.BoxArt              = game.Box_Art;
                    newGame.DetailsUrl          = game.Details_Url;
                    newGame.MainStoryLength     = game.Main_Story_Length;
                    newGame.MainExtraLength     = game.Main_Extra_Length;
                    newGame.CompletionistLength = game.Completionist_Length;
                    newGame.CombinedLength      = game.Combined_Length;
                    newGame.ReviewScore         = game.IGDB_Review_Score;
                    newGame.CompletedGame       = data[i].Completed;
                    newGame.PlatinumStatus      = data[i].Platinum;
                    newGame.PlayTime            = data[i].PlayTime;

                    // If the game isn't in the list already then add it
                    if (!backloggedGames.Contains(newGame))
                    {
                        backloggedGames.Add(newGame);
                    }
                }

                // Pass the final results to the client
                BackloggedGamePage pagedResults = new BackloggedGamePage();
                pagedResults.Games = backloggedGames;
                pagedResults.Pager = pager;

                return(View(pagedResults));
            }
        }
Esempio n. 7
0
        public JsonResult Add(string gameName, bool completed, string playTime)
        {
            if (gameName == "")
            {
                return(Json("{\"success\": false}", JsonRequestBehavior.AllowGet));
            }

            using (BacklogDataContext db = new BacklogDataContext())
            {
                if (gameName != null)
                {
                    // Look up ID of input game name
                    Game game = db.Games.First(g => g.Name == gameName);

                    // Check to make sure game doesn't exist in backlog
                    int id = game.Id;

                    // If game doesn't exist in backlog, add it, otherwise update the entry
                    if (!db.Backlogs.Any(b => b.GameId == id))
                    {
                        // Add game to backlog list and return success
                        Backlog backlog = new Backlog();
                        backlog.UserName       = User.Identity.Name; // Set username to currently logged in user
                        backlog.GameId         = game.Id;
                        backlog.Completed_Game = completed;

                        // Ensure playtime is valid
                        int time = 0;
                        Int32.TryParse((string)playTime.ToString(), out time);

                        if (time < 0)
                        {
                            time = 0;
                        }

                        backlog.PlayTime        = (time * 60); // Convert playtime to minutes
                        backlog.Platinum_Status = false;

                        db.Backlogs.Add(backlog);
                        db.SaveChanges();

                        return(Json("{\"success\": true}", JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        // Remove old entry
                        Backlog oldEntry = db.Backlogs.First(m => m.GameId == id);
                        db.Backlogs.Remove(oldEntry);

                        // Add game to backlog list and return success
                        Backlog backlog = new Backlog();
                        backlog.UserName       = User.Identity.Name; // Set username to currently logged in user
                        backlog.GameId         = game.Id;
                        backlog.Completed_Game = completed;

                        // Ensure playtime is valid
                        int time = 0;
                        Int32.TryParse((string)playTime.ToString(), out time);

                        if (time < 0)
                        {
                            time = 0;
                        }

                        backlog.PlayTime        = (time * 60); // Convert playtime to minutes
                        backlog.Platinum_Status = false;

                        db.Backlogs.Add(backlog);
                        db.SaveChanges();

                        return(Json("{\"success\": true}", JsonRequestBehavior.AllowGet));
                    }
                }

                return(Json("{\"success\": false}", JsonRequestBehavior.AllowGet));
            }
        }