Exemplo n.º 1
0
        private static AutoUpdateManager GetAutoUpdateManager()
        {
            // build up AutoUpdateManager - use DI instead?
            SteamCommunityManager steamCommunityManager =
                new SteamCommunityManager(new WebClientWrapper(), new SteamProfileXmlParser(), new GameXmlParser(),
                                          new AchievementXmlParser());
            AchievementService achievementService =
                new AchievementService(
                    new AchievementManager(new SteamRepository()), steamCommunityManager);
            UserService userService = new UserService(new AchievementManager(new SteamRepository()));

            // verify the log path
            DirectoryInfo logDirectory = new DirectoryInfo("logs");

            if (!logDirectory.Exists)
            {
                logDirectory.Create();
            }

            IAutoUpdateLogger autoUpdateLogger = new AutoUpdateLogger(logDirectory.FullName);

            // only keeps logs for the past 10 days
            autoUpdateLogger.Delete(DateTime.Now.AddDays(-10));
            // the default writer saves output to a file, this will display it in the console as well
            autoUpdateLogger.Attach(Console.Out);

            AutoUpdateManager autoUpdateManager =
                new AutoUpdateManager(achievementService, userService, new FacebookPublisher(),
                                      autoUpdateLogger);

            return(autoUpdateManager);
        }
        protected void addButton_Click(object sender, EventArgs e)
        {
            if (!IsValid)
            {
                return;
            }

            Game game = new Game
            {
                Abbreviation = abbreviationTextBox.Text,
                Name         = nameTextBox.Text
            };

            using (SteamCommunityManager community = new SteamCommunityManager())
                using (AchievementManager manager = new AchievementManager())
                {
                    manager.AddGame(game);

                    IEnumerable <Achievement> achievements =
                        community.GetAchievements(steamUserIdTextBox.Text, game);

                    manager.AddAchievements(game.Id, achievements);
                }

            Response.Redirect("~/Admin");
        }
Exemplo n.º 3
0
        public void GetAchievements()
        {
            SteamCommunityManager manager = new SteamCommunityManager();

            IEnumerable <Achievement> achievements = manager.GetAchievements("nullreference");

            Assert.That(achievements.Any());
            Assert.That(achievements.Any(a => a.Name == "Acid Reflex"));
        }
Exemplo n.º 4
0
        public void GetGames()
        {
            SteamCommunityManager manager = new SteamCommunityManager();

            IEnumerable <Game> games = manager.GetGames("nullreference");

            Assert.That(games.Any());
            Assert.That(games.Any(game => game.Name == "Left 4 Dead"));
            Assert.That(games.Any(game => game.Name == "Left 4 Dead 2"));
        }
        /// <summary>
        /// Serializes the achievements.
        /// </summary>
        /// <param name="steamUserId">The steam user id.</param>
        private static void SerializeAchievements(string steamUserId)
        {
            SteamCommunityManager manager = new SteamCommunityManager(new WebClientWrapper(),
                                                                      new SteamProfileXmlParser(), new GameXmlParser(),
                                                                      new AchievementXmlParser());

            UserAchievement[] achievements = manager.GetClosedAchievements(steamUserId).ToArray();

            Serialize("Serialized" + steamUserId + "Achievements.xml", achievements);
        }
        private static Publisher CreatePublisher()
        {
            var settings           = Settings.Default;
            var logger             = new AutoUpdateLogger(_logDirectory.FullName);
            var achievementManager = new AchievementManager(new SteamRepository());
            var communityManager   = new SteamCommunityManager(new WebClientWrapper(), new SteamProfileXmlParser(), new GameXmlParser(), new AchievementXmlParser());
            var achievementService = new AchievementService(achievementManager, communityManager);
            var facebookClient     = new FacebookClientService(settings.FacebookAppId, settings.FacebookAppSecret, settings.FacebookCanvasUrl);
            var autoUpdateManager  = new AutoUpdateManager(achievementService, new UserService(achievementManager), facebookClient, logger);

            return(new Publisher(autoUpdateManager));
        }
