public ActionResult Edit(int id)
        {
            if (!_orchardServices.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not allowed to manage open authentication settings")))
            {
                return(new HttpUnauthorizedResult());
            }
            CreateProviderViewModel pv = _providerConfigurationService.Get(id);

            pv.ProviderNameList = getAllProviderName(pv.ProviderName);
            return(View((Object)pv));
        }
Example #2
0
        public IAuthenticationClient GetClient(string providerName)
        {
            Argument.ThrowIfNullOrEmpty(providerName, "providerName");

            // Do we have a configuration?
            var clientConfiguration = _providerConfigurationService.Get(providerName);

            if (clientConfiguration == null)
            {
                return(null);
            }

            // Is this a known internal client
            var clientBuilder = _openAuthAuthenticationClients
                                .SingleOrDefault(o => o.ProviderName.Equals(providerName, StringComparison.OrdinalIgnoreCase));

            if (clientBuilder != null)
            {
                return(clientBuilder.Build(clientConfiguration));
            }

            return(CreateOpenIdClient(clientConfiguration));
        }
Example #3
0
        protected override DriverResult Display(TwitterPostPart part, string displayType, dynamic shapeHelper)
        {
            //Determine if we're on an admin page
            bool isAdmin = AdminFilter.IsApplied(_orchardServices.WorkContext.HttpContext.Request.RequestContext);

            if (isAdmin)
            {
                if ((displayType == "Detail") || (displayType == "Summary"))
                {
                    var         pcr = _providerConfigurationService.Get("Twitter");
                    TwitterOgVM vm  = new TwitterOgVM();
                    if (pcr != null)
                    {
                        vm.Site = pcr.UserIdentifier;
                    }
                    TwitterPostPartSettingVM setting = part.Settings.GetModel <TwitterPostPartSettingVM>();
                    var tokens = new Dictionary <string, object> {
                        { "Content", part.ContentItem }
                    };
                    if (!string.IsNullOrEmpty(setting.Description))
                    {
                        vm.Description = _tokenizer.Replace(setting.Description, tokens);
                    }
                    else
                    {
                        vm.Description = part.TwitterDescription;
                    }
                    if (!string.IsNullOrEmpty(setting.Image))
                    {
                        string ids = _tokenizer.Replace(setting.Image, tokens);

                        int idimage;
                        Int32.TryParse(ids.Replace("{", "").Replace("}", "").Split(',')[0], out idimage);;
                        if (idimage > 0)
                        {
                            // _orchardServices.ContentManager.Get(id);
                            // vm.Image = Url.ItemDisplayUrl(_orchardServices.ContentManager.Get(id));
                            var urlHelper = new UrlHelper(_orchardServices.WorkContext.HttpContext.Request.RequestContext);
                            //       vm.Image = urlHelper.ItemDisplayUrl(_orchardServices.ContentManager.Get(id));// get current display link
                            //   Fvm.Link = urlHelper.MakeAbsolute(urlHelper.ItemDisplayUrl(Twitterpart));// get current display link
                            var ContentImage = _orchardServices.ContentManager.Get(idimage, VersionOptions.Published);
                            //   var pathdocument = Path.Combine(ContentImage.As<MediaPart>().FolderPath, ContentImage.As<MediaPart>().FileName);
                            //  part.TwitterPicture = pathdocument;//
                            vm.Image = urlHelper.MakeAbsolute(ContentImage.As <MediaPart>().MediaUrl);
                            //   .ResizeMediaUrl(Width: previewWidth, Height: previewHeight, Mode: "crop", Alignment: "middlecenter", Path: Model.MediaData.MediaUrl)');
                        }
                        else
                        {
                            vm.Image = "";
                        }
                    }
                    else
                    {
                        vm.Image = part.TwitterPicture;
                    }
                    if (!string.IsNullOrEmpty(setting.Title))
                    {
                        vm.Title = _tokenizer.Replace(setting.Title, tokens);
                    }

                    else
                    {
                        vm.Title = part.TwitterTitle;
                    }
                    return(ContentShape("Parts_TwitterPost_Detail",
                                        () => shapeHelper.Parts_TwitterPost_Detail(Twitter: vm, SendOnNextPublish: part.SendOnNextPublish, TwitterMessageSent: part.TwitterMessageSent)));
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Example #4
0
        public ActionResult GetPostTokenFacebook()
        {
            var pcr = _providerConfigurationService.Get("Facebook");

            if (pcr == null)
            {
                _notifier.Add(NotifyType.Error, T("No facebook account setting added, add one in Settings -> Open Authentication"));
                return(RedirectToAction("Index", "FacebookAccount", new { area = "Laser.Orchard.Facebook", id = -10 }));
            }
            string app_id     = pcr.ProviderIdKey;
            string app_secret = pcr.ProviderSecret;
            string scope      = "publish_actions,manage_pages,publish_pages,user_photos";//user_status status_updated nelle extended permission

            if (Request["code"] == null)
            {
                string url = string.Format(
                    "https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
                    app_id, Request.Url.AbsoluteUri, scope);
                Response.Redirect(url, false);
            }
            else
            {
                Dictionary <string, string> tokens = new Dictionary <string, string>();

                string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
                                           app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);

                HttpWebRequest request      = System.Net.WebRequest.Create(url) as HttpWebRequest;
                string         access_token = "";
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    string       vals   = reader.ReadToEnd();
                    var          json   = JObject.Parse(vals);
                    if ((json["access_token"]).Type != JTokenType.Null)
                    {
                        access_token = (json["access_token"] ?? "").ToString();
                    }
                }
                var client = new FacebookClient(access_token);

                //  FacebookPostSettingPart getpart = _orchardServices.WorkContext.CurrentSite.As<FacebookPostSettingPart>();
                //  getpart.FacebookAccessToken = access_token;
                object taskresult       = client.Get("/me");
                var    result           = (IDictionary <string, object>)taskresult;
                string facebookUserId   = (string)result["id"];
                string facebookUserName = (string)result["name"];

                FacebookAccountVM fvm = new FacebookAccountVM();
                fvm.UserToken      = access_token;
                fvm.UserIdFacebook = facebookUserId;
                fvm.UserName       = facebookUserName;
                OrchardRegister(fvm);


                JsonObject jsonResponse = client.Get("me/accounts") as JsonObject;

                Uri profilePictureUrl = new Uri(string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", facebookUserId, "small", access_token));
                var mediaPath         = HostingEnvironment.IsHosted
                    ? HostingEnvironment.MapPath("~/Media/") ?? ""
                    : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Media");
                WebClient webClient = new WebClient();
                webClient.DownloadFile(profilePictureUrl, mediaPath + _shellSettings.Name + @"\facebook_" + facebookUserId + ".jpg");

                Dictionary <string, string> ElencoPagine = new Dictionary <string, string>();
                foreach (var account in (JsonArray)jsonResponse["data"])
                {
                    string accountName = (string)(((JsonObject)account)["name"]);
                    fvm               = new FacebookAccountVM();
                    fvm.UserToken     = access_token;
                    fvm.PageName      = accountName;
                    fvm.PageToken     = (string)(((JsonObject)account)["access_token"]);
                    fvm.IdPage        = (string)(((JsonObject)account)["id"]);
                    profilePictureUrl = new Uri(string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", fvm.IdPage, "small", access_token));
                    webClient         = new WebClient();
                    webClient.DownloadFile(profilePictureUrl, mediaPath + _shellSettings.Name + @"\facebook_" + fvm.IdPage + ".jpg");
                    fvm.UserIdFacebook = fvm.IdPage;
                    fvm.UserName       = accountName;
                    OrchardRegister(fvm);
                }
                return(RedirectToAction("Index", "FacebookAccount", new { area = "Laser.Orchard.Facebook", id = -10 }));
            }
            return(null);
        }
Example #5
0
        public ActionResult GetPostTokenTwitter()
        {
            ProviderConfigurationRecord pcr = _providerConfigurationService.Get("Twitter");

            if (pcr == null)
            {
                _notifier.Add(NotifyType.Error, T("No twitter account setting added, add one in Settings -> Open Authentication"));
                return(RedirectToAction("Index", "TwitterAccount", new { area = "Laser.Orchard.Twitter", id = -10 }));
            }

            string consumerKey    = pcr.ProviderIdKey;
            string consumerSecret = pcr.ProviderSecret;

            // il meccanismo utilizzato è il 3-Legged oAuth
            if (Request["oauth_token"] == null)
            {
                string             tmpreq   = Request.Url.AbsoluteUri;
                OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(consumerKey, consumerSecret, tmpreq);
                Response.Redirect(string.Format("https://api.twitter.com/oauth/authorize?oauth_token={0}", reqToken.Token));
            }
            else
            {
                string           requestToken = Request["oauth_token"].ToString();
                string           verifier     = Request["oauth_verifier"].ToString();
                var              tokens       = OAuthUtility.GetAccessToken(consumerKey, consumerSecret, requestToken, verifier);
                TwitterAccountVM vm           = new TwitterAccountVM();
                vm.DisplayAs       = tokens.ScreenName;
                vm.UserToken       = tokens.Token;
                vm.UserTokenSecret = tokens.TokenSecret; // conterrà l'account_token_secret
                #region [recupero immagine]
                OAuthTokens accessToken = new OAuthTokens();
                accessToken.AccessToken       = vm.UserToken;
                accessToken.AccessTokenSecret = vm.UserTokenSecret;
                accessToken.ConsumerKey       = consumerKey;
                accessToken.ConsumerSecret    = consumerSecret;

                TwitterResponse <TwitterUser> myTwitterUser = TwitterUser.Show(accessToken, tokens.ScreenName);
                TwitterUser user = myTwitterUser.ResponseObject;
                var         profilePictureUrl = user.ProfileImageLocation;
                var         mediaPath         = HostingEnvironment.IsHosted
                 ? HostingEnvironment.MapPath("~/Media/") ?? ""
                 : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Media");
                WebClient webClient = new WebClient();
                webClient.DownloadFile(profilePictureUrl, mediaPath + _shellSettings.Name + @"\twitter_" + vm.DisplayAs + ".jpg");
                #endregion
                // var avatarFormat = "https://api.twitter.com/1.1/users/show.json?screen_name={0}";
                // var avatarUrl = string.Format(avatarFormat, vm.DisplayAs);
                // HttpWebRequest avatarRequest = (HttpWebRequest)WebRequest.Create(avatarUrl);
                // var timelineHeaderFormat = "{0} {1}";
                // avatarRequest.Headers.Add("Authorization", String.Format("Bearer {0}", vm.UserToken));
                //// avatarRequest.Headers.Add("Authorization",
                ////                             string.Format(timelineHeaderFormat, "oauth_token", requestToken));
                // avatarRequest.Method = "Get";
                // WebResponse timeLineResponse = avatarRequest.GetResponse();

                // var reader = new StreamReader(timeLineResponse.GetResponseStream());
                // var avatarJson = string.Empty;
                //using (authResponse) {
                //    using (var reader = new StreamReader(timeLineResponse.GetResponseStream())) {
                //        avatarJson = reader.ReadToEnd();
                //    }
                //}

                // Uri profilePictureUrl = new Uri(string.Format("https://api.twitter.com/1.1/users/show.json?screen_name={1}", vm.DisplayAs ));

                OrchardRegister(vm);
            }
            return(RedirectToAction("Index", "TwitterAccount", new { area = "Laser.Orchard.Twitter", id = -10 }));
        }
        public ResponseAction PostTwitter(PostToTwitterViewModel message)
        {
            ResponseAction rsp = new ResponseAction();

            rsp.Success = true;
            bool trysended = false;
            List <TwitterAccountPart>   TwitterAccountSettings = Twitter_GetAccessToken(message.AccountList);
            ProviderConfigurationRecord pcr = _providerConfigurationService.Get("Twitter");

            foreach (TwitterAccountPart Faccount in TwitterAccountSettings)
            {
                try {
                    trysended = true;
                    OAuthTokens accesstoken = new OAuthTokens()
                    {
                        AccessToken       = Faccount.UserToken,
                        AccessTokenSecret = Faccount.UserTokenSecret,
                        ConsumerKey       = pcr.ProviderIdKey,
                        ConsumerSecret    = pcr.ProviderSecret
                    };
                    TwitterResponse <TwitterStatus> response;
                    string realmessage = message.Message;
                    if (!string.IsNullOrEmpty(message.Link))
                    {
                        realmessage += " " + message.Link;
                    }
                    if (string.IsNullOrEmpty(message.Picture))
                    {
                        response = TwitterStatus.Update(accesstoken, realmessage.Trim());
                    }
                    else
                    {
                        var mediaPath = HostingEnvironment.IsHosted
                                ? HostingEnvironment.MapPath("~/Media/") ?? ""
                                : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Media");
                        string physicalPath = mediaPath + _shellsettings.Name + "\\" + message.Picture;
                        byte[] photo        = System.IO.File.ReadAllBytes(physicalPath);
                        response = TwitterStatus.UpdateWithMedia(accesstoken, realmessage.Trim(), photo, new StatusUpdateOptions()
                        {
                            UseSSL = true, APIBaseAddress = "http://api.twitter.com/1.1/"
                        });
                    }
                    if (response.Result != RequestResult.Success)
                    {
                        if (response.Content != null)
                        {
                            Logger.Error("response.Content:" + response.Content);
                        }
                        rsp.Success = false;
                        if (response.ErrorMessage != null)
                        {
                            Logger.Error("response.ErrorMessage:" + response.ErrorMessage);
                            _notifier.Add(NotifyType.Error, T("Can't post on twitter: {0} {1}", Faccount.DisplayAs, response.ErrorMessage));
                        }
                        else
                        {
                            var       serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                            var       jsondict   = serializer.Deserialize <Dictionary <string, object> >(response.Content);
                            ArrayList errors     = (ArrayList)jsondict["errors"];
                            foreach (System.Collections.Generic.Dictionary <string, object> error in errors)
                            {
                                string errormsg = "";
                                foreach (var errordict in error)
                                {
                                    errormsg += " " + errordict.Key.ToString() + ":" + errordict.Value.ToString();
                                }
                                _notifier.Add(NotifyType.Error, T("Can't post on twitter: {0} {1}", Faccount.DisplayAs, errormsg));
                            }
                        }
                    }
                } catch (Exception ex) {
                    Logger.Error("Twitter Posting Error Message::" + ex.Message);
                    rsp.Success = false;
                    rsp.Message = "Twitter Posting Error Message: " + ex.Message;
                    _notifier.Add(NotifyType.Error, T("Twitter Posting {0}  Error Message: {1}", Faccount.DisplayAs, ex.Message));
                }
            }
            if (trysended && rsp.Success)
            {
                _notifier.Add(NotifyType.Information, T("Twitter posted"));
            }
            return(rsp);
        }