protected async Task <string> HandleTweetWithoutLocationData(ITweet tweet, string filterHashtag)
        {
            //check all hashtags, one by one to see if they contain a location
            foreach (var hashtag in tweet.Hashtags.Where(x => $"#{x.Text}" != filterHashtag).ToList())
            {
                var locationResult = await _locationFinder.GetLocationFromStringAsync(hashtag.Text);

                if (locationResult == null)
                {
                    continue;
                }

                var tweetData = new TweetData
                {
                    CreatedDate        = tweet.CreatedAt,
                    Image              = tweet.Media.First(x => x.MediaType != "video").MediaURLHttps,
                    Text               = tweet.Text,
                    TweetId            = tweet.IdStr,
                    Coords             = new double[] { locationResult.Coordinates.Latitude, locationResult.Coordinates.Longitude },
                    Area               = locationResult.AdminDistrict2,
                    TwitterHandle      = tweet.CreatedBy.ScreenName,
                    LocationConfidence = locationResult.Confidence.ToString(),
                    TweetUrl           = tweet.Url
                };

                return(await ForwardTweetData(tweetData));
            }

            return(null);
        }
        protected async Task <string> HandleTweetWithLocationData(ITweet tweet)
        {
            Logging.Debug("Tweet place bounding box:");
            foreach (var coord in tweet.Place.BoundingBox.Coordinates)
            {
                Logging.Debug($"{coord.Latitude} - {coord.Longitude}");
            }

            var coordinateList = tweet.Place.BoundingBox.Coordinates.Select(x => new LocationFinder.Coordinates {
                Latitude = x.Latitude, Longitude = x.Longitude
            }).ToList();
            var centerPoint = _locationFinder.GetCentralGeoCoordinate(coordinateList);

            Logging.Debug($"Center point: {centerPoint.Latitude} - {centerPoint.Longitude}");

            var tweetData = new TweetData
            {
                CreatedDate        = tweet.CreatedAt,
                Image              = tweet.Media.First(x => x.MediaType != "video").MediaURLHttps,
                Text               = tweet.Text,
                TweetId            = tweet.IdStr,
                Coords             = new double[] { centerPoint.Latitude, centerPoint.Longitude },
                Area               = "TODO", //todo: get area for this location!
                TwitterHandle      = tweet.CreatedBy.ScreenName,
                LocationConfidence = LocationConfidence.EXACT.ToString(),
                TweetUrl           = tweet.Url
            };

            return(await ForwardTweetData(tweetData));
        }
    // Once data has been fetched using the GET requests and we have been allocated
    // a space in the "Wallet" to populate, we have to instantiate the nodes and links.
    // Before instantiating, we have to translate the nodes such that the nodes fit accurately
    // in the "Wallet" section.

    // Translation order:
    // Image coordinates -> Coordinates within pixelDeviation rect
    // -> Coordinates within section object.
    IEnumerator PlaceResultsInSection(TweetData results, float translationX
                                      , float translationY, GameObject panel, int panelNumber)
    {
        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        sw.Start();
        float frameStartTime = 0.0f;

        foreach (TweetDataNode node in results.Nodes)
        {
            if (sw.ElapsedMilliseconds - frameStartTime >= Commons.maxMSspentPerFrame)
            {
                yield return(null);

                frameStartTime = sw.ElapsedMilliseconds;
            }

            node.Translate(translationX, translationY);
            PlaceNodeInSection(node, panelNumber, panel);
        }
        foreach (TweetDataLink link in results.Links)
        {
            if (sw.ElapsedMilliseconds - frameStartTime >= Commons.maxMSspentPerFrame)
            {
                yield return(null);

                frameStartTime = sw.ElapsedMilliseconds;
            }

            link.Translate(translationX, translationY);
            PlaceLinkInSection(link, panelNumber, panel);
        }
    }
Beispiel #4
0
 public static void TransToTweetData()
 {
     for (int i = 0; i < Info.items.Count; i++)
     {
         TWEET     a     = Info.items [i];
         TweetData tweet = new TweetData();
         tweet.id       = a.tweet_id;
         tweet.userId   = a.user_id;
         tweet.info     = a.tweet_info;
         tweet.order    = a.order;
         tweet.isSecret = a.is_secret;
         tweet.pics     = new int[a.pic_array.Count];
         for (int m = 0; m < tweet.pics.Length; m++)
         {
             tweet.pics[m] = a.pic_array[m];
         }
         tweet.location = a.location;
         List <TweetData> tweets;
         if (ZoneManager.Instance.id2Tweet.TryGetValue(a.user_id, out tweets))
         {
         }
         else
         {
             tweets = new List <TweetData> ();
             ZoneManager.Instance.id2Tweet.Add(a.user_id, tweets);
         }
         tweets.Add(tweet);
     }
 }