Exemplo n.º 7
0
        public void GetGameAchievements()
        {
            SteamCommunityManager manager = new SteamCommunityManager();

            Game game = new Game {
                Id = 1, Name = "Left 4 Dead", Abbreviation = "l4d"
            };

            IEnumerable <Achievement> achievements = manager.GetAchievements("nullreference", game);

            Assert.That(achievements.Any());
            Assert.That(achievements.All(a => a.GameId == game.Id));
        }
        /// <summary>
        /// Serializes the achievements.
        /// </summary>
        /// <param name="steamUserId">The steam user id.</param>
        private static void SerializeAchievements(string steamUserId)
        {
            SteamCommunityManager  manager      = new SteamCommunityManager(new WebClientWrapper(), new SteamProfileXmlParser(), new GameXmlParser(), new AchievementXmlParser());
            List <UserAchievement> achievements = manager.GetAchievements(steamUserId).ToList();

            FileInfo      dll                = new FileInfo("SteamAchievements.Services.Tests");
            DirectoryInfo bin                = new DirectoryInfo(dll.Directory.FullName);
            string        projectPath        = bin.Parent.Parent.FullName;
            string        serializedFilePath = Path.Combine(projectPath, "Serialized" + steamUserId + "Achievements.xml");

            DataContractSerializer serializer =
                new DataContractSerializer(typeof(UserAchievement), new[] { typeof(List <UserAchievement>) });

            using (FileStream writer = new FileStream(serializedFilePath, FileMode.Create))
            {
                serializer.WriteObject(writer, achievements);
            }
        }
