示例#1
0
        /// <summary>
        /// Upload the picture
        /// </summary>
        /// <param name="url">URL to upload picture to</param>
        /// <param name="ppo">Postdata</param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 60000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("source", "PockeTwit");
                contents.Add("sourceLink", "http://code.google.com/p/pocketwit/");
                if (!string.IsNullOrEmpty(ppo.Message))
                {
                    contents.Add("message", ppo.Message);
                }

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), ppo.ContentType);

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);
                return contents.UploadXML(request);
            }
            catch (WebException ex)
            {
                if (ex.Response is HttpWebResponse)
                {
                    using(HttpWebResponse response = ex.Response as HttpWebResponse)
                    {
                        OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, String.Format(PockeTwit.Localization.XmlBasedResourceManager.GetString("Error Uploading: Service returned message '{0}'"), response.StatusDescription), ppo.Filename));
                    }
                }
                else if (ex.InnerException is System.Net.Sockets.SocketException)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, ex.Message, ppo.Filename));
                }
                else
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD, ppo.Filename));
                return null;
            }
            catch (Exception)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
示例#2
0
        /// <summary>
        /// Fetch a picture
        /// </summary>
        /// <param name="pictureURL"></param>
        public override void FetchPicture(string pictureURL, Twitter.Account account)
        {
            #region Argument check

            this.account = account;

            //Need a url to read from.
            if (string.IsNullOrEmpty(pictureURL))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_DOWNLOAD));
            }

            #endregion

            try
            {
                workerPPO = new PicturePostObject();
                workerPPO.Message = pictureURL;

                if (workerThread == null)
                {
                    workerThread = new System.Threading.Thread(new System.Threading.ThreadStart(ProcessDownload));
                    workerThread.Name = "PictureUpload";
                    workerThread.Start();
                }
                else
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.NotReady, "", "A request is already running."));
                }
            }
            catch (Exception)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_DOWNLOAD));
            }
        }
示例#3
0
        /// <summary>
        /// Upload the picture
        /// </summary>
        /// <param name="url">URL to upload picture to</param>
        /// <param name="ppo">Postdata</param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 20000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("api_key", API_KEY);
                contents.Add("source", API_ORIGIN_ID);
                if (!string.IsNullOrEmpty(ppo.Message))
                    contents.Add("message", ppo.Message);
                else
                    contents.Add("message", "");

                string contentType = "";
                foreach (MediaType ft in this.API_FILETYPES)
                {
                    if (ft.Extension.Equals(Path.GetExtension(ppo.Filename).Substring(1), StringComparison.InvariantCultureIgnoreCase))
                    {
                        contentType = ft.ContentType;
                        break;
                    }
                }

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), contentType);

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);

                return contents.UploadXML(request);
            }
            catch (Exception)
            {
                //Socket exception 10054 could occur when sending large files.
                // Should be more specific

                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
示例#4
0
        /// <summary>
        /// Post a picture
        /// </summary>
        /// <param name="postData"></param>
        public override bool PostPicture(PicturePostObject postData, Twitter.Account account)
        {
            #region Argument check

            //Check for empty path
            if (string.IsNullOrEmpty(postData.Filename))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
            }

            //Check for empty credentials
            if (string.IsNullOrEmpty(account.OAuth_token) ||
                string.IsNullOrEmpty(account.OAuth_token_secret))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
            }

            #endregion

            _account = account;

            using (postData.PictureStream = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    XmlDocument uploadResult = UploadPicture(API_UPLOAD, postData, account);

                    if (uploadResult == null)
                    {
                        return false;
                    }

                    string URL = uploadResult.SelectSingleNode("//url").InnerText;
                    postData.URL = URL;
                    OnUploadFinish(new PictureServiceEventArgs(PictureServiceErrorLevel.OK, URL, string.Empty, postData.Filename));
                    return true;
                }
                catch
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                    return false;
                }
            }
        }
