Ejemplo n.º 1
2
		public static string UpdateStatus(string status, TwUser user, string replyId)
		{
			Regex regex = new Regex(@"\[(.*?)\]");
			List<FileInfo> media = new List<FileInfo>();
			foreach (System.Text.RegularExpressions.Match match in regex.Matches(status))
			{
				status = status.Replace(match.Value, "");
				FileInfo file = new FileInfo(match.Value.Replace("[", "").Replace("]", ""));
				if (!file.Exists)
					throw new FileNotFoundException("File not found", file.FullName);
				media.Add(file);
            }

			if (media.Count > 4) //limited by the twitter API
				throw new ArgumentOutOfRangeException("media", "Up to 4 media files are allowed per tweet");

			if (user == null)
				user = TwUser.LoadCredentials();
			string encodedStatus = Util.EncodeString(status);
			
			if (media.Count == 0)
				return InternalUpdateStatus(user, encodedStatus, replyId);
			else
				return InternalUpdateWithMedia(user, encodedStatus, replyId, media);
		}
Ejemplo n.º 2
0
		private static string InternalUpdateStatus(TwUser user, string encodedStatus, string replyId, List<string> mediaIds = null)
		{
			string media = null;
			if (mediaIds != null)
				media = Util.EncodeString( string.Join(",", mediaIds.ToArray()));

			HttpWebRequest req = GetUpdateStatusRequest(user.OAuthToken, user.OAuthTokenSecret, encodedStatus, replyId, media);

			byte[] bytes;
			using (Stream str = req.GetRequestStream())
			{
				bytes = Util.GetUTF8EncodingBytes(string.Format("{0}={1}", STATUS, encodedStatus));
				str.Write(bytes, 0, bytes.Length);

				if (!string.IsNullOrEmpty(media))
				{
					bytes = Util.GetUTF8EncodingBytes(string.Format("&{0}={1}", MEDIA, media));
					str.Write(bytes, 0, bytes.Length);
				}
			}

			req.PreAuthenticate = true;
			req.AllowWriteStreamBuffering = true;

			HttpWebResponse response = (HttpWebResponse)req.GetResponse();

			return response.StatusDescription;
		}
Ejemplo n.º 3
0
        private static string InternalUpdateStatus(TwUser user, string encodedStatus, string replyId, List <string> mediaIds = null)
        {
            string media = null;

            if (mediaIds != null)
            {
                media = Util.EncodeString(string.Join(",", mediaIds.ToArray()));
            }

            HttpWebRequest req = GetUpdateStatusRequest(user.OAuthToken, user.OAuthTokenSecret, encodedStatus, replyId, media);

            byte[] bytes;
            using (Stream str = req.GetRequestStream())
            {
                bytes = Util.GetUTF8EncodingBytes(string.Format("{0}={1}", STATUS, encodedStatus));
                str.Write(bytes, 0, bytes.Length);

                if (!string.IsNullOrEmpty(media))
                {
                    bytes = Util.GetUTF8EncodingBytes(string.Format("&{0}={1}", MEDIA, media));
                    str.Write(bytes, 0, bytes.Length);
                }
            }

            req.PreAuthenticate           = true;
            req.AllowWriteStreamBuffering = true;

            HttpWebResponse response = (HttpWebResponse)req.GetResponse();

            return(response.StatusDescription);
        }
Ejemplo n.º 4
0
        public static OAuthTokens getTokens(TwUser usr)
        {
            var tokens = new Twitterizer.OAuthTokens();

            tokens.AccessToken       = usr.Token;
            tokens.AccessTokenSecret = usr.TokenSecret;
            tokens.ConsumerKey       = ConfigurationManager.AppSettings["consumerkey"];
            tokens.ConsumerSecret    = ConfigurationManager.AppSettings["consumersecret"];
            return(tokens);
        }
