Inheritance: CoreBase
    private async void searchUser()
    {
      if (tokens != null)
      {
        user = new List<TweetClass.UserInfo>();
        try
        {
          string search_word = serchBox.Text;
          var result = await tokens.Users.SearchAsync(count => 100, q => search_word);

          //foreach (var status in await tokens.Search.TweetsAsync(q => serchBox.Text, count => 200, lang => "ja"))
          foreach (var status in result)
          {
            user.Add(new TweetClass.UserInfo
            {
              UserName = status.Name,
              UserId = status.Id,
              ScreenName = "@" + status.ScreenName,
              ProfileImageUrl = status.ProfileImageUrlHttps,
              FollowCount = status.FollowersCount,
              FavCount = status.FavouritesCount,
              FollowerCount = status.FriendsCount,
              Prof = status.Description

            });
          }
          userSearchView.ItemsSource = user;
        }
        catch (Exception ex)
        {
          //          viewTextBox.Text = ex.Source;
        }
      }
    }
        public void Initialize()
        {
            this.Title = "X-NowPlaying - Loading...";
            this.JacketImage = new BitmapImage(new Uri("/Resources/insert2.png", UriKind.Relative));
            _objects = ApplicationData.Load();
            if (_objects == null)
            {
                Environment.Exit(0);
            }

            //25個に分割
            int i = 0;
            List<XObject> list = null;
            foreach (XObject obj in _objects)
            {
                if (i == 25)
                {
                    _parallel.Add(list);
                    i = 0;
                }
                if (i == 0)
                {
                    list = new List<XObject>();
                }
                list.Add(obj);
                i++;
            }
            //5 sec interval
            this._timer = new Timer(Update, null, 0, 1000 * 5);
        }
示例#3
0
 /// <summary>
 /// 指定したscreen_nameのユーザのツイートを指定個数取得する。(Retryあり)
 /// </summary>
 /// <param name="token"></param>
 /// <param name="user_id"></param>
 /// <param name="maxCount"></param>
 /// <param name="sleep"></param>
 /// <param name="report"></param>
 /// <returns></returns>
 public static IEnumerable<Status> GetUserTimeLines(List<Tokens> tokens, ulong user_id, int maxCount, TimeSpan sleep, Action<string> report)
 {
     var list2 = tokens.UserTimelineRetry(sleep, report, id => user_id, count => 100, exclude_replies => true, include_rts => false);
     int c = 0;
     long maxId = long.MaxValue;
     foreach (var item in list2)
     {
         maxId = item.Id;
         c++;
         yield return item;
     }
     while (true)
     {
         list2 = tokens.UserTimelineRetry(sleep, report, id => user_id, count => 100, max_id => (maxId - 1).ToString(), exclude_replies => true, include_rts => false);
         int c1 = 0;
         foreach (var item in list2)
         {
             maxId = item.Id;
             yield return item;
             c++;
             c1++;
             if (maxCount <= c) break;
         }
         if (c1 < 20) break;
         if (maxCount <= c) break;
     }
 }
示例#4
0
        internal void AnalyzeText()
        {
            _Text = _Text
                .Replace("&amp;", "&")
                .Replace("&lt;", "<")
                .Replace("&gt;", ">");
            TextElements = new List<StatusElement>();

            var el = new List<EntityInfo>();
            if (origin.Entities != null)
            {
                if (origin.Entities.Urls != null) el.AddRange(origin.Entities.Urls.Select(p => new EntityInfo { Indices = p.Indices, Text = p.DisplayUrl, Infomation = p.ExpandedUrl.ToString(), Type = "Url" }));
                if (origin.Entities.Media != null) el.AddRange(origin.Entities.Media.Select(p => new EntityInfo { Indices = p.Indices, Text = p.DisplayUrl, Infomation = p.ExpandedUrl.ToString(), Type = "Media" }));
                if (origin.Entities.UserMentions != null) el.AddRange(origin.Entities.UserMentions.Select(p => new EntityInfo { Indices = p.Indices, Text = "@" + p.ScreenName, Infomation = p.ScreenName, Type = "Mention" }));
                if (origin.Entities.HashTags != null) el.AddRange(origin.Entities.HashTags.Select(p => new EntityInfo { Indices = p.Indices, Text = "#" + p.Text, Infomation = p.Text, Type = "Hashtag" }));
                el.Sort((x, y) => x.Indices[0].CompareTo(y.Indices[0]));
            }
            int n = 0;
            string s = _Text;
            foreach (var i in el)
            {
                i.Indices[0] = i.Indices[0] >= s.Length ? s.Length - 1 : i.Indices[0];
                var ssi = i.Indices[0] - n;
                ssi = (i.Indices[0] + ssi > s.Length) ? (s.Length - n) : ssi;
                TextElements.Add(new StatusElement { Text = s.Substring(n, ssi), Type = "None" });
                TextElements.Add(new StatusElement { Text = i.Text, Infomation = i.Infomation, Type = i.Type });
                n = (i.Indices[1] >= s.Length - 1) ? s.Length - 1 : i.Indices[1];
            }
            if (n < s.Length - 1) TextElements.Add(new StatusElement { Text = s.Substring(n), Type = "None" });
        }
示例#5
0
        public override IEnumerable<Kbtter4Plugin> Load(Kbtter instance, IList<string> filenames)
        {
            var files = filenames.Where(p => p.EndsWith(".py"));
            var ret = new List<Kbtter4IronPythonPlugin>();

            engine = Python.CreateEngine();

            var context = HostingHelpers.GetLanguageContext(engine) as PythonContext;
            var path = context.GetSearchPaths();
            path.Add(Environment.CurrentDirectory + "\\");
            engine.SetSearchPaths(path);

            engine.Runtime.LoadAssembly(typeof(Status).Assembly);

            foreach (var i in files)
            {
                try
                {
                    var scope = engine.CreateScope();
                    scope.SetVariable("Kbtter4", new Kbtter4PluginProvider(instance));
                    var src = engine.CreateScriptSourceFromFile(i);
                    var code = src.Compile();
                    code.Execute(scope);
                    var p = new Kbtter4IronPythonPlugin(scope,instance);
                    ret.Add(p);
                }
                catch (Exception e)
                {
                    instance.LogError(String.Format("プラグイン読み込み中にエラーが発生しました : {0}\n{1}", i, e.Message));

                }
            }

            return ret;
        }