示例#5
0
        /// <summary>
        /// Send a picture to a twitter picture framework without the use of the finish event
        /// </summary>
        /// <param name="postData">Postdata</param>
        /// <returns>Returned URL from server</returns>
        public override bool PostPictureMessage(PicturePostObject postData)
        {
            #region Argument check

            //Check for empty path
            if (string.IsNullOrEmpty(postData.Filename))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty , API_ERROR_UPLOAD));
                return false;
            }

            //Check for empty credentials
            if (string.IsNullOrEmpty(postData.Username) ||
                string.IsNullOrEmpty(postData.Password))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed,string.Empty , API_ERROR_UPLOAD));
                return false;
            }

            #endregion

            using (FileStream file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    //Load the picture data
                    byte[] incoming = new byte[file.Length];
                    file.Read(incoming, 0, incoming.Length);

                    //use sync.
                    postData.PictureData = incoming;
                    XmlDocument uploadResult = UploadPictureAndPost(postData);

                    if (uploadResult.SelectSingleNode("pikchur/error") == null)
                    {
                        XmlNode UrlKeyNode = uploadResult.SelectSingleNode("pikchur/post/url");
                        string URL = UrlKeyNode.InnerText;
                        URL = URL.Replace("\n", "");
                    }
                    else
                    {
                        OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                    }
                }
                catch (Exception)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                    return false;
                }
            }
            return true;
        }