Beispiel #5
0
        public void ProcessFindsHashTagAndIncrementsTag()
        {
            string hashtag  = "";
            var    hashTags = new Hashtag[1];

            hashTags[0] = new Hashtag
            {
                Tag = hashtag
            };

            TweetData tweetData = new TweetData
            {
                Data = new Tweet
                {
                    CreatedAt = DateTime.Today,
                    Text      = "Non Empty Text Data",
                    Entities  = new TweetEntities
                    {
                        Hashtags = hashTags
                    }
                }
            };

            string tweetDataJson = GetTweetJsonString(tweetData);

            Func <Task <string> > taskWithTweetData = () => Task.FromResult(tweetDataJson);
            Task <string>         tweetDataTask     = Task.Run(taskWithTweetData);
            Task processTask = _tweetProcessor.Process(tweetDataTask);

            Assert.True(processTask.Wait(1000));
            _mockTwitterDataCapturer.Verify(mtdc => mtdc.IncrementHashtag(hashtag), Times.Once);
        }
Beispiel #6
0
        public void ProcessFindsUrlAndIncrementsTweetWithUrl()
        {
            string expectedUrl = "http://fakewebsite.com";

            var urls = new Url[1];

            urls[0] = new Url
            {
                ExpandedUrl = expectedUrl
            };

            TweetData tweetData = new TweetData
            {
                Data = new Tweet
                {
                    CreatedAt = DateTime.Today,
                    Text      = "Non Empty Text Data",
                    Entities  = new TweetEntities
                    {
                        Urls = urls
                    }
                }
            };

            string tweetDataJson = GetTweetJsonString(tweetData);

            Func <Task <string> > taskWithTweetData = () => Task.FromResult(tweetDataJson);
            Task <string>         tweetDataTask     = Task.Run(taskWithTweetData);
            Task processTask = _tweetProcessor.Process(tweetDataTask);

            Assert.True(processTask.Wait(1000));
            _mockUrlHandler.Verify(muh => muh.GetDomainFromUrl(expectedUrl), Times.Once);
            _mockTwitterDataCapturer.Verify(mtdc => mtdc.IncrementTweetWithUrl(), Times.Once);
        }
Beispiel #7
0
        public static void TweetWithImage(string gameId, string text, params string[] hashTags)
        {
            if (_currentCoroutine != null)
            {
                Debug.Log("画像アップロード中に多重呼び出しされました。");
                return;
            }

            var tweetData = new TweetData(gameId, text, hashTags);

            var title = tweetData.GameUrl;
            var desc  = text;

            _currentCoroutine = CoroutineHandler.StartStaticCoroutine(
                GyazoUploader.CaptureScreenshotAndUpload(
                    title
                    , desc
                    , (res, error) =>
            {
                if (string.IsNullOrEmpty(error))
                {
                    Debug.Log("画像アップロード成功 : " + res.permalink_url);
                    //エラーなし => ツイートする
                    tweetData.ImageUrl = res.permalink_url;
                    Tweet(tweetData);
                }
                else
                {
                    //エラーあり
                    Debug.LogError("画像アップロード失敗 : " + error);
                }

                _currentCoroutine = null;
            }));
        }
Beispiel #8
0
 private void Persist(string topic, TweetData tweetData)
 {
     try
     {
         using (var dbConnection = new SqlConnection(_connectionString))
         {
             var spParameters = new DynamicParameters();
             spParameters.Add("@TweetId", tweetData.TweetId);
             spParameters.Add("@Topic", topic);
             spParameters.Add("@Content", tweetData.OriginalContent);
             spParameters.Add("@TweetedTime", tweetData.TweetedTime);
             if (tweetData.ReTweet)
             {
                 spParameters.Add("@OriginalTweetId", tweetData.OriginalTweetId);
                 dbConnection.Execute("[dbo].[PersistReTweet]", spParameters, commandTimeout: 30, commandType: CommandType.StoredProcedure);
             }
             else
             {
                 dbConnection.Execute("[dbo].[PersistTweet]", spParameters, commandType: CommandType.StoredProcedure);
             }
         }
     }catch (SqlException e) when(e.Number == 2627)
     {
         _log.Warn($"Tweet with Id: {tweetData.OriginalTweetId} already exists in dbo.TweetData.");
     }
 }