Ejemplo n.º 5
0
        public List <TweetExtended> getTimeline(TwUser usr)
        {
            var tokens = TwitrucHelpers.getTokens(usr);
            var o      = new Twitterizer.TimelineOptions();

            o.Count = 60;
            try {
                Twitterizer.TwitterResponse <Twitterizer.TwitterStatusCollection> userResponse = Twitterizer.TwitterTimeline.HomeTimeline(tokens, o);
                if (userResponse.Content != null)
                {
                    return(userResponse.ResponseObject.Where(st => st != null).Select(st => new TweetExtended(st)).ToList());
                }
            } catch (Exception) { }
            return(db.TweetSet.Where(t => t.AuthorNick == usr.Nickname).ToArray().Select(t => new TweetExtended(t)).ToList());
        }
Ejemplo n.º 6
0
		public static List<Status> GetMentions(TwUser user, string lastTweet)
		{
			if (user == null)
				user = TwUser.LoadCredentials();

			HttpWebRequest req = GetMentionsRequest(user.OAuthToken, user.OAuthTokenSecret, lastTweet);
			HttpWebResponse response = (HttpWebResponse)req.GetResponse();

			if (response.StatusCode != HttpStatusCode.OK)
				return null;

			DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Statuses));
			Statuses ss = (Statuses)serializer.ReadObject(response.GetResponseStream());

			return ss;
		}
Ejemplo n.º 7
0
        public List <TweetExtended> getTweetsFrom(string id, TwUser usr)
        {
            var tokens = TwitrucHelpers.getTokens(usr);
            var o      = new Twitterizer.UserTimelineOptions();

            o.ScreenName = id;
            o.Count      = 50;
            try {
                Twitterizer.TwitterResponse <Twitterizer.TwitterStatusCollection> userResponse = Twitterizer.TwitterTimeline.UserTimeline(tokens, o);
                if (userResponse.Content != null)
                {
                    return(userResponse.ResponseObject.Select(st => new TweetExtended(st)).ToList());
                }
            } catch (Exception) { }
            return(db.TweetSet.Where(t => t.AuthorNick == id).ToArray().Select(t => new TweetExtended(t)).ToList());
        }
Ejemplo n.º 8
0
 public bool CreateUser(string userName, string nickname, string password, string email)
 {
     if (String.IsNullOrEmpty(userName))
     {
         throw new ArgumentException("Value cannot be null or empty.", "userName");
     }
     if (String.IsNullOrEmpty(nickname))
     {
         throw new ArgumentException("Value cannot be null or empty.", "nickname");
     }
     if (String.IsNullOrEmpty(password))
     {
         throw new ArgumentException("Value cannot be null or empty.", "password");
     }
     if (password.Length <= 4)
     {
         throw new ArgumentException("Password too short, need more than 4 chars.", "password");
     }
     if (String.IsNullOrEmpty(email))
     {
         throw new ArgumentException("Value cannot be null or empty.", "email");
     }
     if (db.UserSet.Any(u => u.Email == email))
     {
         throw new ArgumentException("This email is already registred.", "email");
     }
     if (db.UserSet.Any(u => u.Nickname == nickname))
     {
         throw new ArgumentException("This nickname is already registred.", "nickname");
     }
     try {
         var u = new TwUser();
         u.Name        = userName;
         u.Nickname    = nickname;
         u.Password    = password;
         u.Email       = email;
         u.TwitterNick = "";
         u.Token       = "";
         u.TokenSecret = "";
         db.UserSet.AddObject(u);
         db.SaveChanges();
         return(true);
     } catch (Exception e) {
         throw e;
     }
 }
Ejemplo n.º 9
0
        public Tweet CreateTweet(string content, TwUser u)
        {
            if (String.IsNullOrEmpty(content))
            {
                throw new ArgumentException("Value cannot be null or empty.", "Content");
            }
            var t = new Tweet();

            t.Content     = content;
            t.TwitrucUser = u;
            t.AuthorNick  = u.TwitterNick;
            t.Date        = DateTime.Now;
            t.Sent        = false;
            t.Public      = false;
            db.TweetSet.AddObject(t);
            db.SaveChanges();
            return(t);
        }