示例#6
0
        /// <summary>
        /// Upload picture
        /// </summary>
        /// <param name="ppo"></param>
        /// <returns></returns>
        private XmlDocument UploadPictureAndPost(PicturePostObject ppo)
        {
            if (string.IsNullOrEmpty(AUTH_KEY))
            {
                RequestAuthKey(ppo);
            }
            if (string.IsNullOrEmpty(AUTH_KEY))
            {
                //Authorisation has failed.
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(API_UPLOAD);

                string boundary = Guid.NewGuid().ToString();
                request.Credentials = new NetworkCredential(ppo.Username, ppo.Password);
                request.Headers.Add("Accept-Language", "cs,en-us;q=0.7,en;q=0.3");
                request.PreAuthenticate = true;
                request.ContentType = string.Format("multipart/form-data;boundary={0}", boundary);

                //request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "POST";
                request.Timeout = 20000;
                string header = string.Format("--{0}", boundary);
                string ender = "\r\n" + header + "\r\n";

                StringBuilder contents = new StringBuilder();

                contents.Append(CreateContentPartStringForm(header, "data[api][key]", API_KEY, "application/octet-stream"));
                contents.Append(CreateContentPartStringForm(header, "data[api][status]", ppo.Message, "application/octet-stream"));
                contents.Append(CreateContentPartStringForm(header, "data[api][auth_key]", AUTH_KEY, "application/octet-stream"));
                contents.Append(CreateContentPartStringForm(header, "data[api][upload_only]", "FALSE", "application/octet-stream"));
                contents.Append(CreateContentPartStringForm(header, "data[api][origin]", API_ORIGIN_ID, "application/octet-stream"));

                if (!string.IsNullOrEmpty(ppo.Lat) && !string.IsNullOrEmpty(ppo.Lon))
                {
                    contents.Append(CreateContentPartStringForm(header, "data[api][geo][lat]", ppo.Lat, "application/octet-stream"));
                    contents.Append(CreateContentPartStringForm(header, "data[api][geo][lon]", ppo.Lon, "application/octet-stream"));
                }
                //image
                int imageIdStartIndex = ppo.Filename.LastIndexOf('\\') + 1;
                string filename = ppo.Filename.Substring(imageIdStartIndex, ppo.Filename.Length - imageIdStartIndex);
                contents.Append(CreateContentPartPicture(header, "dataAPIimage", filename));

                //Create the form message to send in bytes
                byte[] message = Encoding.UTF8.GetBytes(contents.ToString());
                byte[] footer = Encoding.UTF8.GetBytes(ender);
                request.ContentLength = message.Length + ppo.PictureData.Length + footer.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(message, 0, message.Length);
                    requestStream.Write(ppo.PictureData, 0, ppo.PictureData.Length);
                    requestStream.Write(footer, 0, footer.Length);
                    requestStream.Flush();
                    requestStream.Close();

                    using (WebResponse response = request.GetResponse())
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            XmlDocument responseXML = new XmlDocument();
                            string responseFromService = reader.ReadToEnd();
                            responseXML.LoadXml(responseFromService);
                            return responseXML;
                        }
                    }
                }
            }
            catch (Exception)
            {
                //Socket exception 10054 could occur when sending large files.
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
示例#7
0
        /// <summary>
        /// Upload the picture
        /// </summary>
        /// <param name="url">URL to upload picture to</param>
        /// <param name="ppo">Postdata</param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 20000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("api_key", TwitrPixKey);

                if (!string.IsNullOrEmpty(ppo.Message))
                    contents.Add("message", ppo.Message);
                else
                    contents.Add("message", "");

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename));

                if (!string.IsNullOrEmpty(ppo.Lat) && !string.IsNullOrEmpty(ppo.Lon))
                {
                    contents.Add("latitude", ppo.Lat);
                    contents.Add("longitude", ppo.Lat);
                }

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);

                return contents.UploadXML(request);
            }
            catch (WebException we)
            {
                StreamReader sr = new StreamReader(we.Response.GetResponseStream());
                string resp = sr.ReadToEnd();
                Console.WriteLine(resp);
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
            catch (Exception)
            {
                //Socket exception 10054 could occur when sending large files.
                //Should be more specific

                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
示例#8
0
        /// <summary>
        /// Upload the picture
        /// </summary>
        /// <param name="url">URL to upload picture to</param>
        /// <param name="ppo">Postdata</param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 20000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("key", TwitPicKey);

                if (!string.IsNullOrEmpty(ppo.Message))
                    contents.Add("message", ppo.Message);
                else
                    contents.Add("message", "");

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), ppo.ContentType);

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);

                return contents.UploadXML(request);
            }
            catch (Exception /*e*/)
            {
                //Socket exception 10054 could occur when sending large files.
                // Should be more specific

                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
示例#9
0
 private void StartUpload(IPictureService mediaService, String fileName)
 {
     if (mediaService.CanUploadMessage && ClientSettings.SendMessageToMediaService)
     {
         AddPictureToForm(fileName, pictureFromStorage);
         picturePath = fileName;
         //Reduce length of message 140-pictureService.UrlLength
         pictureUsed = true;
     }
     else
     {
         uploadingPicture = true;
         AddPictureToForm(FormColors.GetThemeIconPath("wait.png"), pictureFromStorage);
         using (PicturePostObject ppo = new PicturePostObject())
         {
             ppo.Filename = fileName;
             ppo.Username = AccountToSet.UserName;
             ppo.Password = AccountToSet.Password;
             ppo.UseAsync = false;
             Cursor.Current = Cursors.WaitCursor;
             mediaService.PostPicture(ppo);
         }
     }
 }
示例#10
0
        private bool PostTheUpdate()
        {
            LocationFinder.StopPosition();
            if (!string.IsNullOrEmpty(StatusText) ||
                (!string.IsNullOrEmpty(picturePath) && pictureService.CanUploadMessage && ClientSettings.SendMessageToMediaService))
            {
                Cursor.Current = Cursors.WaitCursor;
                var updateText = TrimTo140(StatusText);

                if(updateText.Length>140)
                {
                    if (PockeTwit.Localization.LocalizedMessageBox.Show("The text is still too long.  If you post it twitter will cut off the end.  Post anyway?", "Long Text", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.No)
                    {
                        return false;
                    }
                }
                
                if (!string.IsNullOrEmpty(picturePath) && pictureService.CanUploadMessage && ClientSettings.SendMessageToMediaService )
                {
                    PicturePostObject ppo = new PicturePostObject();
                    ppo.Filename = picturePath;
                    ppo.Username = AccountToSet.UserName;
                    ppo.Password = AccountToSet.Password;
                    ppo.Message = StatusText;

                    if (pictureService.CanUploadGPS && GPSLocation != null)
                    {
                        try
                        {
                            ppo.Lat = GPSLocation.Split(',')[0];
                            ppo.Lon = GPSLocation.Split(',')[1];
                        }
                        catch { }
                    }

                    return pictureService.PostPictureMessage(ppo);
                }
                else
                {


                    Yedda.Twitter TwitterConn = new Yedda.Twitter();
                    TwitterConn.AccountInfo = AccountToSet;

                    try
                    {
                        if (GPSLocation != null)
                        {
                            TwitterConn.SetLocation(GPSLocation);
                        }
                    }
                    catch { }
                    string retValue = string.Empty;
                    string userID = IsDirectMessage(updateText);
                    if (string.IsNullOrEmpty(userID))
                        retValue = TwitterConn.Update(updateText, in_reply_to_status_id, Yedda.Twitter.OutputFormatType.XML);
                    else
                    {
                        retValue = TwitterConn.SendDirectMessage(userID, updateText.Substring(updateText.IndexOf(userID) + userID.Length + 1), in_reply_to_status_id, Yedda.Twitter.OutputFormatType.XML);
                    }
                    uploadedPictureURL = string.Empty;
                    uploadingPicture = false;

                    if (string.IsNullOrEmpty(retValue))
                    {
                        PockeTwit.Localization.LocalizedMessageBox.Show("Error posting status -- empty response.  You may want to try again later.");
                        return false;
                    }
                    try
                    {
                        Library.status.DeserializeSingle(retValue, AccountToSet);
                    }
                    catch
                    {
                        PockeTwit.Localization.LocalizedMessageBox.Show("Error posting status -- bad response.  You may want to try again later.");
                        return false;
                    }

                    return true;
                }
            }
            return true;
        }
示例#11
0
        /// <summary>
        /// Post a picture.
        /// </summary>
        /// <param name="postData"></param>
        public override void PostPicture(PicturePostObject postData)
        {
            #region Argument check

            //Check for empty path
            if (string.IsNullOrEmpty(postData.Filename))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "",API_ERROR_UPLOAD));
            }

            //Check for empty credentials
            if (string.IsNullOrEmpty(postData.Username) ||
                string.IsNullOrEmpty(postData.Password) )
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_UPLOAD));
            }

            #endregion

            using (System.IO.FileStream file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    //Load the picture data
                    byte[] incoming = new byte[file.Length];
                    file.Read(incoming, 0, incoming.Length);

                    if (postData.UseAsync)
                    {
                        workerPPO = (PicturePostObject) postData.Clone();
                        workerPPO.PictureData = incoming;

                        if (workerThread == null)
                        {
                            workerThread = new System.Threading.Thread(new System.Threading.ThreadStart(ProcessUpload));
                            workerThread.Name = "PictureUpload";
                            workerThread.Start();
                        }
                        else
                        {
                            OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.NotReady, "", API_ERROR_NOTREADY));
                        }
                    }
                    else
                    {
                        //use sync.
                        postData.PictureData = incoming;
                        XmlDocument uploadResult = UploadPicture(API_UPLOAD, postData);

                        if (uploadResult == null)
                        {
                            return;
                        }

                        if (uploadResult.SelectSingleNode("rsp").Attributes["status"].Value == "fail")
                        {
                            string ErrorText = uploadResult.SelectSingleNode("//err").Attributes["msg"].Value;
                            OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, ErrorText));
                        }
                        else
                        {
                            string URL = uploadResult.SelectSingleNode("//mediaurl").InnerText;
                            OnUploadFinish(new PictureServiceEventArgs(PictureServiceErrorLevel.OK, URL, string.Empty, postData.Filename));
                        }
                    }
                }
                catch (Exception)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                }
            }
        }
