Пример #1
0
    // Use this for initialization
    void Start()
    {
        //Find the Twitter Manager in the scene.
        twitterManager = FindObjectOfType <TwitterManager> ();
        partyManager   = FindObjectOfType <PartyManager> ();
        waveManager    = FindObjectOfType <WaveManager> ();

        guimMainGame = FindObjectOfType <GUIM_MainGame> ();

        dynamicObjectHolder = GameObject.Find("Dynamic Objects");

        if (dynamicObjectHolder == null)
        {
            dynamicObjectHolder = new GameObject("Dynamic Objects");
        }

        //Jordan Says: Scraping here might be good for more data and key words: http://www.bbc.co.uk/news/election/2015/manifesto-guide

        //DEBUG: To leave game running.
        Application.runInBackground = true;

        Cursor.visible = false;

        //Launch the Game
        StartGame();
    }
Пример #2
0
    public void ApplyTwitterContent()
    {
        TwitterManager tweets = TwitterManager.Instance;

        if (tweets != null)
        {
            TweetSearchTwitterData data = null;

            if (this is AttractedCube || this is StreamingCube)
            {
                data = tweets.GetNextImgTweet();
                if (data == null && (m_image == null || m_image.sprite == null))
                {
                    tweets.GetNextTweet();
                }
            }
            else
            {
                data = tweets.GetNextTweet();
            }

            if (data == null)
            {
                Debug.LogError("Data is NULL for some strange reason!!!");
            }
            else
            {
                SetText(data.tweetText);
                Load(data.tweetMedia);
            }
        }
    }
        public void TestEmojiResourceFileLoadToRepo()
        {
            var mgr = new TwitterManager(_abcRepo, _config, Mock.Of <ILogger <TwitterManager> >());

            mgr.LoadEmojiDataFromFileResource("ABC.Integration.Resources.emoji.json", _abcRepo);
            var count = _abcRepo.GetAll <Emoji>().Count();

            Assert.IsTrue(_abcRepo.GetAll <Emoji>().Count() > 10);
        }
Пример #4
0
        public void TwitterManagerTests_TestMe_NoMocks()
        {
            var manager = new TwitterManager();

            var results = manager.TestMe();

            Assert.IsFalse(string.IsNullOrEmpty(results));
            Assert.AreEqual("TwitterSearchBackend.Engines.ValidationEngine, TwitterSearchBackend.Accessors.TwitterAPIAccessor, TwitterSearchBackend.Managers.TwitterManager", results);
        }
Пример #5
0
    private void Start()
    {
        twitterManager = FindObjectOfType <TwitterManager>(); // TODO: Separate twitterManager from this script

        if (!refreshAfterEnable && spawnedAtStart)
        {
            mCanvas = FindObjectOfType <Canvas>();
            SetUpPanel();
        }
    }
        public TwitterApiTest()
        {
            _abcRepo = SetupABCDBRepo();
            var config      = GetConfigSetings();
            var logger      = Mock.Of <ILogger <TwitterManager> >();
            var loggerStats = Mock.Of <ILogger <StatisticsManager> >();

            _twitterManager   = new TwitterManager(_abcRepo, config, logger);
            _socialStatistics = new StatisticsManager(_abcRepo, config, loggerStats);
        }
Пример #7
0
        public void TwitterManagerTests_TestMe_WithMocks()
        {
            var manager = new TwitterManager();

            manager.FactoryOverride <IValidationEngine>(new Mocks.EngineMock_ValidationEngine());
            manager.FactoryOverride <ITwitterApiAccessor>(new Mocks.AccessorMock_TwitterAPIAccessor());

            var results = manager.TestMe();

            Assert.IsFalse(string.IsNullOrEmpty(results));
            Assert.AreEqual("TwitterTests.Mocks.EngineMock_ValidationEngine, TwitterTests.Mocks.AccessorMock_TwitterAPIAccessor, TwitterSearchBackend.Managers.TwitterManager", results);
        }
Пример #8
0
        private async Task Run(bool fastShutdown)
        {
            Console.WriteLine($"{(fastShutdown ? "Fast" : "Slow")} shutdown started");

            if (!fastShutdown)
            {
                // Shutdown the Scheduler
                await QuartzScheduler.Dispose();

                // Shutdown the DiscordBot
                await DiscordBot.Dispose();
            }
            else
            {
                // Create a backup of the current config.json just in case
                File.Copy(Boot.LOCAL_CONFIGURATION, Boot.LOCAL_CONFIGURATION_AUTOMATIC_BACKUP, true);
            }

            // Shutdown Twitter
            TwitterManager.Dispose();

            // Shutdown DigitalOcean
            DoApi.Dispose();

            // Shutdown S3
            S3Api.Dispose();

            // Shutdown BCAT
            BcatApi.Dispose();

            // Shutdown DAuth
            DAuthApi.Dispose();

            // Shutdown the HandlerMapper
            HandlerMapper.Dispose();

            // Shutdown the KeysetManager
            KeysetManager.Dispose();

            // Shutdown anything app-specific
            ShutdownAppSpecificItems();

            // Save the configuration
            Configuration.LoadedConfiguration.Write();

            if (!fastShutdown)
            {
                // Wait a little while
                await Task.Delay(1000 *ShutdownWaitTime);
            }

            Console.WriteLine("Shutdown complete");
        }