示例#6
0
        public Form1()
        {
            InitializeComponent();

            this.BringToFront();
            this.Focus();
            this.KeyPreview = true;

            Index = 0; Pages = new List<Tuple<string, Status>>();
            button1.Enabled = button2.Enabled = false;

            if (BearerToken.Equals("none"))
                try
                {
                    BearerToken = OAuth2.GetToken(ConsumerKey, ConsumerSecret).BearerToken;
                    Properties.Settings.Default.Save();
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                    Environment.Exit(1);
                }
            Token = OAuth2Token.Create(ConsumerKey, ConsumerSecret, BearerToken);
            toolStripTextBox1.Focus();
        }
示例#7
0
        public Form_Talk(Tokens tokens, List<Status> talk, Form_Main parentForm)
        {
            InitializeComponent();
            this.tokens = tokens;
            this.talk = talk;
            this.parentForm = parentForm;

            this.Text = "Talk.";
        }
示例#8
0
        public Form_TalkDM(Tokens tokens, List<DirectMessage> talk, Form_Main parentForm)
        {
            InitializeComponent();
            this.tokens = tokens;
            this.talk = talk;
            this.parentForm = parentForm;

            this.Text = "Talk (Direct Message).";
        }
示例#9
0
        public TwitterCheck()
        {
            var settings = ConfigurationManager.AppSettings;

            var blackWords = new List<string>();
            var whiteWords = new List<string>();
            for (int i = 1; i <= SettingMax; i++)
            {
                string black = settings["twitter.blackwords." + i];
                if (black == null) continue;
                foreach (var elem in black.Split(','))
                {
                    blackWords.Add(elem);
                }
                string white = settings["twitter.whitewords." + i];
                if (white == null) continue;
                foreach (var elem in white.Split(','))
                {
                    whiteWords.Add(elem);
                }
            }
            BlackWords = blackWords.AsReadOnly();
            WhiteWords = whiteWords.AsReadOnly();
            Log.Trace.TraceEvent(TraceEventType.Information, 0,
                "{0} black words loaded", BlackWords.Count);
            Log.Trace.TraceEvent(TraceEventType.Information, 0,
               "{0} white words loaded", WhiteWords.Count);

            var replaceList = new List<KeyValuePair<string, string>>();
            for (int i = 1; i <= SettingMax; i++)
            {
                string str = settings["twitter.replace." + i];
                if (str == null) continue;
                foreach (var pair in str.Split(','))
                {
                    string[] kv = pair.Split('=');
                    replaceList.Add(new KeyValuePair<string, string>(kv[0], kv[1]));
                }
            }
            ReplaceList = replaceList.AsReadOnly();
            Log.Trace.TraceEvent(TraceEventType.Information, 0,
                "{0} replace entries loaded", ReplaceList.Count);

            try
            {
                dlNetwork = DollsLib.Learning.DataManager.LoadDeepLearning(
                    SettingManager.Settings.Twitter.DlNetTrainError);
            }
            catch (Exception)
            {
                Log.Trace.TraceEvent(TraceEventType.Warning, 0,
                "DlNwtwork {0} load failed", SettingManager.Settings.Twitter.DlNetTrainError);
            }
        }
示例#10
0
        public static List<Status> getOAuthAndReplies()
        {
            var tokens = SingleService.getTokens();
            var home = tokens.Statuses.HomeTimeline();
            var mentions = tokens.Statuses.MentionsTimeline();
            List<Status> replies = new List<Status>();

            foreach(var m in mentions)
            {
                replies.Add(m);
            }
            return replies;
        }
示例#11
0
        public MainWindow()
		{
            selectImage = "";
			InitializeComponent();
			pictureBoarders = new List<Rectangle>();
            twhelper = new TwitterHelpper();
            Properties.Settings.Default.FileRoot= Properties.Settings.Default.FileRoot == "" ?
                System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures) :
                    Properties.Settings.Default.FileRoot;
            Properties.Settings.Default.Save();

            hotKey = new HotKey.HotKeyRegister(HotKey.MOD_KEY.CONTROL, Keys.Q, this);
			pictureList = new Mok.Util.PaginateList<string>(9);
			hotKey.HotKeyPressed += (k) =>
			{
	
				counter++;
                try
                {
                    wc.CaptureImage().Save(FilePath(), System.Drawing.Imaging.ImageFormat.Png);
                }
                catch(WindowCapture.WindowNotFoundException)
                {
                    System.Windows.MessageBox.Show("PC TV with Nasneが起動されていません。");
                    return;
                }
				pictureList.AddShift(FilePath());
				ReconstractView();
				selectImage = FilePath();
				pictureBoarders.ForEach(p => p.Visibility = Visibility.Hidden);
				pictureBoarders[Math.Min(8, pictureList.Count - 1)].Visibility = Visibility.Visible;

			};
			wc = new WindowCapture.WindowCapture("PC TV");
		
			Loaded += (ss, ee) =>
			{
				var picarea = PictureArea.Children;
				foreach (var item in picarea)
				{
					if (item.GetType().ToString() == "System.Windows.Shapes.Rectangle")
					{
						pictureBoarders.Add((Rectangle)item);
						((Rectangle)item).Visibility = Visibility.Hidden;
					}
				}
      
            };

		}