Beispiel #9
0
        public bool ShouldTweet()
        {
            string twitterUsername = _config.GetValue <string>("TwitterUsername");
            string fullUrl         = $"https://api.twitter.com/2/tweets/search/recent?query=from:{twitterUsername}&tweet.fields=created_at&expansions=author_id&user.fields=created_at";

            try
            {
                using (var http = new HttpClient())
                {
                    http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _config.GetValue <string>("BearerToken"));
                    var httpResponse = http.GetAsync(fullUrl).Result;
                    var responseBody = httpResponse.Content.ReadAsStringAsync().Result;

                    TweetData twitterData = JsonConvert.DeserializeObject <TweetData>(responseBody);

                    DateTime mostRecentTweet = twitterData.data.Max(x => x.created_at);

                    if (mostRecentTweet.Date == DateTime.Today)
                    {
                        return(false);
                    }
                    else
                    {
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }
        }
        public void ProcessTwitterStreamProcessesTweet()
        {
            Task <string> capturedTaskString = null;


            _mockTweetProcessor.Setup(mtp => mtp.Process(It.IsAny <Task <string> >())).Callback((Task <string> taskString) => capturedTaskString = taskString);

            TweetData tweetData = new TweetData
            {
                Data = new Tweet
                {
                    CreatedAt = DateTime.Today,
                    Id        = "1234",
                    Text      = "Tweet Text"
                }
            };

            string tweetJson = JsonConvert.SerializeObject(tweetData);

            _testMessageHandler.AddMessagesToStream(Enumerable.Repeat(tweetJson, 50000));


            Task processTask = _twitterStreamProcessor.ProcessTwitterStream(_cancellationTokenSource.Token);

            Assert.True(processTask.Wait(1000));

            _mockTweetProcessor.Verify(mtp => mtp.Process(It.IsAny <Task <string> >()), Times.AtLeastOnce);
            string capturedJson = capturedTaskString.Result;

            Assert.Equal(tweetJson, capturedJson);
        }
Beispiel #11
0
        /// <summary>
        /// Attempts to hit the given URI and returns a tweet (couldnt get this call to work, was working in postman and ran out of time while trying to investigate)
        /// </summary>
        /// <param name="uri">a provided URI that the http client will use to perform a get operation</param>
        /// <param name="count">the number of tweets to respond with (search through twitter API documentation and couldnt find how to implement this)</param>
        /// <returns>a list of tweets that meet the query criteria</returns>
        public async Task <List <Tweet> > GetTweetsByUri(string uri, int count)
        {
            using (var client = new HttpClient())
            {
                string bearer = ConfigurationManager.AppSettings["BearerToken"];
                string auth   = $"Bearer {bearer}";

                client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", auth);
                client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "SynergiTweetTrawler");
                client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "*/*");
                client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
                client.DefaultRequestHeaders.TryAddWithoutValidation("Connection", "keep-alive");

                try
                {
                    var response = await client.GetAsync(uri);

                    var responseContent = await response.Content.ReadAsStringAsync();

                    JavaScriptSerializer ser             = new JavaScriptSerializer();
                    TweetData            TwitterResponse = ser.Deserialize <TweetData>(responseContent);

                    return(TwitterResponse.tweets);
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                    Console.ReadLine();
                    throw;
                }
            }
        }
        public TweetItemViewModel(TweetData tweetData)
        {
            this.tweetData = tweetData;

            this.IconUrl = this.tweetData.IconUrl
                           .ToReadOnlyReactivePropertySlim()
                           .AddTo(this.disposables);

            this.ScreenName = this.tweetData.ScreenName
                              .ToReadOnlyReactivePropertySlim()
                              .AddTo(this.disposables);

            this.Name = tweetData.Name
                        .ToReadOnlyReactivePropertySlim()
                        .AddTo(this.disposables);

            this.Text = tweetData.Text
                        .ToReadOnlyReactivePropertySlim()
                        .AddTo(this.disposables);

            var bitmapImage = new BitmapImage();

            bitmapImage.BeginInit();
            bitmapImage.UriSource = new Uri(this.IconUrl.Value);
            bitmapImage.EndInit();
            IconImage       = new ReactivePropertySlim <ImageSource>( );
            IconImage.Value = bitmapImage;
        }