示例#12
0
        /// <summary>
        /// Upload a picture
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ppo"></param>
        /// <returns></returns>
        private XmlDocument UploadPictureMessage(string url, PicturePostObject ppo)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);

                string boundary = System.Guid.NewGuid().ToString();
                request.Credentials = new NetworkCredential(ppo.Username, ppo.Password);
                request.Headers.Add("Accept-Language", "cs,en-us;q=0.7,en;q=0.3");
                request.PreAuthenticate = true;
                request.ContentType = string.Format("multipart/form-data;boundary={0}", boundary);

                //request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "POST";
                request.Timeout = 20000;
                string header = string.Format("--{0}", boundary);
                string ender = "\r\n" + header + "\r\n";

                StringBuilder contents = new StringBuilder();

                contents.Append(CreateContentPartString(header, "username", ppo.Username));
                contents.Append(CreateContentPartString(header, "password", ppo.Password));
                contents.Append(CreateContentPartString(header, "message", ppo.Message));

                int imageIdStartIndex = ppo.Filename.LastIndexOf('\\') + 1;
                string filename = ppo.Filename.Substring(imageIdStartIndex, ppo.Filename.Length - imageIdStartIndex);
                contents.Append(CreateContentPartPicture(header, filename));

                //Create the form message to send in bytes
                byte[] message = Encoding.UTF8.GetBytes(contents.ToString());
                byte[] footer = Encoding.UTF8.GetBytes(ender);
                request.ContentLength = message.Length + ppo.PictureData.Length + footer.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(message, 0, message.Length);
                    requestStream.Write(ppo.PictureData, 0, ppo.PictureData.Length);
                    requestStream.Write(footer, 0, footer.Length);
                    requestStream.Flush();
                    requestStream.Close();

                    using (WebResponse response = request.GetResponse())
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            XmlDocument responseXML = new XmlDocument();
                            string resp = reader.ReadToEnd();
                            responseXML.LoadXml(resp);
                            return responseXML;
                        }
                    }
                }
            }
            catch (Exception)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_UPLOAD));
                return null;
            }

        }