示例#12
0
        public static string GetPeriodicMessage()
        {
            var messages = new List<string> {
            "Destiny has a new Twitter! twitter.com/OmniDestiny",
            "Robot Lady will read your message for $5 or more donations twitchalerts.com/donate/destiny",
            "Remember to use Destiny's Amazon referral link! destiny.gg/amazon",
            $"Destiny updates YouTube regularly now! {Tools.LatestYoutube()}",
              };

              if (i + 1 < messages.Count)
            i++;
              else
            i = 0;
              return messages[i];
        }
 public List<Result> Query(Query query)
 {
     List<Result> results = new List<Result>();
     string tweetMessage = query.ToString().Remove(0, 2);
     results.Add(new Result()
     {
         
         Title = "Tweet: " + tweetMessage,
         IcoPath = "Image\\twitter.png",
         Action = context =>
         {
             postTweet(tweetMessage);
             return true;
         }
     });
     return results;
 }
    private async void muteInfo()
    {
      if (tokens != null)
      {


        user = new List<TweetClass.UserInfo>();
        try
        {

         
          foreach (var status in await tokens.Mutes.Users.ListAsync())

          {
            //data.AddInfo(userPro2, status);
            user.Add(new TweetClass.UserInfo
            {
              UserName = status.Name,
              UserId = status.Id,
              ScreenName = "@" + status.ScreenName,
              ProfileImageUrl = status.ProfileImageUrlHttps,
              FollowCount = status.FollowersCount,
              FavCount = status.FavouritesCount,
              FollowerCount = status.FriendsCount,
              Prof = status.Description

            });

          }
          this.muteView.ItemsSource = user;
        }

        catch (Exception ex)

        {

        }

      }

    }
示例#15
0
        public override IEnumerable<Kbtter4Plugin> Load(Kbtter instance, IList<string> filenames)
        {
            var list = new List<Kbtter4LuaPlugin>();
            var files = filenames.Where(p => p.EndsWith(".lua"));
            foreach (var i in files)
            {
                try
                {
                    Lua l = new Lua();
                    l.LoadCLRPackage();
                    l["Kbtter4"] = new Kbtter4PluginProvider(instance);
                    l.DoFile(i);
                    list.Add(new Kbtter4LuaPlugin(l,instance));
                }
                catch (Exception e)
                {
                    instance.LogError("Luaプラグイン読み込み中にエラーが発生しました : " + e.Message);
                }
            }

            return list;
        }
示例#16
0
        /// <summary>
        /// UserTimelineAPIを使う。もしAPIを使いきっているなら、スリープし、再実行する。
        /// </summary>
        /// <param name="statuses"></param>
        /// <param name="sleepTime"></param>
        /// <param name="report"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static IEnumerable<CoreTweet.Status> UserTimelineRetry(this List<Tokens> tokens, TimeSpan sleepTime, Action<string> report, params System.Linq.Expressions.Expression<Func<string, object>>[] parameters)
        {
            CoreTweet.Status[] list2 = new List<CoreTweet.Status>().ToArray();
            bool flag = false;
            try
            {
                list2 = tokens[token_index].Statuses.UserTimeline(parameters).ToArray();
            }
            catch (Exception ex)
            {
                report(ex.Message);
                if (ex.Message == "Rate limit exceeded")
                {
                    flag = true;
                }
                else if (ex.Message == "Over capacity")
                {
                    flag = true;
                }
                else
                {
                    throw ex;
                }

            }
            if (flag)
            {
                report("Sleep");
                System.Threading.Thread.Sleep(sleepTime);
                token_index = (token_index + 1) % tokens.Count;
                report("Token is " + token_index.ToString());
                Program.nowTokenIndex = token_index;
                return UserTimelineRetry(tokens, sleepTime, report, parameters);
            }
            return list2;
        }
示例#17
0
        private List<Status> getTalk(Status tweet)
        {
            List<Status> talk = new List<Status>();
            talk.Add(tweet);

            while (tweet.InReplyToStatusId != null)
            {
                tweet = getTweetFromId(this.tokens, tweet.InReplyToStatusId.ToString());
                talk.Add(tweet);
            }

            return talk;
        }