Beispiel #13
0
        public static TweetData Convert(JObject tweetJson)
        {
            if (tweetJson.TryGetValue("limit", out _))
            {
                return(null); // you have made too many requests for twitter, you naughty dog
            }

            var tweet = new TweetData
            {
                TweetId     = tweetJson.GetValue("id").Value <long>(),
                TweetedTime = Epoch.AddMilliseconds(tweetJson.GetValue("timestamp_ms").Value <long>()),
                ReTweet     = tweetJson.TryGetValue("retweeted_status", out _)
            };

            if (tweet.ReTweet)
            {
                tweetJson = tweetJson.GetValue("retweeted_status").ToObject <JObject>();
            }

            tweet.OriginalTweetId = tweetJson.GetValue("id").Value <long>();
            tweet.OriginalContent = tweetJson.GetValue("truncated").Value <bool>()
                ? tweetJson.GetValue("extended_tweet").ToObject <JObject>().GetValue("full_text").Value <string>()
                : tweetJson.GetValue("text").Value <string>();

            return(tweet);
        }
Beispiel #14
0
        public bool CreateTweet(TweetData tweetData)
        {
            bool status = false;

            try
            {
                tweetData.createdAt = DateTime.Now;
                tweetData.updatedAt = DateTime.Now;
                status = TweetRepository.Create(tweetData);
            }
            catch (Exception ex)
            {
                this.ExceptionMessage = "Meesage : " + ex.Message + " ,Stacktrace: " + ex.StackTrace;
            }
            return(status);
        }
Beispiel #15
0
        private async Task <string> ForwardTweetData(TweetData data)
        {
            var    tweetForwarder = _tweetForwarderFactory.NewForwarder();
            string responseText;

            try
            {
                responseText = await tweetForwarder.ForwardTweetData(data);
            }
            catch (Exception e)
            {
                Logging.Error($"Error forwarding data to client: {e.Message}");
                Logging.Debug(JsonConvert.SerializeObject(data));
                return(null);
            }

            return(responseText);
        }
Beispiel #16
0
        public void ProcessFindsMultipleImageUrlsButOnlyIncrementsTweetsWithImagesOnce()
        {
            string expectedDomain = "fakewebsite.com";
            string expectedUrl    = $"http://{expectedDomain}";

            _mockUrlHandler.Setup(muh => muh.GetDomainFromUrl(expectedUrl)).Returns(expectedDomain);
            _mockUrlHandler.Setup(muh => muh.DomainIsImageDomain(expectedDomain)).Returns(true);

            var urls = new Url[2];

            urls[0] = new Url
            {
                ExpandedUrl = expectedUrl
            };
            urls[1] = new Url
            {
                ExpandedUrl = expectedUrl
            };

            TweetData tweetData = new TweetData
            {
                Data = new Tweet
                {
                    CreatedAt = DateTime.Today,
                    Text      = "Non Empty Text Data",
                    Entities  = new TweetEntities
                    {
                        Urls = urls
                    }
                }
            };

            string tweetDataJson = GetTweetJsonString(tweetData);

            Func <Task <string> > taskWithTweetData = () => Task.FromResult(tweetDataJson);
            Task <string>         tweetDataTask     = Task.Run(taskWithTweetData);
            Task processTask = _tweetProcessor.Process(tweetDataTask);

            Assert.True(processTask.Wait(1000));
            _mockUrlHandler.Verify(muh => muh.GetDomainFromUrl(expectedUrl), Times.Exactly(2));
            _mockUrlHandler.Verify(muh => muh.DomainIsImageDomain(expectedDomain), Times.Once);
            _mockTwitterDataCapturer.Verify(mtdc => mtdc.IncrementTweetWithImageUrl(), Times.Once);
        }
Beispiel #17
0
        public IActionResult CreateTweet([FromBody] TweetData tweetData)
        {
            bool status = false;

            try
            {
                status = tweetService.CreateTweet(tweetData);
                if (status)
                {
                    return(Ok("Tweet Posted"));
                }
                return(Ok("Unable to Post Tweet"));
            }
            catch (Exception ex)
            {
                this.ExceptionMessage = "Meesage : " + ex.Message + " ,Stacktrace: " + ex.StackTrace;
            }
            return(BadRequest());
        }
    // After determining the exact rectangles for each panel to grab data from, we
    // make the actual GET requests. This is done using Coroutines which check for
    // async operation completion every frame.
    IEnumerator GetJSON(DataRect rect)
    {
        UnityWebRequest req = SendRequest(rect);

        while (!req.isDone)
        {
            yield return(null);
        }
        if (req.isNetworkError || req.isHttpError)
        {
            Debug.Log(req.error);
            yield break;
        }

        GameObject panel = Wallet.Instance.MakeSpace();

        TweetData results = JSONParser.parseJSONObject <TweetData>(req.downloadHandler.text);

        yield return(StartCoroutine(PlaceResultsInSection(results, -rect.topLeft.x, -rect.topLeft.y, panel, rect.panelNumber)));
    }