Пример #9
0
        public List <Tweet> GetTweets()
        {
            //allows calls from any origin
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
            //get count and screenname query string params
            var requestQueryStringParams = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters;
            var count      = string.IsNullOrEmpty(requestQueryStringParams[_CountKey]) ? 10 : Convert.ToInt32(requestQueryStringParams[_CountKey]);
            var screenname = string.IsNullOrEmpty(requestQueryStringParams[_ScreenNameKey]) ? "salesforce" : requestQueryStringParams[_ScreenNameKey];
            //init business manager
            var manager = new TwitterManager();

            return(manager.GetTweets(count, screenname));
        }
Пример #10
0
        public void TwitterManagerTests_Search_HandleErrorResults()
        {
            var manager = new TwitterManager();

            manager.FactoryOverride <IValidationEngine>(new Mocks.EngineMock_ValidationEngine());
            manager.FactoryOverride <ITwitterApiAccessor>(new Mocks.AccessorMock_TwitterAPIAccessor());

            var results = manager.Search("error");

            Assert.IsTrue(results != null);
            Assert.IsTrue(results.Items == null);
            Assert.IsFalse(string.IsNullOrEmpty(results.Error));
        }
Пример #11
0
        public static void HandleAdded(Present present)
        {
            // Get the tweet header
            string tweetHeader = Localizer.Localize("twitter.present.header", Language.EnglishUS);

            // Get the tweet content
            string tweetContent = present.TitleText[Language.EnglishUS] + "\n\n" + present.ContentText[Language.EnglishUS];

            // Get the tweet URL component
            string tweetUrl = string.Format(Localizer.Localize("twitter.present.url", Language.EnglishUS), $"https://smash.oatmealdome.me/present/{present.Id}/en-US/");

            // Send the tweet
            TwitterManager.GetAccount("SSBUBot").Tweet(tweetHeader, present.TitleText[Language.EnglishUS], tweetUrl, present.Image);
        }
Пример #12
0
        //Publicar nuevo festival en Twitter
        private void publicarFestivalNuevoTwitter(string pNombreEvento)
        {
            TwitterManager twitter = new TwitterManager();

            try
            {
                string mensajeTweet = "¡Visita nuestro nuevo festival " + pNombreEvento + "!";
                twitter.enviarTweet(mensajeTweet);
            }
            catch (Exception e)
            {
                throw (e);
            }
        }
Пример #13
0
        public static void HandleAdded(LineNews lineNews)
        {
            // Get the tweet header
            string tweetHeader = Localizer.Localize("twitter.line_news.header", Language.EnglishUS);

            // Get the tweet content
            string tweetContent = $"\"{lineNews.OneLines[0].Text[Language.EnglishUS]}\" and more...";

            // Get the tweet URL component
            string tweetUrl = string.Format(Localizer.Localize("twitter.line_news.url", Language.EnglishUS), $"https://smash.oatmealdome.me/line_news/{lineNews.Id}/en-US/");

            // Send the tweet
            TwitterManager.GetAccount("SSBUBot").Tweet(tweetHeader, tweetContent, tweetUrl);
        }
Пример #14
0
        /// <summary>
        /// Returns Twitter Feeds in JSON format
        /// </summary>
        /// <returns></returns>
        public string TwitterFeed()
        {
            try
            {
                // Get feed from cache if possible
                var cacheKey = string.Format(ModelCacheEventConsumer.TWITTER_FEEDS_KEY);
                var feed     = _cacheManager.Get <string>(cacheKey);

                if (!string.IsNullOrEmpty(feed))
                {
                    return(feed);
                }

                //no value in the cache yet so let's retrieve it

                var tm = new TwitterManager(
                    ConfigurationManager.AppSettings["Twitter.AccessToken"],
                    ConfigurationManager.AppSettings["Twitter.AccessTokenSecret"],
                    ConfigurationManager.AppSettings["Twitter.ConsumerKey"],
                    ConfigurationManager.AppSettings["Twitter.ConsumerSecret"]
                    );

                int maximumTweets;
                if (!Int32.TryParse(ConfigurationManager.AppSettings["Twitter.MaximumTweets"], out maximumTweets))
                {
                    maximumTweets = 6;
                }

                feed = tm.GetUserTimeline(ConfigurationManager.AppSettings["Twitter.ScreenName"], maximumTweets);

                int cacheDuration;
                if (!Int32.TryParse(ConfigurationManager.AppSettings["Twitter.CacheDuration"], out cacheDuration))
                {
                    cacheDuration = 10; // 10 minutes
                }

                //let's cache the result
                _cacheManager.Set(cacheKey, feed, cacheDuration);

                return(feed);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message, ex);
                return(string.Empty);
            }
        }