示例#18
0
        static void Main(string[] args)
        {
            //StreamReader sr = new StreamReader(@"account_csv.log");
            StreamReader sr = new StreamReader(args[0]);
            bool isCrawTrainData = true;
            string imagePath = "images";
            string corpusPath = "corpus";
            System.Net.WebClient wc = new System.Net.WebClient();

            ulong savedId = Properties.Settings.Default.Last_ID;
            bool isLoad = false;
            if (savedId != 0) isLoad = true;

            var tokens = TwitterAPI.getTokens();
            System.Text.RegularExpressions.Regex r =
    new System.Text.RegularExpressions.Regex(@"https?://[\w/:%#\$&\?\(\)~\.=\+\-]+");

            //画像保存用
            if (!Directory.Exists(imagePath) && isCrawTrainData) Directory.CreateDirectory(imagePath);
            //文書保存用
            if (!Directory.Exists(corpusPath) && isCrawTrainData) Directory.CreateDirectory(corpusPath);

            //ループ
            while (sr.Peek() > -1)
            {
                string id_str = sr.ReadLine().Split(',')[0];
                ulong account_id = Convert.ToUInt64(id_str);
                bool unMedia = true;

                //goto saved pointer
                if (isLoad && savedId != account_id) continue;
                if (savedId == account_id)
                {
                    isLoad = false;
                    continue;
                }

                Console.WriteLine(id_str+":");
                UserResponse user=null;

                //UserResponce取得
                userFirst:
                try
                {
                    user = tokens[nowTokenIndex].Users.Show(id => account_id);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(("user:"******"Rate limit exceeded")
                    {
                        System.Threading.Thread.Sleep(new TimeSpan(0, 1, 0));
                        goto userFirst;
                    }
                    else if (ex.Message == "Over capacity")
                    {
                        System.Threading.Thread.Sleep(new TimeSpan(0, 1, 0));
                        goto userFirst;
                    }
                }

                try
                {
                    uint counter = Properties.Settings.Default.counter;
                    List<int> RTList = new List<int>(), FavList = new List<int>();
                    List<string> myCorpus = new List<string>();
                    List<int> CorpusRT = new List<int>();
                    List<long> CorpusID = new List<long>();
                    List<string> CorpusTime = new List<string>();

                    //user info
                    userInfo uf = new userInfo(user);

                    //get tweet
                    var lines = CoreTweetExtend.GetUserTimeLines(tokens, account_id, 3000, new TimeSpan(0, 1, 0), (n) => Console.WriteLine(n));

                    //画像用ファイル
                    string myImagePath = Path.Combine(imagePath, user.Id.Value.ToString());
                    if (!Directory.Exists(myImagePath) && isCrawTrainData) Directory.CreateDirectory(myImagePath);

                    foreach (var str in lines)
                    {
                        RTList.Add(str.RetweetCount.Value);
                        FavList.Add(str.FavoriteCount.Value);

                        //Mediaのみ取得
                        if (str.Entities.Media != null || !isCrawTrainData)
                        {
                            //文章手直し
                            string replaced = r.Replace(str.Text, "");
                            replaced = replaced.Replace("\r", "");
                            replaced = replaced.Replace("\n", "");
                            if (isCrawTrainData)
                            {
                                replaced = replaced.Replace(",", "、");
                                replaced = replaced.Replace(".", "。");
                            }

                            if (replaced != "")
                            {
                                myCorpus.Add(replaced);
                                CorpusRT.Add(str.RetweetCount.Value);
                                CorpusID.Add(str.Id);
                                CorpusTime.Add(str.CreatedAt.ToString("yyyy/MM/dd HH:mm:ss"));

                                //メディア保存
                                if (isCrawTrainData)
                                {
                                    unMedia = false;
                                    string tweetPath = Path.Combine(myImagePath, str.Id.ToString());
                                    Directory.CreateDirectory(tweetPath);
                                    foreach(var media in str.Entities.Media)
                                    {
                                        string thisPath = Path.Combine(tweetPath, Path.GetFileName(media.MediaUrl));
                                        wc.DownloadFile(media.MediaUrl, thisPath);

                                        Console.WriteLine(thisPath+":"+counter);
                                    }
                                }
                            }
                        }
                    }

                    if (!unMedia)
                    {

                        //統計計算
                        uf.RTMean = RTList.Average();
                        uf.RTDev = Math.Sqrt(RTList.Select(t => Math.Pow(t - uf.RTMean, 2.0)).Sum() / RTList.Count());
                        uf.FavMean = FavList.Average();
                        uf.FavDev = Math.Sqrt(FavList.Select(t => Math.Pow(t - uf.FavMean, 2.0)).Sum() / FavList.Count());

                        //ユーザ情報書き込み
                        if (isCrawTrainData)
                        {
                            using (StreamWriter sw_ui = new StreamWriter("user_info.txt", true, Encoding.UTF8))
                            {
                                sw_ui.WriteLine(uf.ToString());
                            }
                        }

                        //コーパス書き込み
                        string mycpPath = Path.Combine(corpusPath, user.Id + ".txt");
                        using (StreamWriter cw_cp = new StreamWriter(mycpPath, true, Encoding.UTF8))
                        {
                            foreach (string cp in myCorpus.Zip(CorpusID, (first, second) => string.Format("{0},{1}", first, second)).Zip(CorpusRT, (first, second) => string.Format("{0},{1}", first, second)))
                            {
                                cw_cp.WriteLine(cp);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                Properties.Settings.Default.Last_ID = account_id;
                Console.WriteLine(Properties.Settings.Default.counter);
                Properties.Settings.Default.counter++;
                Properties.Settings.Default.Save();
            }
        }
示例#19
0
        /// <summary>
        /// トークンの取得
        /// </summary>
        /// <returns>トークン</returns>
        public static List<Tokens> getTokens()
        {
            if (myApis == null)
            {
                myApis = loadAPIInfo();
            }

            List<Tokens> tokens = new List<Tokens>();

            foreach(var myApi in myApis)
            {
                tokens.Add(Tokens.Create(myApi.APIKey
                , myApi.APISecret
                , myApi.AccessToken
                , myApi.AccessTokenSecret));
            }
            return tokens;
        }
    private void userInfo()
    {
     if (tokens != null)
      {
        userPro = new List<TweetClass.UserInfo>();
        try
        {

     //     showedUser =await tokens.Users.ShowAsync(user_id => name);


          userPro.Add(new TweetClass.UserInfo
          {
            UserName = showedUser.Name,
            UserId = showedUser.Id,
            ScreenName = "@" + showedUser.ScreenName,
            ProfileImageUrl = showedUser.ProfileImageUrlHttps,
            FollowCount = showedUser.FollowersCount,
            FavCount = showedUser.FavouritesCount,
            FollowerCount = showedUser.FriendsCount,
            Prof = showedUser.Description

          }
);

          this.userInfoView.ItemsSource = userPro;

          //userTimeline2();
        }

        catch (Exception ex)

        {

        }

      }

    }
 private static List<DoubleUtf16Char> GetCodePoints(string str)
 {
     var result = new List<DoubleUtf16Char>(str.Length);
     for (var i = 0; i < str.Length; i++)
     {
         var c = str[i];
         result.Add(char.IsHighSurrogate(c)
             ? new DoubleUtf16Char(c, str[++i])
             : new DoubleUtf16Char(c));
     }
     return result;
 }
示例#22
0
        public TitleChildSceneOptionEdit(User[] op)
        {
            opts = op;
            osi = new int[opts.Length];
            oii = new OptionInitializationInformation[opts.Length];
            sum = new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { Value = "オプション装備編集", X = 230, Y = 8 };
            type = new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Blue) { Value = "装備タイプ", X = 160, Y = 32 + 8 };
            dirc = new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Green) { Value = "装備方向", X = 160, Y = 64 + 8 };
            mode = new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Green) { Value = "モード", X = 160, Y = 96 + 8 };
            uvdesc = new List<StringSprite>()
            {
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Red) { Value = "装備固有オプション1", X = 160, Y = 128 + 8 },
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Red) { Value = "装備固有オプション2", X = 160, Y = 160 + 8 },
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Red) { Value = "装備固有オプション3", X = 160, Y = 192 + 8 },
            };

            seltype = new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { Value = "", X = 360, Y = 32 + 8 };
            seldirc = new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { Value = "", X = 360, Y = 64 + 8 };
            selmode = new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { Value = "", X = 360, Y = 96 + 8 };
            ipuvdesc = new List<StringSprite>()
            {
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { Value = "", X = 360, Y = 128 + 8 },
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { Value = "", X = 360, Y = 160 + 8 },
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { Value = "", X = 360, Y = 192 + 8 },
            };

            uvs = new List<StringSprite>();
            uvs.Add(type);
            uvs.Add(dirc);
            uvs.Add(mode);
            uvs.AddRange(uvdesc);

            seluvs = new List<StringSprite>();
            seluvs.Add(seltype);
            seluvs.Add(seldirc);
            seluvs.Add(selmode);
            seluvs.AddRange(ipuvdesc);

            uvsmal = new List<MenuAllocationInformation>
            {
                new MenuAllocationInformation{ X = 144, Y = 48 },
                new MenuAllocationInformation{ X = 144, Y = 80 },
                new MenuAllocationInformation{ X = 144, Y = 112 },
                new MenuAllocationInformation{ X = 144, Y = 144 },
                new MenuAllocationInformation{ X = 144, Y = 176 },
                new MenuAllocationInformation{ X = 144, Y = 208 },
            };

            for (int i = 0; i < uvsmal.Count; i++)
            {
                int ci = i;
                uvsmal[i].Upper = uvsmal[(i + uvsmal.Count - 1) % uvsmal.Count];
                uvsmal[i].Lower = uvsmal[(i + 1) % uvsmal.Count];
                uvsmal[i].AvailableChangingAction =
                    (p, v) =>
                    {
                        uvs[ci].Alpha = seluvs[ci].Alpha = v ? 1.0 : 0.5;
                    };
                if (i >= 1) uvsmal[i].IsAvailable = false;
            }

            udc = new[]
            {
                new MultiAdditionalCoroutineSprite(){HomeX=64,HomeY=64,ScaleX=0.8,ScaleY=0.4,Image=CommonObjects.ImageCursor128[2],X=64,Y=48},
                new MultiAdditionalCoroutineSprite(){HomeX=64,HomeY=64,ScaleX=0.8,ScaleY=0.4,Image=CommonObjects.ImageCursor128[3],X=64,Y=208},
            };
            selopts = new List<MultiAdditionalCoroutineSprite>();
            foreach (var i in opts)
            {
                if (i == null) continue;
                selopts.Add(new MultiAdditionalCoroutineSprite() { HomeX = 48, HomeY = 48, X = 64, Y = 128, Image = BigUserImageManager.GetUserImage(i), Alpha = 0 });
            }
            avu = selopts.Count;
            for (int i = 0; i < avu; i++)
            {
                osi[i] = 0;
                oii[i] = new OptionInitializationInformation();
            }
            selopts.Add(new MultiAdditionalCoroutineSprite() { HomeX = 48, HomeY = 48, X = 64, Y = 128, Image = CommonObjects.ImageOptionEditEnd, Alpha = 0 });
            selopts[usel].Alpha = 1;

            mc = new MultiAdditionalCoroutineSprite() { Image = CommonObjects.ImageCursor128[1], HomeX = 64, HomeY = 64, ScaleX = 0.25, ScaleY = 0.25 };
            mc.X = uvsmal[smsel].X;
            mc.Y = uvsmal[smsel].Y;
        }