Ejemplo n.º 10
0
        public static List <Status> GetTimeline(TwUser user, string lastTweet)
        {
            if (user == null)
            {
                user = TwUser.LoadCredentials();
            }

            HttpWebRequest  req      = GetTimelineRequest(user.OAuthToken, user.OAuthTokenSecret, lastTweet);
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();

            if (response.StatusCode != HttpStatusCode.OK)
            {
                return(null);
            }

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Statuses));
            Statuses ss = (Statuses)serializer.ReadObject(response.GetResponseStream());

            return(ss);
        }
Ejemplo n.º 11
0
        public static string UpdateStatus(string status, TwUser user, string replyId)
        {
            Regex           regex = new Regex(@"\[(.*?)\]");
            List <FileInfo> media = new List <FileInfo>();

            foreach (System.Text.RegularExpressions.Match match in regex.Matches(status))
            {
                status = status.Replace(match.Value, "");
                FileInfo file = new FileInfo(match.Value.Replace("[", "").Replace("]", ""));
                if (!file.Exists)
                {
                    throw new FileNotFoundException("File not found", file.FullName);
                }
                media.Add(file);
            }

            if (media.Count > 4)             //limited by the twitter API
            {
                throw new ArgumentOutOfRangeException("media", "Up to 4 media files are allowed per tweet");
            }

            if (user == null)
            {
                user = TwUser.LoadCredentials();
            }
            string encodedStatus = Util.EncodeString(status);

            if (media.Count == 0)
            {
                return(InternalUpdateStatus(user, encodedStatus, replyId));
            }
            else
            {
                return(InternalUpdateWithMedia(user, encodedStatus, replyId, media));
            }
        }