Пример #15
0
        //Publica bandas agregadas en Twiter
        private void publicarBandasTwitter(string pNombreEvento, List <categoriasevento> pListaCategoriasBanda)
        {
            TwitterManager twitter = new TwitterManager();

            foreach (categoriasevento cat_eve in pListaCategoriasBanda)
            {
                string nombreBanda  = _manejador.obtenerBanda(cat_eve.FK_CATEGORIASEVENTO_BANDAS).nombreBan;
                string mensajeTweet = "¡Vota por tu banda. " + nombreBanda + " en el festival " + pNombreEvento + "!";
                try
                {
                    twitter.enviarTweet(mensajeTweet);
                } catch (Exception e)
                {
                    throw (e);
                }
            }
        }
Пример #16
0
        public static void HandleAdded(PopUpNews popUpNews)
        {
            // Check if this is an event pop-up news and is not the initial pop-up
            if (popUpNews.IsPopUpForEvent && !popUpNews.Id.StartsWith("01"))
            {
                // Skip
                return;
            }

            // Get the tweet header
            string tweetHeader = Localizer.Localize("twitter.popupnews.header", Language.EnglishUS);

            // Get the tweet URL component
            string tweetUrl = string.Format(Localizer.Localize("twitter.popupnews.url", Language.EnglishUS), $"https://smash.oatmealdome.me/popup_news/{popUpNews.Id}/en-US/");

            // Send the tweet
            TwitterManager.GetAccount("SSBUBot").Tweet(tweetHeader, popUpNews.TitleText[Language.EnglishUS], tweetUrl, popUpNews.Image);
        }
Пример #17
0
        public void DoCommand(string command)
        {
            if (authed)
            {
                switch (command)
                {
                case "generate shop":
                    GenerateShop();
                    break;

                case "draw shop":
                    DrawShop(ShopV2.Get());
                    break;

                case "clear cache":
                    Directory.Delete($"{Root}Cache", true);
                    Console.WriteLine("Cleared cache!");
                    break;

                case "tweet":
                    Console.WriteLine("Enter Status:");
                    TwitterManager.Tweet(Console.ReadLine());
                    break;

                default:
                    Console.WriteLine("Wrong command!");
                    break;
                }
            }
            else if (command == Environment.GetEnvironmentVariable("COMMANDSKEY"))
            {
                authed = true;
                Console.WriteLine("Commands enabled");
            }

            Console.WriteLine(authed ? "Enter command:" : "Wrong key.\nTry again:");
            DoCommand(Console.ReadLine());
        }
 public SocialMediaController(ISocialStatistics statisticsManager, TwitterManager twitterManager, ILogger <SocialMediaController> logger)
 {
     _twitterManager    = twitterManager;
     _logger            = logger;
     _statisticsManager = statisticsManager;
 }
Пример #19
0
 public HomeController()
 {
     _twitterManager     = new TwitterManager();
     _monkeyLearnManager = new MonkeyLearnManager();
     _slangManager       = new SlangManager();
 }
Пример #20
0
    /// <summary>
    /// Load control .
    /// </summary>
    private void LoadSocialBoxes()
    {
        List <String> cta_boxes   = new List <String>();
        int           total_boxes = Convert.ToInt32(SocialBoxCount);

        if (!String.IsNullOrEmpty(CTAS))
        {
            try{
                cta_boxes = Regex.Split(CTAS, "{}").ToList();
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException("SocialApp control", "LoadSocialBoxes CTA", ex);
            }
        }
        int           social_count = total_boxes - cta_boxes.Count();
        List <String> obj_list     = new List <String>();

        if (!String.IsNullOrEmpty(InstagramUserID))
        {
            try
            {
                InstagramManager imgr    = new InstagramManager(InstagramOAuthConsumerID, InstagramOAuthConsumerSecret, RedirectURL);
                List <String>    instgrm = imgr.GetRandom(Convert.ToInt32(InstagramUserID), total_boxes).ToList();
                obj_list = obj_list.Concat(instgrm).ToList();
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException("SocialApp control", "LoadSocialBoxes Instagram", ex);
            }
        }
        if (!String.IsNullOrEmpty(TwitterUser))
        {
            try
            {
                TwitterManager tm = new TwitterManager(TwitterOAuthConsumerID, TwitterOAuthConsumerSecret, TwitterOAuthAccessToken, TwitterOAuthAccessSecret);

                List <String> tweet = tm.GetRandomTweet(TwitterUser, total_boxes).ToList();
                obj_list = obj_list.Concat(tweet).ToList();
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException("SocialApp control", "LoadSocialBoxes Twitter", ex);
            }
        }
        if (!String.IsNullOrEmpty(FacebookUserID))
        {
            try
            {
                FacebookManager fmgr   = new FacebookManager(FacebookAuthToken, FacebookAppID, FacebookClientSecret, FacebookRedirectURI);
                List <String>   fbpost = fmgr.GetRandomPost(FacebookUserID, total_boxes).ToList();
                obj_list = obj_list.Concat(fbpost).ToList();
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException("SocialApp control", "LoadSocialBoxes Facebook", ex);
            }
        }
        if (!String.IsNullOrEmpty(youtube_api_key))
        {
            try
            {
                YouTubeManager ytmgr   = new YouTubeManager(youtube_api_key);
                List <String>  ytvideo = ytmgr.GetVideosByPlaylistID(youtube_playlist_id, total_boxes).ToList();
                obj_list = obj_list.Concat(ytvideo).ToList();
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException("SocialApp control", "LoadSocialBoxes Youtube", ex);
            }
        }

        //Randomize the list of social items and take the top # of social boxes
        obj_list = obj_list.OrderBy(x => Guid.NewGuid()).Take(social_count).ToList();

        //CTAs are always shown, add on to the end of the main list
        if (!String.IsNullOrEmpty(CTAS))
        {
            OtherManager  cta_build = new OtherManager();
            List <String> ctas      = cta_build.BuildCTAList(cta_boxes).ToList();
            obj_list = obj_list.Concat(ctas).ToList();
        }

        //If the number of boxes are less than the number requested, fill with backup images
        if ((obj_list.Count() < total_boxes) && !String.IsNullOrEmpty(BackupImages))
        {
            try
            {
                int           num_images = total_boxes - obj_list.Count();
                OtherManager  img_build  = new OtherManager();
                List <String> imgs       = img_build.BuildImageList(s_images_list, num_images).ToList();
                obj_list = obj_list.Concat(imgs).ToList();
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException("SocialApp control", "LoadSocialBoxes BackupImages", ex);
            }
        }

        //randomize again
        obj_list = obj_list.OrderBy(x => Guid.NewGuid()).ToList();

        StringBuilder sb = new StringBuilder();

        foreach (String s in obj_list)
        {
            sb.Append(s);
        }
        community_box_list.InnerHtml = sb.ToString();
    }