示例#23
0
        public TitleChildSceneOptionUserSelect(AccountInformation ainfo, int idx, bool back, User[] us)
        {
            b = back;
            ai = ainfo;
            uinfo = new UserInformation(ai.Users[idx]);
            index = idx;
            mvf = (ta, aid, max) => (mai, val) =>
            {
                if (max > aid) ta[aid].Alpha = val ? 1.0 : 0.5;
            };
            users = us;
            opod = new List<StringSprite>
            {
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 64, Y = 64 - 8, Value = "1st" },
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 64, Y = 96 - 8, Value = "2nd" },
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 64, Y = 128 - 8, Value = "3rd" },
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 64, Y = 160 - 8, Value = "4th" },
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 64, Y = 192 - 8, Value = "5th" }
            };
            next = new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Blue) { X = 64, Y = nextpos - 8, Value = "決定" };
            opsn = new List<StringSprite>
            {
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 128, Y = 64 - 8, Value = "" },
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 128, Y = 96 - 8, Value = "" },
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 128, Y = 128 - 8, Value = "" },
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 128, Y = 160 - 8, Value = "" },
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 128, Y = 192 - 8, Value = "" }
            };
            mal = new List<MenuAllocationInformation>
            {
                new MenuAllocationInformation(){ X = 32, Y = 64 },
                new MenuAllocationInformation(){ X = 32, Y = 96 },
                new MenuAllocationInformation(){ X = 32, Y = 128 },
                new MenuAllocationInformation(){ X = 32, Y = 160 },
                new MenuAllocationInformation(){ X = 32, Y = 192 },
                new MenuAllocationInformation(){ X = 32, Y = 224 },
            };
            opop = new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 64, Y = 224 - 8, Value = "編集        削除" };
            opopmal = new List<MenuAllocationInformation>
            {
                new MenuAllocationInformation(){X=40,Y=224},
                new MenuAllocationInformation(){X=136,Y=224},
            };

            okcancel = new List<StringSprite>
            {
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { Value = "OK", X = 528, Y = 180 , Alpha = 0},
                new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { Value = "キャンセル", X = 528, Y = 204, Alpha = 0 }
            };
            ocmal = new List<MenuAllocationInformation>
            {
                new MenuAllocationInformation(){X=512,Y=180+8,IsAvailable=false},
                new MenuAllocationInformation(){X=512,Y=204+8},
            };
            ouip = new OptionUserInformationPanel(ai.Tokens[index], ai.Users[index])
            {
                ChangingAction = (p) =>
                {
                    //タイムラグ対策
                    if (cs != 2) return;
                    if (p && users.Where(q => q != null).All(q => q.Id != ouip.SourceUser.Id))
                    {
                        valid.Value = "オプションOK";
                        valid.Color = CommonObjects.Colors.Blue;
                        ocmal[0].IsAvailable = true;
                    }
                    else
                    {
                        valid.Value = "オプションNG";
                        valid.Color = CommonObjects.Colors.Red;
                        ocmsel = 1;
                        ocmal[0].IsAvailable = false;
                        mc.AddSubOperation(SpritePatterns.VerticalMove(10, ocmal[ocmsel].Y, Easing.OutQuad));
                    }
                }
            };
            for (int i = 0; i < opopmal.Count; i++)
            {
                opopmal[i].Lefter = opopmal[(i + opopmal.Count - 1) % opopmal.Count];
                opopmal[i].Righter = opopmal[(i + 1) % opopmal.Count];
            }
            for (int i = 0; i < ocmal.Count; i++)
            {
                ocmal[i].Upper = ocmal[(i + ocmal.Count - 1) % ocmal.Count];
                ocmal[i].Lower = ocmal[(i + 1) % ocmal.Count];
                ocmal[i].AvailableChangingAction = mvf(okcancel, i, okcancel.Count);
            }
            for (int i = 0; i < mal.Count; i++)
            {
                mal[i].Upper = mal[(i + mal.Count - 1) % mal.Count];
                mal[i].Lower = mal[(i + 1) % mal.Count];
                mal[i].AvailableChangingAction = mvf(opod, i, opod.Count);
                mal[i].IsAvailable = (i < users.Length && users[i] != null) || i == mal.Count - 1 || (users.Count(p => p != null) == i);
            }
            for (int i = 0; i < opsn.Count; i++)
            {
                if (users[i] != null) opsn[i].Value = users[i].ScreenName;
            }

            valid = new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 320, Y = 216, Value = "オプションOK/NG" };
            mc = new MultiAdditionalCoroutineSprite() { Image = CommonObjects.ImageCursor128[1], HomeX = 64, HomeY = 64, ScaleX = 0.25, ScaleY = 0.25 };
            cs = 0;
            ki = null;
            msel = 0;
            ocmsel = 0;
        }