Beispiel #19
0
        public void ProcessIncrementsTweetAtTweetTime()
        {
            TweetData tweetData = new TweetData
            {
                Data = new Tweet
                {
                    CreatedAt = DateTime.Today,
                    Text      = "Non Empty Text Data"
                }
            };

            string tweetDataJson = GetTweetJsonString(tweetData);

            Func <Task <string> > taskWithTweetData = () => Task.FromResult(tweetDataJson);
            Task <string>         tweetDataTask     = Task.Run(taskWithTweetData);
            Task processTask = _tweetProcessor.Process(tweetDataTask);

            Assert.True(processTask.Wait(1000));
            _mockTwitterDataCapturer.Verify(mtdc => mtdc.IncrementTweetAtTime(tweetData.Data.CreatedAt), Times.Once);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Reading text file");
            var textDataLines = File.ReadAllLines(@"TweetInputData.txt");

            Console.WriteLine($"File read contains {textDataLines.Length} lines");

            Console.WriteLine("Generating object collection...");
            var tweetList = new List <TweetData>();

            foreach (var item in textDataLines)
            {
                if (item.Length <= 280) //Trim the text length just in case.
                {
                    var tempObject = new TweetData()
                    {
                        TweetContent = item,
                        IsPublished  = false,
                        PublishDate  = "0000-00-00 00:00:00"
                    };

                    tweetList.Add(tempObject);
                }
            }

            Console.WriteLine($"Object collection generated... {tweetList.Count} of {textDataLines.Length}");
            Console.WriteLine("Ready to push data... presss enter to start");
            Console.ReadLine(); //Just to verify the numbers on console before we submit stuff. Azure ops can be expensive :)

            //Choose to do bulk operation if collection size is large...
            foreach (var item in tweetList)
            {
                Console.WriteLine("Inserting..." + item.TweetContent.Substring(0, 10) + "...");
                DocumentDbRepository <TweetData> .CreateItemAsync(item).GetAwaiter().GetResult();

                Task.Delay(100);
            }

            Console.WriteLine("Push done");
            Console.ReadLine();
        }
Beispiel #21
0
        private async Task <MessageItem> ConstructMessage(TweetData item)
        {
            var mainId = $"Message{item.Id}";
            var user   = await LoadUser(item.CreatorId).ConfigureAwait(false);

            var message = new MessageItem(user, item);
            var added   = cache.GetOrCreate(
                mainId,
                cacheEntry =>
            {
                cacheEntry.SlidingExpiration = TimeSpan.FromMinutes(1);
                return(message);
            });

            if (added == message)
            {
                added.User.Add(added);
            }

            return(message);
        }
Beispiel #22
0
        public void ProcessFindsEmojiInStringAndIncrementsIt()
        {
            string emoji = "🙏";

            TweetData tweetData = new TweetData
            {
                Data = new Tweet
                {
                    CreatedAt = DateTime.Today,
                    Text      = emoji
                }
            };

            string tweetDataJson = GetTweetJsonString(tweetData);

            Func <Task <string> > taskWithTweetData = () => Task.FromResult(tweetDataJson);
            Task <string>         tweetDataTask     = Task.Run(taskWithTweetData);
            Task processTask = _tweetProcessor.Process(tweetDataTask);

            Assert.True(processTask.Wait(1000));
            _mockTwitterDataCapturer.Verify(mtdc => mtdc.IncrementEmoji(emoji), Times.Once);
        }