Ejemplo n.º 12
0
		private static List<string> UploadMedia(TwUser user, List<FileInfo> media)
		{
			List<string> ids = new List<string>();

			foreach (FileInfo file in media)
			{
				WriteMessage($"Uploading {file.Name}");
				HttpWebRequest req = GetMediaUploadStatusRequest(user.OAuthToken, user.OAuthTokenSecret);

				string boundary = GetMultipartBoundary(),
					separator = "--" + boundary,
					footer = separator + "--",
					shortFileName = file.Name,
					fileContentType = GetMimeType(shortFileName),
					fileHeader = string.Format("Content-Disposition: form-data; name=\"media\"; filename=\"{0}\"", shortFileName),
					contentType = "Content-Type: application/octet-stream";

				var encoding = System.Text.Encoding.UTF8;

				req.KeepAlive = false;
				req.ContentType = string.Format("multipart/form-data, boundary=\"{0}\"", boundary);

				string newLine = "\r\n";
				byte[] bytes;
				using (var s = req.GetRequestStream())
				{
					bytes = encoding.GetBytes(separator);
					s.Write(bytes, 0, bytes.Length);

					bytes = encoding.GetBytes(newLine);
					s.Write(bytes, 0, bytes.Length);

					bytes = encoding.GetBytes(fileHeader);
					s.Write(bytes, 0, bytes.Length);

					bytes = encoding.GetBytes(newLine);
					s.Write(bytes, 0, bytes.Length);

					bytes = encoding.GetBytes(contentType);
					s.Write(bytes, 0, bytes.Length);

					bytes = encoding.GetBytes(newLine);
					s.Write(bytes, 0, bytes.Length);

					bytes = encoding.GetBytes(newLine);
					s.Write(bytes, 0, bytes.Length);

					bytes = File.ReadAllBytes(file.FullName);
					s.Write(bytes, 0, bytes.Length);

					bytes = encoding.GetBytes(newLine);
					s.Write(bytes, 0, bytes.Length);

					bytes = encoding.GetBytes(footer);
					s.Write(bytes, 0, bytes.Length);

					bytes = encoding.GetBytes(newLine);
					s.Write(bytes, 0, bytes.Length);

				}

				req.PreAuthenticate = true;
				req.AllowWriteStreamBuffering = true;

				HttpWebResponse response = (HttpWebResponse)req.GetResponse();

				string responseBody;
				using (StreamReader reader = new StreamReader(response.GetResponseStream()))
					responseBody = reader.ReadToEnd();

				int start = responseBody.IndexOf("media_id_string") + "media_id_string".Length + 3;
				int end = responseBody.IndexOf(",", start) - 1;
				string mediaId = responseBody.Substring(start, end - start);

				ids.Add(mediaId);
			}

			return ids;
		}
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            try
            {
                //Debug.Assert(false, "Attach VS here!");

                //http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx
                //AppDomain.CurrentDomain.AssemblyResolve += (sender, arg) => {
                //	string resourceName = "AssemblyLoadingAndReflection." +
                //	new AssemblyName(arg.Name).Name + ".dll";

                //	using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) {
                //		Byte[] assemblyData = new Byte[stream.Length];
                //		stream.Read(assemblyData, 0, assemblyData.Length);
                //		return Assembly.Load(assemblyData);
                //	}
                //};

                shelltwitlib.API.OAuth.OAuthHelper.Initilize(CONSUMER_KEY, CONSUMER_SECRET);
                shelltwitlib.API.Tweets.Update.SetMessageAction(message => Console.WriteLine(message));

                if (args.Length == 0)
                {
                    PrintTwits(shelltwitlib.API.Tweets.Timeline.GetTimeline());
                    return;
                }


                if (args[0].StartsWith("/"))
                {
                    string flag = args[0].ToLower().Trim();
                    switch (flag)
                    {
                    case CLEAR:
                        TwUser.ClearCredentials();
                        Console.WriteLine("User credentials cleared!");
                        return;

                    case HELP:
                        ShowUsage();
                        return;

                    case TIME_LINE:
                        PrintTwits(shelltwitlib.API.Tweets.Timeline.GetTimeline());
                        return;

                    case MENTIONS:
                        PrintTwits(shelltwitlib.API.Tweets.Mentions.GetMentions());
                        return;

                    default:
                        Console.WriteLine("Invalid flag: " + flag);
                        ShowUsage();
                        return;
                    }
                }

                if (args[0].StartsWith("\\"))
                {
                    Console.WriteLine("Really? do you really wanna twit that?. [T]wit, or [N]o sorry, I messed up...");
                    ConsoleKeyInfo input = Console.ReadKey();
                    while (input.Key != ConsoleKey.T && input.Key != ConsoleKey.N)
                    {
                        Console.WriteLine();
                        Console.WriteLine("[T]wit, or [N]o sorry, I messed up...");
                        input = Console.ReadKey();
                    }
                    Console.WriteLine();

                    if (input.Key == ConsoleKey.N)
                    {
                        Console.WriteLine("That's what I thought! ;)");
                        return;
                    }
                }

                shelltwitlib.API.OAuth.OAuthHelper.Initilize(CONSUMER_KEY, CONSUMER_SECRET);
                string status   = BitLyHelper.Util.GetShortenString(args);
                string response = shelltwitlib.API.Tweets.Update.UpdateStatus(status);

                if (response != "OK")
                {
                    Console.WriteLine("Response was not OK: " + response);
                }
                //ConsoleWriter.WriteWarning("Response was not OK: " + response);
            }
            catch (WebException wex)
            {
                //ConsoleWriter.WriteError(wex.Message);
                Console.WriteLine(wex.Message);

                HttpWebResponse res = (HttpWebResponse)wex.Response;
                if (res != null)
                {
                    UpdateError errors = UpdateError.GetFromStream(res.GetResponseStream());
                    errors.Errors.ForEach(e => Console.WriteLine(e.ToString()) /* ConsoleWriter.WriteWarning(e.ToString())*/);
                }
            }
            catch (Exception ex)
            {
                //ConsoleWriter.WriteError(ex.Message);
                Console.WriteLine(ex.Message);
            }
            finally
            {
#if DEBUG
                if (Debugger.IsAttached)
                {
                    //ConsoleWriter.WriteWarning("Press <enter> to exit...");
                    Console.WriteLine("Press <enter> to exit...");
                    Console.ReadLine();
                }
#endif
            }

            Environment.Exit(0);
        }