示例#24
0
        private List<DirectMessage> getTalkDm(DirectMessage dm)
        {
            User talkingUser = dm.Sender;

            var dmRecieved = tokens.DirectMessages.Received(count => 200).Where(x => x.Sender.ScreenName == talkingUser.ScreenName);
            var dmSent = tokens.DirectMessages.Sent(count => 200).Where(x => x.Recipient.ScreenName == talkingUser.ScreenName);

            List<DirectMessage> dmList = new List<DirectMessage>();
            dmList.AddRange(dmRecieved);
            dmList.AddRange(dmSent);

            var query = dmList.OrderByDescending(s => s.CreatedAt);
            List<DirectMessage> talk = query.ToList<DirectMessage>();

            return talk;
        }
示例#25
0
        private void tweet(Tokens tokens, string context, List<string> uploadFiles)
        {
            List<MediaUploadResult> results = new List<MediaUploadResult>();
            foreach (string filePath in uploadFiles)
            {
                MediaUploadResult result = tokens.Media.Upload(media: new FileInfo(filePath));
                results.Add(result);
            }

            var param = new Dictionary<string, object>();
            param.Add("status", context);
            if (0 < results.Count)
            {
                param.Add("media_ids", results.Select(x => x.MediaId));
            }

            if (this.status != null)
            {
                param.Add("in_reply_to_status_id", this.status.Id.ToString());
            }

            tokens.Statuses.UpdateAsync(param);
            resetReply();
            resetAppend();

            string message = string.Format("Tweeted: {0}", context);
            changeStatus(message, NotificationStatus.DoTweet);
        }