示例#13
0
        public override bool PostPictureMessage(PicturePostObject postData)
        {
            #region Argument check

            //Check for empty path
            if (string.IsNullOrEmpty(postData.Filename))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return false;
            }

            //Check for empty credentials
            if (string.IsNullOrEmpty(postData.Username) ||
                string.IsNullOrEmpty(postData.Password))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return false;
            }

            #endregion

            using (System.IO.FileStream file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    //Load the picture data
                    byte[] incoming = new byte[file.Length];
                    file.Read(incoming, 0, incoming.Length);

                    postData.PictureData = incoming;
                    XmlDocument uploadResult = UploadPictureMessage(API_UPLOAD_POST, postData);

                    if (uploadResult == null)
                    {
                        //event allready thrown in upload
                        return false;
                    }

                    if (uploadResult.SelectSingleNode("rsp").Attributes["status"].Value == "fail")
                    {
                        string ErrorText = uploadResult.SelectSingleNode("//err").Attributes["msg"].Value;
                        OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, ErrorText));
                        return false;
                    }

                }
                catch (Exception)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                    return false;
                }
            }
            return true;
        }
示例#14
0
 /// <summary>
 /// Post a picture
 /// </summary>
 /// <param name="postData"></param>
 public override bool PostPicture(PicturePostObject postData, Twitter.Account account)
 {
     return DoPost(postData, account, true);
 }