Пример #21
0
 public TwitterController(UserManager managerUser, TwitterManager manager) : base(managerUser)
 {
     _manager = manager;
 }
	static TwitterBinding()
	{
		TwitterManager.noop();
	}
Пример #23
0
 public UserController(UserManager managerUser, TwitterManager twitterManager) : base(managerUser)
 {
     _twitterManager = twitterManager;
 }
Пример #24
0
        public void GenerateShop()
        {
            Directory.CreateDirectory($"{Root}Cache");

            Console.WriteLine("Generating Shop...");

            var watch = new Stopwatch();

            watch.Start();

            var      shop = Shop.Get(Environment.GetEnvironmentVariable("APIKEY")).Data;
            DateTime date = shop.ShopDate;

            Dictionary <StorefrontEntry, BitmapData> entries = new Dictionary <StorefrontEntry, BitmapData>();

            if (shop.HasFeatured)
            {
                GenerateEntries(shop.Featured.Entries, ref entries);
            }
            if (shop.HasDaily)
            {
                GenerateEntries(shop.Daily.Entries, ref entries);
            }
            if (shop.HasSpecialFeatured)
            {
                GenerateEntries(shop.SpecialFeatured.Entries, ref entries);
            }
            if (shop.HasSpecialDaily)
            {
                GenerateEntries(shop.SpecialDaily.Entries, ref entries);
            }

            Dictionary <Section, BitmapData> bitmaps = GenerateSections(entries);
            List <Section> sections = bitmaps.Keys.ToList();

            sections.Sort(SectionComparer.Comparer);

            shop    = null;
            entries = null;
            GC.Collect();

            using (var full = A(sections, bitmaps))
            {
                using (var image = SKImage.FromBitmap(full))
                {
                    using (var data = image.Encode(SKEncodedImageFormat.Jpeg, 100))
                    {
                        using (var stream = File.OpenWrite($"{Root}Output/{date.ToString("dd-MM-yyyy")}.jpg"))
                        {
                            data.SaveTo(stream);
                        }
                    }
                }

                string suffix = (date.Day % 10 == 1 && date.Day != 11) ? "st"
                    : (date.Day % 10 == 2 && date.Day != 12) ? "nd"
                    : (date.Day % 10 == 3 && date.Day != 13) ? "rd"
                    : "th";

                string status = $"Fortnite Item Shop\n{string.Format("{0:dddd},{0: d}{1} {0:MMMM yyyy}", date, suffix)}\n\nIf you want to support me,\nconsider using my code 'Chic'\n\n#Ad";

                #region TryCatchSend
                try
                {
                    TwitterManager.TweetWithMedia($"{Root}Output/{date.ToString("dd-MM-yyyy")}.jpg", status);
                } catch (Exception)
                {
                    int w = (int)(full.Width / 1.5);
                    int h = (int)(full.Height / 1.5);

                    SaveToCache(full, "shop");
                    sections = null;
                    bitmaps  = null;

                    GC.Collect();

                    using (var bmp = new SKBitmap(w, h))
                    {
                        using (var c = new SKCanvas(bmp))
                            using (var b = LoadFromCache("shop"))
                            {
                                c.DrawBitmap(b, new SKRect(0, 0, w, h));
                            }

                        using (var image = SKImage.FromBitmap(bmp))
                        {
                            using (var dat = image.Encode(SKEncodedImageFormat.Png, 100))
                            {
                                using (var stream = File.OpenWrite($"{Root}Output/{date.ToString("dd-MM-yyyy")}_small.png"))
                                {
                                    dat.SaveTo(stream);
                                }
                            }
                        }
                    }

                    try
                    {
                        TwitterManager.TweetWithMedia($"{Root}Output/{date.ToString("dd-MM-yyyy")}_small.png", status);
                    }
                    catch (Exception)
                    {
                        TwitterManager.Tweet($"Fortnite Item Shop\n{ string.Format("{0:dddd},{0: d}{1} {0:MMMM yyyy}", date, suffix)}\n\nI was not able to send the shop image.\nClick the link to view the shop:\nhttps://bit.ly/ChicIsCoolioShop");
                    }
                }
                #endregion
            }

            watch.Stop();
            Console.WriteLine($"Done in {watch.Elapsed} ms");
            watch = null;

            DeleteFromCache("shop");
            DeleteFromCache(file => file.StartsWith("section_"));

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
Пример #25
0
        static async Task Main(string[] args)
        {
            // Wait for the debugger to attach if requested
            if (args.Length > 0 && args[0].ToLower() == "--waitfordebugger")
            {
                Console.WriteLine("Waiting for debugger...");

                while (!Debugger.IsAttached)
                {
                    await Task.Delay(1000);
                }

                Console.WriteLine("Debugger attached!");
            }

            // Get the type of the Configuration
            Type configType = TypeUtils.GetSubclassOfType <Configuration>();

            // Declare variable to hold the configuration
            Configuration configuration;

            // Check if the config file exists
            if (!File.Exists(LOCAL_CONFIGURATION))
            {
                // Create a new dummy Configuration
                configuration = (Configuration)Activator.CreateInstance(TypeUtils.GetSubclassOfType <Configuration>());
                configuration.SetDefaults();

                // Write out the default config
                configuration.Write(LOCAL_CONFIGURATION);

                Console.WriteLine("Wrote default configuration to " + LOCAL_CONFIGURATION);

                return;
            }

            // Create the Exception logs directory
            System.IO.Directory.CreateDirectory(LOCAL_EXCEPTION_LOGS_DIRECTORY);

            // Load the Configuration
            Configuration.Load(configType, LOCAL_CONFIGURATION);

            // Initialize the Localizer
            Localizer.Initialize();

            // Initialize the HandlerMapper
            HandlerMapper.Initialize();

            // Initialize the KeysetManager
            KeysetManager.Initialize();

            // Initialize DAuth
            DAuthApi.Initialize();

            // Initialize BCAT
            BcatApi.Initialize();

            // Initialize S3
            S3Api.Initialize();

            // Initialize DigitalOcean
            DoApi.Initialize();

            // Initialize Twitter
            TwitterManager.Initialize();

            // Initialize the DiscordBot
            await DiscordBot.Initialize();

            // Initialize the Scheduler
            await QuartzScheduler.Initialize();

            // Wait for the bot to fully initialize
            while (!DiscordBot.IsReady)
            {
                await Task.Delay(1000);
            }

            // Print out to the logging channel that we're initialized
            await DiscordBot.LoggingChannel.SendMessageAsync("\\*\\*\\* **Initialized**");

            // Schedule the BootHousekeepingJob
            await QuartzScheduler.ScheduleJob(TypeUtils.GetSubclassOfType <BootHousekeepingJob>(), "Immediate");

            // Register the SIGTERM handler
            AssemblyLoadContext.Default.Unloading += async x =>
            {
                // Run Shutdown in fast mode
                await Shutdown.CreateAndRun(true);
            };

            await Task.Delay(-1);
        }
Пример #26
0
        public void DrawInfo()
        {
            var teams = Battles.GetScoreInfo().Props.PageProps.Teams;

            teams.Sort(TeamComparer.Comparer);

            var teamsDictionary = new Dictionary <string, List <Team> >();

            foreach (var team in teams)
            {
                if (teamsDictionary.ContainsKey(team.Region))
                {
                    teamsDictionary[team.Region].Add(team);
                }
                else
                {
                    teamsDictionary.Add(team.Region, new List <Team> {
                        team
                    });
                }
            }

            List <BitmapInfo> bitmaps = new List <BitmapInfo>();

            int teamHeight  = 50;
            int offset      = 20;
            int regionWidth = 300 + offset * 2;

            foreach (var region in teamsDictionary)
            {
                int regionHeight = teamHeight * region.Value.Count + 18 + offset * 2;

                /*using (*/
                var bitmap = new SKBitmap(regionWidth, regionHeight);//)
                //{
                using (var c = new SKCanvas(bitmap))
                {
                    using (var path = new SKPath())
                    {
                        path.MoveTo(15, 15);
                        path.LineTo(regionWidth - 10, 10);
                        path.LineTo(regionWidth - 20, regionHeight - 15);
                        path.LineTo(10, regionHeight - 10);
                        path.Close();

                        c.DrawPath(path, new SKPaint
                        {
                            IsAntialias   = true,
                            FilterQuality = SKFilterQuality.High,
                            Color         = SKColors.White,
                            ImageFilter   = SKImageFilter.CreateDropShadow(0, 0, 5, 5, SKColors.Black)
                        });
                        //c.DrawRect(offset, offset, width, height, new SKPaint { Color = SKColors.White });
                    }

                    using (var flag = BitmapFromUrl($"https://teambattles.fortnite.com/image/flag/{region.Value[0].Nationality.ToLower()}.png", region.Value[0].Nationality.ToLower()))
                    {
                        int _x = (regionWidth - flag.Width) / 2;
                        int _y = offset;

                        c.DrawBitmap(flag, _x, _y, new SKPaint
                        {
                            IsAntialias   = true,
                            FilterQuality = SKFilterQuality.High,
                            ImageFilter   = SKImageFilter.CreateDropShadow(0, 0, 5, 5, SKColors.Black)
                        });
                    }

                    int y = 18 + offset;

                    foreach (var team in region.Value)
                    {
                        c.DrawText(team.Name, 10 + offset, y + 36, new SKPaint
                        {
                            IsAntialias   = true,
                            FilterQuality = SKFilterQuality.High,
                            TextSize      = 20,
                            Typeface      = ChicTypefaces.BurbankBigRegularBlack,
                            Color         = SKColors.Black
                        });

                        using (var paint = new SKPaint
                        {
                            IsAntialias = true,
                            FilterQuality = SKFilterQuality.High,
                            TextSize = 20,
                            Typeface = ChicTypefaces.BurbankBigRegularBlack,
                            Color = SKColors.Black
                        })
                        {
                            c.DrawText($"{team.Score.ToString("N0")}",
                                       regionWidth - 10 - offset - paint.MeasureText($"{team.Score.ToString("N0")}"), y + 36, paint);
                        }

                        y += teamHeight;
                    }
                }

                bitmaps.Add(SaveToCache(bitmap, $"region_{region.Value[0].Nationality}"));
            }

            int maxRegionsPerRow = 7;

            maxRegionsPerRow = Math.Clamp(bitmaps.Count, 0, maxRegionsPerRow);

            int extraHeight   = 800;
            int _regionHeight = bitmaps.Max(bitmap => bitmap.Height);

            int o = 50;

            int width  = maxRegionsPerRow * (regionWidth + o) + o;
            int height = (int)Math.Ceiling((decimal)bitmaps.Count / maxRegionsPerRow) * (_regionHeight + o) + o;

            int extraExtraHeight = (int)(width * 0.5625f) - height - extraHeight;

            extraExtraHeight = extraExtraHeight >= 0 ? extraExtraHeight : 0;
            int extraWidth = (int)((height + extraHeight) * 1.77777777778f) - width;

            extraWidth = extraWidth >= 0 ? extraWidth : 0;

            using (var full = new SKBitmap(width + extraWidth, height + extraHeight + extraExtraHeight))
            {
                using (var c = new SKCanvas(full))
                {
                    using (var paint = new SKPaint
                    {
                        IsAntialias = true,
                        FilterQuality = SKFilterQuality.High,
                        Shader = SKShader.CreateLinearGradient(new SKPoint(-100, -200), new SKPoint(width + 300, height + 500),
                                                               new SKColor[]
                        {
                            new SKColor(56, 33, 50),
                            new SKColor(192, 4, 92),
                            new SKColor(243, 9, 76),
                            new SKColor(249, 96, 83),
                            new SKColor(250, 111, 84),
                            new SKColor(255, 232, 75),
                            new SKColor(255, 239, 74),
                        }, SKShaderTileMode.Clamp)
                    })
                    {
                        c.DrawRect(0, 0, width + extraWidth, extraHeight, paint);
                    }

                    using (var logo = SKBitmap.Decode($"{Root}Resources/logo.png"))
                    {
                        c.DrawBitmap(logo.Resize(new SKSizeI(logo.Width * 2, logo.Height * 2), SKFilterQuality.High), 100, 25);
                    }

                    using (var lovely = SKBitmap.Decode($"{Root}Resources/hero.webp"))
                    {
                        c.DrawBitmap(lovely, width + extraWidth - lovely.Width, 0);
                    }

                    using (var path = new SKPath())
                    {
                        path.MoveTo(0, 695);
                        path.LineTo((width + extraWidth) / 2, 745);
                        path.LineTo(width + extraWidth - (int)((width + extraWidth) / 1.7f), 715);
                        path.LineTo(width + extraWidth, 790);
                        path.LineTo(width + extraWidth, height + extraHeight);
                        path.LineTo(0, height + extraHeight);
                        path.Close();

                        c.DrawPath(path, new SKPaint
                        {
                            IsAntialias   = true,
                            FilterQuality = SKFilterQuality.High,
                            Color         = SKColors.White,
                            ImageFilter   = SKImageFilter.CreateDropShadow(0, -2, 5, 5, SKColors.Black)
                        });
                    }

                    int x = o;
                    int y = o + extraHeight;

                    int xi = 1;

                    foreach (var bmp in bitmaps)
                    {
                        c.DrawBitmap(LoadFromCache(bmp), x, y);

                        if (xi == maxRegionsPerRow)
                        {
                            x  = o;
                            y += _regionHeight + o;
                            xi = 1;
                        }
                        else
                        {
                            x += regionWidth + o;
                            xi++;
                        }
                    }

                    using (var watermark = SKBitmap.Decode($"{Root}Resources/watermark.png"))
                    {
                        c.DrawBitmap(watermark, width - extraWidth - watermark.Width, height + extraHeight - extraExtraHeight - watermark.Height, new SKPaint
                        {
                            IsAntialias   = true,
                            FilterQuality = SKFilterQuality.High,
                            ImageFilter   = SKImageFilter.CreateDropShadow(0, 0, 5, 5, SKColors.Black)
                        });
                    }
                }

                using (var image = SKImage.FromBitmap(full))
                {
                    using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
                    {
                        using (var stream = File.OpenWrite($"{Root}Output/output.png"))
                        {
                            data.SaveTo(stream);
                        }
                    }
                }
            }

            TwitterManager.TweetWithMedia($"{Root}Output/output.png", "Fortnite Hearts Wild Team Battles results!\nIt's over guys. Woo");

            foreach (var file in Directory.GetFiles($"{Root}Cache").Where(x => x.Contains("region_")))
            {
                File.Delete(file);
            }

            GC.Collect();
            Console.WriteLine("Done");
        }
Пример #27
0
        public void DrawShop(ShopV2 shop)
        {
            var watch = new Stopwatch();

            watch.Start();
            var sections = DrawSections(shop);

            int width  = sections[0].Width;
            int height = 0;

            sections.ForEach(section => height += section.Height);

            using (var bitmap = new SKBitmap(width, height))
            {
                using (var c = new SKCanvas(bitmap))
                {
                    int y = 0;

                    foreach (var section in sections)
                    {
                        using (var sectionBitmap = LoadFromCache(section))
                        {
                            c.DrawBitmap(sectionBitmap, 0, y);
                            y += section.Height;
                        }
                    }
                }

                string fileName = $"{shop.ShopDate.ToString("dd-MM-yyyy")}.jpg";

                using (var image = SKImage.FromBitmap(bitmap))
                {
                    using (var data = image.Encode(SKEncodedImageFormat.Jpeg, 100))
                    {
                        using (var stream = File.OpenWrite($"{Root}Output/{fileName}"))
                        {
                            data.SaveTo(stream);
                        }
                    }
                }

                string suffix = (shop.ShopDate.Day % 10 == 1 && shop.ShopDate.Day != 11) ? "st"
                    : (shop.ShopDate.Day % 10 == 2 && shop.ShopDate.Day != 12) ? "nd"
                    : (shop.ShopDate.Day % 10 == 3 && shop.ShopDate.Day != 13) ? "rd"
                    : "th";

                string status = $"Fortnite Item Shop\n{string.Format("{0:dddd},{0: d}{1} {0:MMMM yyyy}", shop.ShopDate, suffix)}\n\nIf you want to support me,\nconsider using my code 'Chic'\n\n#Ad";

                #region TryCatchSend
                try
                {
                    TwitterManager.TweetWithMedia($"{Root}Output/{fileName}", status);
                } catch (Exception)
                {
                    int w = (int)(bitmap.Width / 1.5);
                    int h = (int)(bitmap.Height / 1.5);

                    SaveToCache(bitmap, "shop");
                    sections = null;

                    GC.Collect();

                    using (var bmp = new SKBitmap(w, h))
                    {
                        using (var c = new SKCanvas(bmp))
                            using (var b = LoadFromCache("shop"))
                            {
                                c.DrawBitmap(b, new SKRect(0, 0, w, h));
                            }

                        using (var image = SKImage.FromBitmap(bmp))
                        {
                            using (var dat = image.Encode(SKEncodedImageFormat.Png, 100))
                            {
                                using (var stream = File.OpenWrite($"{Root}Output/{fileName.Replace(".jpg", "")}_small.png"))
                                {
                                    dat.SaveTo(stream);
                                }
                            }
                        }
                    }

                    try
                    {
                        TwitterManager.TweetWithMedia($"{Root}Output/{fileName.Replace(".jpg", "")}_small.png", status);
                    }
                    catch (Exception)
                    {
                        TwitterManager.Tweet($"Fortnite Item Shop\n{ string.Format("{0:dddd},{0: d}{1} {0:MMMM yyyy}", shop.ShopDate, suffix)}\n\nI was not able to send the shop image.\nClick the link to view the shop:\nhttps://bit.ly/ChicIsCoolioShop");
                    }
                }
                #endregion
            }

            watch.Stop();
            Console.WriteLine($"Done in {watch.Elapsed}");
        }
Пример #28
0
        public static Task HandleFestival(RomType romType, Dictionary <string, byte[]> data, FestivalSetting previousFestival, FestivalSetting newFestival, byte[] rawFile)
        {
            // Don't do anything
            if (previousFestival.FestivalId == newFestival.FestivalId)
            {
                return(Task.FromResult(0));
            }

            // Get the language based off the RomType
            Language language;

            switch (romType)
            {
            case RomType.NorthAmerica:
                language = Language.EnglishUS;
                break;

            case RomType.Europe:
                language = Language.EnglishUK;
                break;

            case RomType.Japan:
                language = Language.Japanese;
                break;

            default:
                throw new Exception("Unsupported RomType (A)");
            }

            // Create the title
            string localizedRomType = Localizer.Localize(string.Format("romtype.{0}", romType.ToString().ToLower()), language);
            string title            = string.Format(Localizer.Localize("festival.twitter.title", language), localizedRomType);

            // Create the description
            string localizedDescription = Localizer.Localize("festival.twitter.description", language);
            string startTime            = Localizer.LocalizeDateTime(newFestival.Times.Start, language);
            string endTime = Localizer.LocalizeDateTime(newFestival.Times.End, language);

            localizedDescription = string.Format(localizedDescription, newFestival.Teams[0].ShortName[language], newFestival.Teams[1].ShortName[language], startTime, endTime);

            // Get the region code based off the RomType
            string regionCode;

            switch (romType)
            {
            case RomType.NorthAmerica:
                regionCode = "na";
                break;

            case RomType.Europe:
                regionCode = "eu";
                break;

            case RomType.Japan:
                regionCode = "jp";
                break;

            default:
                throw new Exception("Unsupported RomType (B)");
            }

            // Create the URL
            string url = string.Format(Localizer.Localize("festival.twitter.url", language), regionCode);

            // Get the target Twitter account
            string targetAccount;

            if (Configuration.LoadedConfiguration.IsProduction)
            {
                if (romType == RomType.NorthAmerica || romType == RomType.Europe)
                {
                    targetAccount = "JelonzoBot";
                }
                else if (romType == RomType.Japan)
                {
                    targetAccount = "JelonzoBotJP";
                }
                else
                {
                    throw new Exception("Unsupported RomType (C)");
                }
            }
            else
            {
                targetAccount = "JelonzoTest";
            }

            // Get the image
            string imagePath = string.Format(FileCache.FESTIVAL_PANEL_PATH, romType.ToString(), newFestival.FestivalId);

            byte[] image = File.ReadAllBytes(imagePath);

            // Tweet
            TwitterManager.GetAccount(targetAccount).Tweet(title, localizedDescription, url, image);

            return(Task.FromResult(0));
        }
Пример #29
0
        public async Task LoadTwitterFeeds()
        {
            //ObservableCollection<Tweet> result = null;

            if (NetworkInterface.GetIsNetworkAvailable())
            {
                try
                {
                    var twitterManager = new TwitterManager();
                    var account        = twitterManager.Service;
                    var auth           = new ApplicationOnlyAuthorizer()
                    {
                        CredentialStore = new InMemoryCredentialStore
                        {
                            ConsumerKey    = account.ConsumerKey,
                            ConsumerSecret = account.ConsumerSecret,
                        },
                    };
                    await auth.AuthorizeAsync();

                    var    twitterContext = new TwitterContext(auth);
                    Search queryResponse  = null;
                    var    hashtag        = "\"#techedindia\"";
                    queryResponse = await
                                        (from tweet in twitterContext.Search
                                        where tweet.Type == SearchType.Search &&
                                        tweet.Query == hashtag &&
                                        tweet.Count == 20
                                        select tweet).SingleOrDefaultAsync();


                    if (queryResponse != null && queryResponse.Statuses != null)
                    {
                        var queryTweets = queryResponse.Statuses;
                        var tweets      = (from s in queryTweets
                                           select new Tweet
                        {
                            Text = s.Text,
                            CreatedAt = s.CreatedAt,
                            ScreenName = s.User.ScreenNameResponse,
                            ProfileImage = s.User.ProfileImageUrl
                        }).ToList();
                        if (tweets != null)
                        {
                            TwitterFeeds = tweets.ToObservableCollection();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Insights.Report(ex);
                }
                //await Task.Factory.StartNew(() =>
                //{
                //    var done = false;
                //    try
                //    {
                //        var twitterManager = new TwitterManager();
                //        twitterManager.Service.Search(new SearchOptions() { Q = "#techedindia", Count = 20 },
                //            (ts, rep) =>
                //            {
                //                if (rep.StatusCode == HttpStatusCode.OK)
                //                {
                //                    result = ts.Statuses.ToObservableCollection();
                //                }
                //                done = true;
                //            });
                //        while (!done)
                //        {
                //        }
                //    }
                //    catch (Exception ex)
                //    {

                //    }
                //});
                //if (result != null)
                //    TwitterFeeds = result;
            }
        }