示例#26
0
        private void AnalyzeTextElements()
        {
            TextElements = new ObservableSynchronizedCollection<StatusTextElement>();
            var l = new List<Tuple<int[], StatusTextElement>>();

            if (Source.Entities != null)
            {
                if (Source.Entities.Urls != null)
                    foreach (var i in Source.Entities.Urls)
                    {
                        //Text = Text.Replace(i.Url.ToString(), i.DisplayUrl.ToString());
                        var e = new StatusTextElement();
                        e.Original = i.Url.ToString();
                        e.Action = main.View.OpenInDefault;
                        e.Type = StatusTextElementType.Uri;
                        e.Link = i.ExpandedUrl;
                        e.Surface = i.DisplayUrl;
                        l.Add(new Tuple<int[], StatusTextElement>(i.Indices, e));
                    }
                /*
                //互換性上の理由で画像がUrlとMedia両方で送られてくるらしいので暫定的に削除
                if (Source.Entities.Media != null)
                    foreach (var i in Source.Entities.Media)
                    {
                        //Text = Text.Replace(i.Url.ToString(), i.DisplayUrl.ToString());
                        var e = new StatusTextElement();
                        e.Original = i.Url.ToString();
                        e.Action = main.View.OpenInDefault;
                        e.Type = StatusTextElementType.Media;
                        e.Link = i.ExpandedUrl;
                        e.Surface = i.DisplayUrl;
                        l.Add(new Tuple<int[], StatusTextElement>(i.Indices, e));
                    }
                */
                if (Source.Entities.UserMentions != null)
                    foreach (var i in Source.Entities.UserMentions)
                    {
                        var e = new StatusTextElement();
                        e.Action = async (p) =>
                        {
                            var user = await Kbtter.Token.Users.ShowAsync(id => i.Id);
                            Kbtter.AddUserToUsersList(user);
                            main.View.Notify(user.Name + "さんの情報");
                            main.View.ChangeToUser();
                        };
                        e.Type = StatusTextElementType.User;
                        e.Link = new Uri("https://twitter.com/" + i.ScreenName);
                        e.Surface = "@" + i.ScreenName;
                        e.Original = e.Surface;
                        l.Add(new Tuple<int[], StatusTextElement>(i.Indices, e));
                    }

                if (Source.Entities.HashTags != null)
                    foreach (var i in Source.Entities.HashTags)
                    {
                        var e = new StatusTextElement();
                        e.Action = (p) =>
                        {
                            main.View.ChangeToSearch();
                            main.View.SearchText = "#" + i.Text;
                            Kbtter.Search("#" + i.Text);
                        };
                        e.Type = StatusTextElementType.Hashtag;
                        e.Link = new Uri("https://twitter.com/search?q=%23" + i.Text);
                        e.Surface = "#" + i.Text;
                        e.Original = e.Surface;
                        l.Add(new Tuple<int[], StatusTextElement>(i.Indices, e));
                    }

                l.Sort((x, y) => x.Item1[0].CompareTo(y.Item1[0]));
            }

            int le = 0;
            foreach (var i in l)
            {
                var el = i.Item1[1] - i.Item1[0];
                var ntl = i.Item1[0] - le;
                if (ntl != 0)
                {
                    var nt = Text.Substring(le, ntl);
                    nt = nt
                        .Replace("&lt;", "<")
                        .Replace("&gt;", ">")
                        .Replace("&amp;", "&");
                    TextElements.Add(new StatusTextElement { Surface = nt, Type = StatusTextElementType.None });
                }
                TextElements.Add(i.Item2);
                le = i.Item1[1];
            }
            //foreach (var i in l) Text = Text.Replace(i.Item2.Original, i.Item2.Surface);
            if (Text.Length > le - 1)
            {
                var ls = Text.Substring(le);
                ls = ls
                        .Replace("&lt;", "<")
                        .Replace("&gt;", ">")
                        .Replace("&amp;", "&");
                TextElements.Add(new StatusTextElement { Surface = ls, Type = StatusTextElementType.None });
            }
        }
示例#27
0
        static void Main(string[] args)
        {
            "Wake up, HinayakuBot!".COut ();
            bool ShutDownFlag = false;
            List<Task> Tasks = new List<Task> ();
            var CommandContext = new CommandContext ();
            var StatusContext = new StatusContext ();
            var cts = new System.Threading.CancellationTokenSource ();
            Tasks.Add(Task.Run(() =>  StreamObservable.StreamStart(CommandContext,StatusContext),cts.Token));
            Tasks.Add(Task.Run (() => AILogic.AI (CommandContext,StatusContext),cts.Token));
            Tasks.Add (Task.Run (() => UserInterface (CommandContext),cts.Token));
            System.Threading.Thread.Yield ();
            Task.WhenAll (Tasks).ContinueWith (x => ShutDownFlag = true);
            CommandContext.GetCommand.Subscribe (x => {
                if(x.Keys.Any(y => y == Constant.Cmd)) x[Constant.Cmd].COut();
                else if(x.Keys.Any(y => y == Constant.Cmd)&& x[Constant.Cmd] == Constant.CmdEnd) ShutDownFlag = true ;
            });

            var IDs = GetIdFromXml ();
            var Token = TokenCreate (IDs);

            var stream = Token.Streaming.UserAsObservable()
                .Timeout (TimeSpan.FromSeconds (30))
                .Retry (5)
                .Catch((Exception e) => {
                    Console.WriteLine(e.Message);
                    if(e.StackTrace != null) Console.WriteLine(e.StackTrace);
                    return Observable.Never<StatusMessage>();
                })
                .Publish ();

            stream
                .OfType<StatusMessage>()
                .Where (x => !x.Status.User.ScreenName.Contains (@"hinayakuBot"))
                .Select (x => new TwString{Name = x.Status.User.ScreenName, Text = x.Status.Text, Id = x.Status.Id})
                .Subscribe (x => Console.WriteLine(x.Text));

            while(true){
                if (ShutDownFlag == true){
                    Task.Delay (TimeSpan.FromSeconds (15)).Wait ();
                    cts.Cancel ();
                    break;
                }
            }

            "All Done".COut ();
        }
示例#28
0
        /// <summary>
        /// ツイッターAPI情報のロード
        /// </summary>
        /// <returns>API情報</returns>
        public static List<TwitterAPI> loadAPIInfo()
        {
            List<TwitterAPI> APIList = new List<TwitterAPI>();
            XmlSerializer serializer = new XmlSerializer(typeof(TwitterAPI));
            StreamReader sr = new StreamReader(
                Directory.GetCurrentDirectory() + @"\twitterAPI.xml", new System.Text.UTF8Encoding(false));

            APIList.Add((TwitterAPI)serializer.Deserialize(sr));

            XmlSerializer serializer2 = new XmlSerializer(typeof(TwitterAPI));
            StreamReader sr2 = new StreamReader(
                Directory.GetCurrentDirectory() + @"\twitterAPI2.xml", new System.Text.UTF8Encoding(false));

            APIList.Add((TwitterAPI)serializer2.Deserialize(sr2));
            return APIList;
        }