Exemplo n.º 9
0
        public void SerializeAchievements()
        {
            SteamCommunityManager       manager      = new SteamCommunityManager();
            List <Services.Achievement> achievements = manager.GetAchievements("Unimatrixero").ToList();

            FileInfo      dll                = new FileInfo("SteamAchievements.Services.Tests");
            DirectoryInfo bin                = new DirectoryInfo(dll.Directory.FullName);
            string        projectPath        = bin.Parent.Parent.FullName;
            string        serializedFilePath = Path.Combine(projectPath, "SerializedUnimatrixeroAchievements.xml");

            DataContractSerializer serializer =
                new DataContractSerializer(typeof(Services.Achievement), new[] { typeof(List <Services.Achievement>) });

            using (FileStream writer = new FileStream(serializedFilePath, FileMode.Create))
            {
                serializer.WriteObject(writer, achievements);
            }
        }
        public void GetAchievements()
        {
            SteamCommunityManager manager = new SteamCommunityManager();

            IEnumerable <Game> games = new[]
            {
                new Game {
                    Id = 1, Name = "Left 4 Dead", Abbreviation = "l4d"
                },
                new Game {
                    Id = 2, Name = "Left 4 Dead 2", Abbreviation = "l4d2"
                }
            };
            IEnumerable <Achievement> achievements = manager.GetAchievements("nullreference", games);

            Assert.That(achievements.Any());

            Assert.That(achievements.SingleOrDefault(a => a.Name == "Acid Reflex"), Is.Not.Null);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Publishes the user's achievements.
        /// </summary>
        /// <param name="user">The user.</param>
        public void PublishUserAchievements(User user)
        {
            _log.Log(String.Format("User {0} ({1})", user.SteamUserId, user.FacebookUserId));

            if (String.IsNullOrEmpty(user.AccessToken))
            {
                _log.Log("Empty AccessToken");

                // if there is no access token, the user hasn't given the app offline_access
                return;
            }

            try
            {
                // update the user's achievements
                int updated = _achievementService.UpdateAchievements(user.FacebookUserId, user.Language);

                if (updated == 0)
                {
                    _log.Log("No updated achievements");

                    return;
                }
            }
            catch (InvalidGamesXmlException exception)
            {
                _log.Log("Invalid games URL for {0}.", user.SteamUserId);
                _log.Log(exception);

                throw;
            }
            catch (XmlException exception)
            {
                _log.Log("Invalid xml for {0}.", user.SteamUserId);
                _log.Log(exception);

                throw;
            }

            // get unpublished achievements earned in the last 24-48 hours to make up for time zone differences
            // and the time it takes to run the Auto Update process
            DateTime oldestDate = DateTime.UtcNow.AddHours(-48).Date;
            ICollection <Achievement> achievements =
                _achievementService.GetUnpublishedAchievements(user.FacebookUserId, oldestDate, user.Language);

            if (!achievements.Any())
            {
                _log.Log("No unpublished achievements");

                return;
            }

            // only publish the top 5
            achievements = achievements.Take(5).ToList();

            // since the api only supports one attachment, use the first achievement's image
            // and build the description from all achievements
            Achievement firstAchievement = achievements.First();
            Uri         statsUrl         = SteamCommunityManager.GetProfileUrl(user.SteamUserId, false);
            string      message          = String.Format("{0} unlocked {1} achievement{2}!",
                                                         user.SteamUserId,
                                                         achievements.Count,
                                                         achievements.Count > 1 ? "s" : String.Empty);

            IDictionary <string, object> parameters =
                new Dictionary <string, object>
            {
                { "link", statsUrl.ToString() },
                { "message", message },
                { "name", user.SteamUserId },
                { "picture", firstAchievement.ImageUrl },
                { "description", BuildDescription(achievements, user.PublishDescription) }
            };

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

            try
            {
                // publish the post
                _publisher.Publish(user, parameters);

                publishedAchievements.AddRange(achievements.Select(a => a.Id));
            }
            catch (FacebookOAuthException exception)
            {
                // The user's access token is invalid. They may have changed their password performed another action to invalidate it.
                _log.Log("User {0} has an invalid AccessToken, the value will be removed.", user.SteamUserId);
                _log.Log(exception);

                // Reset the user's access token.
                user.AccessToken = String.Empty;
                _userService.UpdateUser(user);

                return;
            }
            catch (FacebookApiException exception)
            {
                _log.Log(exception);

                return;
            }

            // update the published flag
            _achievementService.PublishAchievements(user.FacebookUserId, publishedAchievements);

            _log.Log("Published {0} achievements.", publishedAchievements.Count);
        }
Exemplo n.º 12
0
 public void SetUp()
 {
     _manager = new SteamCommunityManager(new WebClientWrapper(), new SteamProfileXmlParser(), new GameXmlParser(), new AchievementXmlParser());
 }
 public void SetUp()
 {
     _manager = new SteamCommunityManager(new WebClientWrapper(), new SteamProfileXmlParser(),
                                          new GameXmlParser(), new AchievementXmlParser(),
                                          new Mock <IErrorLogger>().Object);
 }
        public void ApiNameMigration()
        {
            UserAchievement[]  communityAchievements;
            Data.Achievement[] dataAchievements;
            using (SteamRepository repository = new SteamRepository())
            {
                Dictionary <string, ICollection <UserAchievement> > userCommunityAchievements;
                using (
                    SteamCommunityManager communityManager =
                        new SteamCommunityManager(new WebClientWrapper(), new SteamProfileXmlParser(),
                                                  new GameXmlParser(), new AchievementXmlParser()))
                {
                    string[] invalidUserProfiles =
                        new[] { "0", "/zero_x9", "-vaka-", "inv4d3r", "barakitten", "76561198032315004", "120gb" };
                    var gameUsersQuery =
                        from userAchievement in repository.UserAchievements
                        where userAchievement.Achievement.ApiName.Length == 0 &&
                        !invalidUserProfiles.Contains(userAchievement.User.SteamUserId)
                        group userAchievement by userAchievement.Achievement.GameId
                        into g
                        select new { GameId = g.Key, SteamUserId = g.Min(ua => ua.User.SteamUserId) };

                    Dictionary <int, string> gameUsers = gameUsersQuery.OrderBy(s => s.GameId)
                                                         .ToDictionary(s => s.GameId, s => s.SteamUserId);

                    Debug.WriteLine(String.Join(", ", gameUsers.Keys));

                    userCommunityAchievements = new Dictionary <string, ICollection <UserAchievement> >();

                    foreach (string user in gameUsers.Values.Distinct().OrderBy(v => v))
                    {
                        try
                        {
                            ICollection <UserAchievement> userAchievements = communityManager.GetAchievements(user);
                            userCommunityAchievements.Add(user, userAchievements);
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("GetAchievements failed for user " + user + ".");
                            Debug.WriteLine(ex);
                            if (ex.InnerException != null)
                            {
                                Debug.WriteLine(ex.InnerException);
                            }
                        }
                    }
                }

                communityAchievements =
                    userCommunityAchievements.Values.SelectMany(v => v.Select(ua => ua)).OrderBy(ua => ua.Game.Id)
                    .OrderBy(ua => ua.AchievementApiName).Distinct().ToArray();

                Serialize("CommunityAchievements.xml", communityAchievements);

                dataAchievements = repository.Achievements.ToArray();
                foreach (Data.Achievement dataAchievement in dataAchievements)
                {
                    UserAchievement achievement =
                        communityAchievements
                        .Where(a =>
                               a.Game.Id == dataAchievement.GameId &&
                               a.Name.ToUpper() == dataAchievement.Name.ToUpper() &&
                               a.Description.ToUpper() == dataAchievement.Description.ToUpper())
                        .FirstOrDefault();
                    if (achievement != null)
                    {
                        dataAchievement.ApiName = achievement.AchievementApiName;
                        //Debug.WriteLine("Id: {0}, GameId: {1}, Name: {2}, ApiName: {3}",
                        //                dataAchievement.Id, dataAchievement.GameId,
                        //                dataAchievement.Name, dataAchievement.ApiName);
                    }
                }

                Serialize("UpdatedApiNameAchievements.xml", dataAchievements.ToArray());

                ChangeSet changeSet = repository.Context.GetChangeSet();
                Debug.WriteLine(changeSet);
                repository.SubmitChanges();
            }
            //Assert.That(changeSet.Updates, Is.Not.Empty);

            Debug.WriteLine("Total Data Achievements: " + dataAchievements.Length);
            Debug.WriteLine("Total Community Achievements: " + communityAchievements.Length);
        }
        private List <Result> UpdateAchievements()
        {
            IEnumerable <User> users;

            using (IAchievementManager manager = new AchievementManager())
            {
                // get users configured for auto update
                users = manager.GetAutoUpdateUsers();
            }

            List <Result> results = new List <Result>();

            using (SteamCommunityManager manager = new SteamCommunityManager())
                using (IAchievementService service = new AchievementService())
                {
                    foreach (User user in users)
                    {
                        Log("User: "******" ( " + user.FacebookUserId + ")");

                        if (String.IsNullOrEmpty(user.AccessToken))
                        {
                            Log("Empty AccessToken");

                            // if there is no access token, the user hasn't given the app offline_access
                            continue;
                        }

                        // update the user's achievements
                        int updated = service.UpdateAchievements(user.SteamUserId);

                        if (updated == 0)
                        {
                            Log("No updated achievements");

                            continue;
                        }

                        // get the user's unpublished achievements
                        IEnumerable <SimpleAchievement> achievements = service.GetNewAchievements(user.SteamUserId);

                        if (!achievements.Any())
                        {
                            Log("No unpublished achievements");

                            continue;
                        }

                        FacebookApp app          = new FacebookApp(user.AccessToken);
                        string      userFeedPath = String.Format("/{0}/feed/", user.FacebookUserId);

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

                        // post the first 5 new achievements
                        foreach (SimpleAchievement achievement in achievements.Take(5))
                        {
                            string message = String.Format("{0} earned an achievement in {1}",
                                                           user.SteamUserId, achievement.Game.Name);
                            dynamic parameters = new ExpandoObject();
                            parameters.link        = achievement.Game.StatsUrl;
                            parameters.message     = message;
                            parameters.name        = achievement.Name;
                            parameters.description = achievement.Description;
                            parameters.picture     = achievement.ImageUrl;

                            Log(message);

                            Result result = new Result
                            {
                                SteamUserId = user.SteamUserId,
                                GameName    = achievement.Game.Name,
                                Description = achievement.Name
                            };

                            try
                            {
                                dynamic response = app.Api(userFeedPath, parameters, HttpMethod.Post);

                                publishedAchievements.Add(achievement.Id);
                            }
                            catch (FacebookApiException ex)
                            {
                                // log Facebook errors and continue
                                result.ExceptionMessage += Environment.NewLine + "Exception: " + ex.Message;
                                if (ex.InnerException != null)
                                {
                                    result.ExceptionMessage += Environment.NewLine + ", Inner Exception: " + ex.InnerException.Message;
                                }

                                Log(result.ExceptionMessage);
                            }

                            results.Add(result);
                        }

                        // update the published flag
                        service.PublishAchievements(user.SteamUserId, publishedAchievements);

                        Log("User achievements published");
                    }
                }

            return(results);
        }