示例#15
0
        /// <summary>
        /// Post a picture.
        /// </summary>
        /// <param name="postData"></param>
        public override bool PostPicture(PicturePostObject postData, Twitter.Account account)
        {
            #region Argument check

            //Check for empty path
            if (string.IsNullOrEmpty(postData.Filename))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "",API_ERROR_UPLOAD));
                return false;
            }

            //Check for empty credentials
            if (string.IsNullOrEmpty(account.OAuth_token_secret) ||
                string.IsNullOrEmpty(account.OAuth_token))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_UPLOAD));
                return false;
            }

            #endregion

            using (System.IO.FileStream file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    postData.PictureStream = file;
                    XmlDocument uploadResult = UploadPicture(API_UPLOAD, postData, account);

                    if (uploadResult == null)
                    {
                        return false;
                    }

                    if (uploadResult.SelectSingleNode("rsp").Attributes["status"].Value == "fail")
                    {
                        string ErrorText = uploadResult.SelectSingleNode("//err").Attributes["msg"].Value;
                        OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, ErrorText));
                        return false;
                    }
                    else
                    {
                        string URL = uploadResult.SelectSingleNode("//mediaurl").InnerText;
                        postData.URL = URL;
                        OnUploadFinish(new PictureServiceEventArgs(PictureServiceErrorLevel.OK, URL, string.Empty, postData.Filename));
                        return true;
                    }
                }
                catch (Exception)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                    return false;
                }
            }
        }
示例#16
0
        private bool DoPost(PicturePostObject postData, Twitter.Account account, bool successEvent)
        {
            this.account = account;
            #region Argument check

            this.account = account;

            //Check for empty path
            if (string.IsNullOrEmpty(postData.Filename))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
            }

            //Check for empty credentials
            if (string.IsNullOrEmpty(account.OAuth_token) ||
                string.IsNullOrEmpty(account.OAuth_token_secret))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
            }

            #endregion

            using (System.IO.FileStream file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    postData.PictureStream = file;
                    XmlDocument uploadResult = UploadPicture(API_UPLOAD, postData, account);

                    if (uploadResult == null) // occurs in the event of an error
                        return false;
                    string URL = uploadResult.SelectSingleNode("//url").InnerText;
                    postData.URL = URL;
                    if(successEvent)
                    {
                        OnUploadFinish(new PictureServiceEventArgs(PictureServiceErrorLevel.OK, URL, string.Empty, postData.Filename));
                    }
                }
                catch (Exception /*ex*/)
                {
                    // could do with catching a SocketException here, so we can give more useful information to the user
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                    return false;
                }
            }
            return true;
        }
示例#17
0
        /// <summary>
        /// Upload a picture
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ppo"></param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);

                request.PreAuthenticate = true;
                request.AllowWriteStreamBuffering = false;
                request.Timeout = 60000;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename));

                OAuth.OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);
                return contents.UploadXML(request);
            }
            catch (Exception)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_UPLOAD));
                return null;
            }
        }
示例#18
0
        public override void FetchPicture(string pictureURL)
        {
            #region Argument check

            //Need a url to read from.
            if (string.IsNullOrEmpty(pictureURL))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
            }

            #endregion

            try
            {
                workerPPO = new PicturePostObject();
                workerPPO.Message = pictureURL;

                if (workerThread == null)
                {
                    workerThread = new System.Threading.Thread(new System.Threading.ThreadStart(ProcessDownload));
                    workerThread.Name = "PictureUpload";
                    workerThread.Start();
                }
                else
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.NotReady, string.Empty, API_ERROR_NOTREADY));
                }
            }
            catch (Exception)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
            }
        }