示例#29
0
        /// <summary>
        /// Sends a POST request with multipart/form-data as an asynchronous operation.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="prm">The parameters.</param>
        /// <param name="authorizationHeader">The OAuth header.</param>
        /// <param name="options">The connection options for the request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// <para>The task object representing the asynchronous operation.</para>
        /// <para>The Result property on the task object returns the response.</para>
        /// </returns>
        internal static async Task<AsyncResponse> HttpPostWithMultipartFormDataAsync(Uri url, KeyValuePair<string, object>[] prm, string authorizationHeader, ConnectionOptions options, CancellationToken cancellationToken, IProgress<UploadProgressInfo> progress)
        {
            if(options == null) options = ConnectionOptions.Default;

            var req = new HttpRequestMessage(HttpMethod.Post, url);
            var toDispose = new List<IDisposable>();

#if WIN_RT
            var content = new HttpMultipartFormDataContent();
            foreach(var x in prm)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var valueStream = x.Value as Stream;
                var valueInputStream = x.Value as IInputStream;
                var valueArraySegment = x.Value as ArraySegment<byte>?;
                var valueBytes = x.Value as IEnumerable<byte>;
                var valueBuffer = x.Value as IBuffer;
                var valueInputStreamReference = x.Value as IInputStreamReference;
                var valueStorageItem = x.Value as IStorageItem;

                var fileName = "file";

                if (valueStorageItem != null)
                {
                    fileName = valueStorageItem.Name;
                }
                else if (x.Value.GetType().FullName == "System.IO.FileInfo")
                {
                    var ti = x.Value.GetType().GetTypeInfo();
                    valueStream = (Stream)ti.GetDeclaredMethod("OpenRead").Invoke(x.Value, null);
                    fileName = (string)ti.GetDeclaredProperty("Name").GetValue(x.Value);
                    toDispose.Add(valueStream);
                }

                if (valueInputStreamReference != null)
                {
                    valueInputStream = await valueInputStreamReference.OpenSequentialReadAsync().AsTask().ConfigureAwait(false);
                    toDispose.Add(valueInputStream);
                }
                else if (valueStream != null)
                {
                    valueInputStream = valueStream.AsInputStream();
                }
                else if (valueArraySegment != null)
                {
                    valueBuffer = valueArraySegment.Value.Array.AsBuffer(valueArraySegment.Value.Offset, valueArraySegment.Value.Count);
                }
                else if (valueBytes != null)
                {
                    var valueByteArray = valueBytes as byte[] ?? valueBytes.ToArray();
                    valueBuffer = valueByteArray.AsBuffer();
                }

                if(valueInputStream != null)
                    content.Add(new HttpStreamContent(valueInputStream), x.Key, fileName);
                else if(valueBuffer != null)
                    content.Add(new HttpBufferContent(valueBuffer), x.Key, fileName);
                else
                    content.Add(new HttpStringContent(x.Value.ToString()), x.Key);
            }
#else
            var content = new MultipartFormDataContent();
            foreach (var x in prm)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var valueStream = x.Value as Stream;
                if (valueStream != null)
                {
                    content.Add(new StreamContent(valueStream), x.Key, "file");
                    continue;
                }

                var valueArraySegment = x.Value as ArraySegment<byte>?;
                if (valueArraySegment != null)
                {
                    content.Add(
                        new ByteArrayContent(valueArraySegment.Value.Array, valueArraySegment.Value.Offset, valueArraySegment.Value.Count),
                        x.Key, "file");
                    continue;
                }

                var valueBytes = x.Value as IEnumerable<byte>;
                if (valueBytes != null)
                {
                    content.Add(new ByteArrayContent(valueBytes as byte[] ?? valueBytes.ToArray()), x.Key, "file");
                    continue;
                }

#if FILEINFO
                var valueFileInfo = x.Value as FileInfo;
                if (valueFileInfo != null)
                {
                    valueStream = valueFileInfo.OpenRead();
                    content.Add(new StreamContent(valueStream), x.Key, valueFileInfo.Name);
                    toDispose.Add(valueStream);
                    continue;
                }
#else
                var fileInfoType = x.Value.GetType();
                if (fileInfoType.FullName == "System.IO.FileInfo")
                {
                    var ti = fileInfoType.GetTypeInfo();
                    valueStream = (Stream)ti.GetDeclaredMethod("OpenRead").Invoke(x.Value, null);
                    content.Add(new StreamContent(valueStream), x.Key, (string)ti.GetDeclaredProperty("Name").GetValue(x.Value));
                    toDispose.Add(valueStream);
                    continue;
                }
#endif

                content.Add(new StringContent(x.Value.ToString()), x.Key);
            }
#endif

            cancellationToken.ThrowIfCancellationRequested();
            req.Content = content;
            var res = await ExecuteRequest(req, authorizationHeader, options, cancellationToken, progress).ConfigureAwait(false);

            foreach (var x in toDispose)
                x.Dispose();

            return res;
        }
    private async void followerTimeline()
    {
      listView2.Visibility = Visibility.Collapsed;
      userTLView.Visibility = Visibility.Visible;
      if (tokens != null)

      {
        //this.userTLView.Items.Clear();

        userPro2 = new List<TweetClass.UserInfo>();
        try

        {
          userPro2 = new List<TweetClass.UserInfo>();
          // var showedUser = tokens.Favorites.List(screen_name => ScreenName, count => 200);

          foreach (var status in await tokens.Followers.ListAsync(user_id => UserId, count => 200))

          {
            //data.AddInfo(userPro2, status);
            userPro2.Add(new TweetClass.UserInfo
            {
              UserName = status.Name,
              UserId = status.Id,
              ScreenName = "@" + status.ScreenName,
              ProfileImageUrl = status.ProfileImageUrlHttps,
              FollowCount = status.FollowersCount,
              FavCount = status.FavouritesCount,
              FollowerCount = status.FriendsCount,
              Prof = status.Description

            });

          }
          this.userTLView.ItemsSource = userPro2;
        }

        catch (Exception ex)

        {


        }

      }
    }