Ejemplo n.º 14
0
        private static List <string> UploadMedia(TwUser user, List <FileInfo> media)
        {
            List <string> ids = new List <string>();

            foreach (FileInfo file in media)
            {
                WriteMessage($"Uploading {file.Name}");
                HttpWebRequest req = GetMediaUploadStatusRequest(user.OAuthToken, user.OAuthTokenSecret);

                string boundary        = GetMultipartBoundary(),
                       separator       = "--" + boundary,
                       footer          = separator + "--",
                       shortFileName   = file.Name,
                       fileContentType = GetMimeType(shortFileName),
                       fileHeader      = string.Format("Content-Disposition: form-data; name=\"media\"; filename=\"{0}\"", shortFileName),
                       contentType     = "Content-Type: application/octet-stream";

                var encoding = System.Text.Encoding.UTF8;

                req.KeepAlive   = false;
                req.ContentType = string.Format("multipart/form-data, boundary=\"{0}\"", boundary);

                string newLine = "\r\n";
                byte[] bytes;
                using (var s = req.GetRequestStream())
                {
                    bytes = encoding.GetBytes(separator);
                    s.Write(bytes, 0, bytes.Length);

                    bytes = encoding.GetBytes(newLine);
                    s.Write(bytes, 0, bytes.Length);

                    bytes = encoding.GetBytes(fileHeader);
                    s.Write(bytes, 0, bytes.Length);

                    bytes = encoding.GetBytes(newLine);
                    s.Write(bytes, 0, bytes.Length);

                    bytes = encoding.GetBytes(contentType);
                    s.Write(bytes, 0, bytes.Length);

                    bytes = encoding.GetBytes(newLine);
                    s.Write(bytes, 0, bytes.Length);

                    bytes = encoding.GetBytes(newLine);
                    s.Write(bytes, 0, bytes.Length);

                    bytes = File.ReadAllBytes(file.FullName);
                    s.Write(bytes, 0, bytes.Length);

                    bytes = encoding.GetBytes(newLine);
                    s.Write(bytes, 0, bytes.Length);

                    bytes = encoding.GetBytes(footer);
                    s.Write(bytes, 0, bytes.Length);

                    bytes = encoding.GetBytes(newLine);
                    s.Write(bytes, 0, bytes.Length);
                }

                req.PreAuthenticate           = true;
                req.AllowWriteStreamBuffering = true;

                HttpWebResponse response = (HttpWebResponse)req.GetResponse();

                string responseBody;
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    responseBody = reader.ReadToEnd();

                int    start   = responseBody.IndexOf("media_id_string") + "media_id_string".Length + 3;
                int    end     = responseBody.IndexOf(",", start) - 1;
                string mediaId = responseBody.Substring(start, end - start);

                ids.Add(mediaId);
            }

            return(ids);
        }
Ejemplo n.º 15
0
 private static string InternalUpdateWithMedia(TwUser user, string encodedStatus, string replyId, List <FileInfo> media)
 {
     return(InternalUpdateStatus(user, encodedStatus, replyId, UploadMedia(user, media)));
 }
Ejemplo n.º 16
0
		private static string InternalUpdateWithMedia(TwUser user, string encodedStatus, string replyId, List<FileInfo> media)
		{
			return InternalUpdateStatus(user, encodedStatus, replyId, UploadMedia(user, media));
		}
Ejemplo n.º 17
0
 public void UpdateTwitterAccount(OAuthTokenResponse atoken, TwUser usr)
 {
     usr.TokenSecret = atoken.TokenSecret;
     usr.Token       = atoken.Token;
     db.SaveChanges();
 }