示例#19
0
        private bool DoPost(PicturePostObject postData, Twitter.Account account, bool successEvent)
        {
            #region Argument check

            this._account = account;

            //Check for empty path
            if (string.IsNullOrEmpty(postData.Filename))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
            }

            //Check for empty credentials
            if (string.IsNullOrEmpty(account.OAuth_token) ||
                string.IsNullOrEmpty(account.OAuth_token_secret))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
            }

            #endregion

            using (System.IO.FileStream file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    #region async
                    //if (postData.UseAsync)
                    //{
                    //    workerPPO = (PicturePostObject) postData.Clone();
                    //    workerPPO.PictureData = incoming;

                    //    if (workerThread == null)
                    //    {
                    //        workerThread = new System.Threading.Thread(new System.Threading.ThreadStart(ProcessUpload));
                    //        workerThread.Name = "PictureUpload";
                    //        workerThread.Start();
                    //    }
                    //    else
                    //    {
                    //        OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.NotReady, string.Empty, "A request is already running."));
                    //    }
                    //}
                    //else
                    //{
                    #endregion
                    //use sync.

                    postData.PictureStream = file;
                    XmlDocument uploadResult = UploadPicture(API_UPLOAD_V2, postData);
                    //if (File.Exists("mobyresult.txt"))
                    //{
                    //    File.Delete("mobyresult.txt");
                    //}
                    //XmlTextWriter xm = new XmlTextWriter("mobyresult.txt", Encoding.UTF8);
                    //uploadResult.Save(xm);
                    //XmlDocument uploadResult = new XmlDocument();
                    //uploadResult.Load("mobyresult.txt");

                    if (uploadResult == null) // occurs in the event of an error
                    {
                        return false;
                    }
                    if (successEvent)
                    {
                        string URL = uploadResult.SelectSingleNode("//mediaurl").InnerText;
                        postData.URL = URL;
                        OnUploadFinish(new PictureServiceEventArgs(PictureServiceErrorLevel.OK, URL, string.Empty, postData.Filename));
                    }
                }
                catch (Exception)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                    return false;
                }
            }
            return true;
        }
示例#20
0
        /// <summary>
        /// Request authorisation key for use in posting.
        /// </summary>
        /// <param name="ppo"></param>
        private void RequestAuthKey(PicturePostObject ppo)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(API_AUTH);

                string boundary = System.Guid.NewGuid().ToString();
                NetworkCredential myCred = new NetworkCredential(ppo.Username, ppo.Password);
                CredentialCache MyCrendentialCache = new CredentialCache();
                Uri uri = new Uri(API_AUTH);
                MyCrendentialCache.Add(uri, "Basic", myCred);
                request.Credentials = MyCrendentialCache;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)";
                request.Headers.Set("Pragma", "no-cache");
                request.ContentType = string.Format("multipart/form-data;boundary={0}", boundary);

                //request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "POST";
                request.Timeout = 20000;

                string header = string.Format("--{0}", boundary);
                string ender = header + "\r\n";

                StringBuilder contents = new StringBuilder();

                contents.Append(CreateContentPartStringForm(header, "data[api][username]", ppo.Username, "application/octet-stream"));
                contents.Append(CreateContentPartStringForm(header, "data[api][password]", ppo.Password, "application/octet-stream"));
                contents.Append(CreateContentPartStringForm(header, "data[api][service]", "twitter", "application/octet-stream"));
                contents.Append(CreateContentPartStringForm(header, "data[api][key]", API_KEY, "application/octet-stream"));

                //Create the form message to send in bytes
                byte[] message = Encoding.UTF8.GetBytes(contents.ToString());

                request.ContentLength = message.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(message, 0, message.Length);
                    requestStream.Flush();
                    requestStream.Close();

                    using (WebResponse response = request.GetResponse())
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            XmlDocument responseXML = new XmlDocument();
                            string responseFromService = reader.ReadToEnd();
                            responseXML.LoadXml(responseFromService);
                            if (responseXML.SelectSingleNode("pikchur/error") == null)
                            {
                                XmlNode authKeyNode = responseXML.SelectSingleNode("pikchur/auth_key");
                                AUTH_KEY = authKeyNode.InnerText;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                //OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_DOWNLOAD));
            }
        }