Beispiel #23
0
    // public Db()
    // {
    //     GameManager.Instance.StartCoroutine(GetTweetData(server_adress, (tweetData, textureAvatar) =>
    //     {
    //         Debug.LogFormat("Incoming User {0}", tweetData.accountName);
    //         CanvasManager.Instance.avatarTweeter.sprite = Sprite.Create
    //         (
    //             textureAvatar,
    //              new Rect(0f, 0f, textureAvatar.width, textureAvatar.height),
    //              Vector2.zero
    //         );
    //     }));
    // }

    IEnumerator GetTweetData(string uri, Action <TweetData, Texture2D> tweetData)
    {
        using (UnityWebRequest request = UnityWebRequest.Get(uri))
        {
            yield return(request.SendWebRequest());

            if (!request.isNetworkError)
            {
                ServerResponse response;
                try
                {
                    response = JsonUtility.FromJson <ServerResponse>(request.downloadHandler.text);
                }
                catch
                {
                    Debug.LogWarning("JSON response very feo");
                    yield break;
                }
                if (response.statusCode == 1)
                {
                    TweetData data = JsonUtility.FromJson <TweetData>(response.dataJSON);

                    Texture2D texture;
                    using (UnityWebRequest textureRequest = UnityWebRequestTexture.GetTexture(data.pictureURL))
                    {
                        yield return(textureRequest.SendWebRequest());

                        texture = ((DownloadHandlerTexture)textureRequest.downloadHandler).texture;
                    }
                    tweetData(data, texture);
                }
            }
            else
            {
                Debug.LogWarning("No me puedo conectar al servidor: " + request.error);
            }
        }
    }
    // See GetJSON method for explanation.
    IEnumerator GetJSONTopBottom(DataRect topRect, DataRect bottomRect)
    {
        UnityWebRequest reqTop    = SendRequest(topRect);
        UnityWebRequest reqBottom = SendRequest(bottomRect);

        while (!reqTop.isDone)
        {
            yield return(null);
        }
        if (reqTop.isNetworkError || reqTop.isHttpError)
        {
            Debug.Log(reqTop.error);
            yield break;
        }

        while (!reqBottom.isDone)
        {
            yield return(null);
        }
        if (reqBottom.isNetworkError || reqBottom.isHttpError)
        {
            Debug.Log(reqBottom.error);
            yield break;
        }

        GameObject panel = Wallet.Instance.MakeSpace();

        TweetData topResults = JSONParser.parseJSONObject <TweetData>(reqTop.downloadHandler.text);

        yield return(StartCoroutine(PlaceResultsInSection(topResults, -topRect.topLeft.x, -topRect.topLeft.y, panel, topRect.panelNumber)));

        TweetData bottomResults
            = JSONParser.parseJSONObject <TweetData>(reqBottom.downloadHandler.text);

        yield return(StartCoroutine(PlaceResultsInSection(bottomResults, -bottomRect.topLeft.x
                                                          , pixelDeviation * 2 - bottomRect.bottomRight.y, panel, bottomRect.panelNumber)));
    }
    // See GetJSON method for explanation.
    IEnumerator GetJSONLeftRight(DataRect leftRect, DataRect rightRect)
    {
        UnityWebRequest reqLeft  = SendRequest(leftRect);
        UnityWebRequest reqRight = SendRequest(rightRect);

        while (!reqLeft.isDone)
        {
            yield return(null);
        }
        if (reqLeft.isNetworkError || reqLeft.isHttpError)
        {
            Debug.Log(reqLeft.error);
            yield break;
        }

        while (!reqRight.isDone)
        {
            yield return(null);
        }
        if (reqRight.isNetworkError || reqRight.isHttpError)
        {
            Debug.Log(reqRight.error);
            yield break;
        }

        GameObject panel = Wallet.Instance.MakeSpace();

        TweetData leftResults = JSONParser.parseJSONObject <TweetData>(reqLeft.downloadHandler.text);

        yield return(StartCoroutine(PlaceResultsInSection(leftResults, -leftRect.topLeft.x, -leftRect.topLeft.y, panel, leftRect.panelNumber)));

        TweetData rightResults = JSONParser.parseJSONObject <TweetData>(reqRight.downloadHandler.text);

        yield return(StartCoroutine(PlaceResultsInSection(rightResults, pixelDeviation * 2 - rightRect.bottomRight.x
                                                          , -rightRect.topLeft.y, panel, rightRect.panelNumber)));
    }
        public void CancelTwitterStreamProcessingEndsProcessingOfTweets()
        {
            TweetData tweetData = new TweetData
            {
                Data = new Tweet
                {
                    CreatedAt = DateTime.Today,
                    Id        = "1234",
                    Text      = "Tweet Text"
                }
            };

            string tweetJson = JsonConvert.SerializeObject(tweetData);

            _testMessageHandler.AddMessagesToStream(Enumerable.Repeat(tweetJson, 50000));

            Task processTask = _twitterStreamProcessor.ProcessTwitterStream(_cancellationTokenSource.Token);
            Task cancelTask  = _twitterStreamProcessor.CancelTwitterStreamProcessing();

            Assert.True(processTask.Wait(1000));
            Assert.True(cancelTask.Wait(1000));

            _mockTweetProcessor.Verify(mtp => mtp.Process(It.IsAny <Task <string> >()), Times.AtLeastOnce());
        }
    // See GetJSON method for explanation.
    IEnumerator GetJSON(DataRect topLeftRect, DataRect topRightRect, DataRect bottomRightRect
                        , DataRect bottomLeftRect)
    {
        UnityWebRequest reqTopLeft     = SendRequest(topLeftRect);
        UnityWebRequest reqTopRight    = SendRequest(topRightRect);
        UnityWebRequest reqBottomRight = SendRequest(bottomRightRect);
        UnityWebRequest reqBottomLeft  = SendRequest(bottomLeftRect);

        while (!reqTopLeft.isDone)
        {
            yield return(null);
        }
        if (reqTopLeft.isNetworkError || reqTopLeft.isHttpError)
        {
            Debug.Log(reqTopLeft.error);
            yield break;
        }

        while (!reqTopRight.isDone)
        {
            yield return(null);
        }
        if (reqTopRight.isNetworkError || reqTopRight.isHttpError)
        {
            Debug.Log(reqTopRight.error);
            yield break;
        }

        while (!reqBottomRight.isDone)
        {
            yield return(null);
        }
        if (reqBottomRight.isNetworkError || reqBottomRight.isHttpError)
        {
            Debug.Log(reqBottomRight.error);
            yield break;
        }

        while (!reqBottomLeft.isDone)
        {
            yield return(null);
        }
        if (reqBottomLeft.isNetworkError || reqBottomLeft.isHttpError)
        {
            Debug.Log(reqBottomLeft.error);
            yield break;
        }

        GameObject panel = Wallet.Instance.MakeSpace();

        List <Action> actions = new List <Action>();

        TweetData results = JSONParser.parseJSONObject <TweetData>(reqTopLeft.downloadHandler.text);

        yield return(StartCoroutine(PlaceResultsInSection(results, -topLeftRect.topLeft.x, -topLeftRect.topLeft.y, panel, topLeftRect.panelNumber)));

        Debug.Log("Placed top left!");

        results = JSONParser.parseJSONObject <TweetData>(reqTopRight.downloadHandler.text);
        yield return(StartCoroutine(PlaceResultsInSection(results, pixelDeviation * 2 - topRightRect.bottomRight.x
                                                          , -topRightRect.topLeft.y, panel, topRightRect.panelNumber)));

        Debug.Log("Placed top right!");

        results = JSONParser.parseJSONObject <TweetData>(reqBottomLeft.downloadHandler.text);
        yield return(StartCoroutine(PlaceResultsInSection(results, -bottomLeftRect.topLeft.x
                                                          , pixelDeviation * 2 - bottomLeftRect.bottomRight.y, panel, bottomLeftRect.panelNumber)));

        Debug.Log("Placed bottom left!");

        results = JSONParser.parseJSONObject <TweetData>(reqBottomRight.downloadHandler.text);
        yield return(StartCoroutine(PlaceResultsInSection(results, pixelDeviation * 2 - bottomRightRect.bottomRight.x
                                                          , pixelDeviation * 2 - bottomRightRect.bottomRight.y, panel, bottomRightRect.panelNumber)));

        Debug.Log("Placed bottom right!");
    }