示例#21
0
        /// <summary>
        /// Upload a picture
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ppo"></param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 20000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;
                request.Headers.Add("Action", "upload");

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("key", APPLICATION_NAME);

                if (!string.IsNullOrEmpty(ppo.Message))
                {
                    contents.Add("message", ppo.Message);
                    string hashTags = FindHashTags(ppo.Message, ",", 32);
                    if (!string.IsNullOrEmpty(hashTags))
                    {
                        contents.Add("tags", hashTags);
                    }
                }
                else
                {
                    contents.Add("message", "");
                }

                if (!string.IsNullOrEmpty(ppo.Lat) && !string.IsNullOrEmpty(ppo.Lon))
                {
                    contents.Add("latlong", string.Format("{0},{1}", ppo.Lat, ppo.Lon));
                }

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), ppo.ContentType);

                OAuthAuthorizer.AuthorizeEcho(request, _account.OAuth_token, _account.OAuth_token_secret);

                return contents.UploadXML(request);
            }
            catch (WebException ex)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, API_ERROR_UPLOAD, String.Format("Received response {0} from server ({1})", ex.Status, ex.Message)));
                return null;
            }
            catch (Exception)
            {
                //Socket exception 10054 could occur when sending large files.

                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
示例#22
0
        public override void PostPicture(PicturePostObject postData)
        {
            #region Argument check

            //Check for empty path
            if (string.IsNullOrEmpty(postData.Filename))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed,string.Empty , API_ERROR_UPLOAD));
            }

            //Check for empty credentials
            if (string.IsNullOrEmpty(postData.Username) ||
                string.IsNullOrEmpty(postData.Password))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
            }

            #endregion

            using (FileStream file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    //Load the picture data
                    byte[] incoming = new byte[file.Length];
                    file.Read(incoming, 0, incoming.Length);

                    if (postData.UseAsync)
                    {
                        workerPPO = (PicturePostObject)postData.Clone();
                        workerPPO.PictureData = incoming;

                        if (workerThread == null)
                        {
                            workerThread = new System.Threading.Thread(new System.Threading.ThreadStart(ProcessUpload));
                            workerThread.Name = "PictureUpload";
                            workerThread.Start();
                        }
                        else
                        {
                            OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.NotReady, string.Empty, API_ERROR_NOTREADY));
                        }
                    }
                    else
                    {
                        //use sync.
                        postData.PictureData = incoming;
                        XmlDocument uploadResult;
                        if (string.IsNullOrEmpty(postData.Message))
                        {
                            uploadResult = UploadPicture(postData);
                        }
                        else
                        {
                            uploadResult = UploadPictureAndPost(postData);
                        }

                        if (uploadResult.SelectSingleNode("pikchur/error") == null)
                        {
                            XmlNode UrlKeyNode = uploadResult.SelectSingleNode("pikchur/post/url");
                            string URL = UrlKeyNode.InnerText;
                            URL = URL.Replace("\n","");

                            OnUploadFinish(new PictureServiceEventArgs(PictureServiceErrorLevel.OK, URL, string.Empty, postData.Filename));
                        }
                        else
                        {
                            OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                        }
                    }
                }
                catch (Exception)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                }
            }
        }
示例#23
0
        /// <summary>
        /// Upload a picture
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ppo"></param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);

                string boundary = System.Guid.NewGuid().ToString();
                request.Timeout = 20000;
                request.AllowAutoRedirect = false;
                request.AllowWriteStreamBuffering = false;
                request.PreAuthenticate = true;

                Multipart content = new Multipart();
                content.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);

                content.Add("source", "pocketwit");

                if (!string.IsNullOrEmpty(ppo.Lat) && !string.IsNullOrEmpty(ppo.Lon))
                {
                    string geotag = string.Format("geotagged,geo:lat={0},geo:lon={1}", ppo.Lat, ppo.Lon);
                    content.Add("tags", geotag);
                }

                if (!string.IsNullOrEmpty(ppo.Message))
                {
                    content.Add("message", ppo.Message);
                }

                content.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), ppo.ContentType);

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret, Twitter.OutputFormatType.XML);

                return content.UploadXML(request);
            }
            catch (Exception)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_UPLOAD));
                return null;
            }
        }