Beispiel #28
0
 void AddTweet(TweetData data)
 {
     tweets.Add(data);
 }
Beispiel #29
0
    public override float SetData(object o)
    {
        base.SetData(o);
        data = o as TweetData;
        HeadSpriteUtils.Instance.SetHead(head, data.userId);
        userName.text = XMLSaver.saveData.GetAccountData(data.userId).GetAnyName();
        float itemHeight = 0.0f;

        itemHeight   -= root.anchoredPosition.y;
        itemHeight   -= mainBody.rectTransform.anchoredPosition.y;
        mainBody.text = data.info;
        mainBody.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 2000.0f);
        mainBody.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, mainBody.preferredHeight);
        itemHeight += mainBody.rectTransform.sizeDelta.y;
        itemHeight += 26.0f;

        picGroup.anchoredPosition = new Vector2(picGroup.anchoredPosition.x, -itemHeight + 20.0f);
        for (int i = 0; i < pic.Length; i++)
        {
            pic [i].gameObject.SetActive(false);
        }
        mainPic.gameObject.SetActive(false);
        if (data.pics.Length == 1)
        {
            mainPic.sprite    = ZoneManager.Instance.picArray[data.pics[0]].pic;
            mainPic.sizeDelta = Utils.CalSpriteDisplaySize(pic[0].sprite.bounds.size, new Vector2(750.0f, 535.0f));
            itemHeight       += mainPic.sizeDelta.y;
            itemHeight       += 30.0f;
            mainPic.gameObject.SetActive(true);
        }
        else if (data.pics.Length >= 2)
        {
            for (int i = 0; i < Mathf.Min(data.pics.Length, 6); i++)
            {
                pic[i].sprite = ZoneManager.Instance.picArray[data.pics[i]].pic;
                pic[i].gameObject.SetActive(true);
            }
            mainPic.sprite    = ZoneManager.Instance.picArray[data.pics[0]].pic;
            mainPic.sizeDelta = Utils.CalSpriteDisplaySize(pic[0].sprite.bounds.size, new Vector2(750.0f, 535.0f));
            mainPic.gameObject.SetActive(true);
            if (data.pics.Length <= 3)
            {
                itemHeight += 260.0f;
            }
            else
            {
                itemHeight += 530.0f;
            }
            itemHeight += 30.0f;
        }

        locationText.anchoredPosition = new Vector2(locationText.anchoredPosition.x, -itemHeight + 20.0f);
        locationText.text             = data.location;
        itemHeight += 70.0f;

        comments.Clear();
        likes.Clear();
        if (ZoneManager.Instance.id2Comment.ContainsKey(data.userId))
        {
            for (int i = 0; i < ZoneManager.Instance.id2Comment[data.userId].Count; i++)
            {
                CommentData commentData = ZoneManager.Instance.id2Comment[data.userId][i];
                if (commentData.commentType != CommentType.Tweet || commentData.targetId != data.id)
                {
                    continue;
                }
                if (commentData.info == null)
                {
                    likes.Add(commentData);
                }
                else
                {
                    comments.Add(commentData);
                }
            }
        }

        if (likes.Count == 0 && comments.Count == 0)
        {
            downPanel.gameObject.SetActive(false);
            itemHeight               += 10.0f;
            height                    = itemHeight;
            dotsCanvas.alpha          = 0.0f;
            dotsCanvas.blocksRaycasts = false;
            comments.Clear();
            likes.Clear();
            sb.Length = 0;
            return(itemHeight);
        }
        downPanelLine.gameObject.SetActive(likes.Count != 0 && comments.Count != 0);
        downPanel.gameObject.SetActive(true);
        downPanel.anchoredPosition = new Vector2(downPanel.anchoredPosition.x, -itemHeight + 20.0f);
        sb.Length = 0;

        float addHeight = 0.0f;

        addHeight += 25.0f;
        if (likes.Count != 0)
        {
            sb.Append(XMLSaver.saveData.GetAccountData(likes[0].userId).GetAnyName());
        }
        for (int i = 1; i < likes.Count; i++)
        {
            sb.Append("," + XMLSaver.saveData.GetAccountData(likes[0].userId).GetAnyName());
        }
        if (likes.Count == 0)
        {
            likesText.gameObject.SetActive(false);
            heartIcon.gameObject.SetActive(false);
        }
        else
        {
            likesText.text = sb.ToString();
            //likeNames.rectTransform.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical,2000.0f);
            likesText.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, likesText.preferredHeight);
            likesText.gameObject.SetActive(true);
            heartIcon.gameObject.SetActive(true);
            addHeight += (90.0f - 40.0f + likesText.height);
        }

        sb.Length = 0;
        if (comments.Count != 0)
        {
            sb.Append(XMLSaver.saveData.GetAccountData(comments[0].userId).GetAnyName() + ":<color=black>" + comments[0].info + "</color>");
        }
        for (int i = 1; i < comments.Count; i++)
        {
            sb.Append("\n");
            sb.Append(XMLSaver.saveData.GetAccountData(comments[i].userId).GetAnyName() + ":<color=black>" + comments[i].info + "</color>");
        }
        if (comments.Count == 0)
        {
            commentText.gameObject.SetActive(false);
        }
        else
        {
            commentText.text             = sb.ToString();
            commentText.anchoredPosition = new Vector2(commentText.anchoredPosition.x, -addHeight - 20.0f);
            //comment.rectTransform.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical,2000.0f);
            commentText.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, commentText.preferredHeight);
            commentText.gameObject.SetActive(true);
            addHeight += (40.0f + commentText.height);
        }
        addHeight += 25.0f;
        downPanel.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, addHeight);
        itemHeight += addHeight;

        itemHeight               += 10.0f;
        height                    = itemHeight;
        dotsCanvas.alpha          = 0.0f;
        dotsCanvas.blocksRaycasts = false;
        comments.Clear();
        likes.Clear();
        sb.Length = 0;
        return(itemHeight);
    }
Beispiel #30
0
        public static void Tweet(string gameId, string text, params string[] hashTags)
        {
            var tweetData = new TweetData(gameId, text, hashTags);

            Tweet(tweetData);
        }