Esempio n. 1
0
 /**
 * Identical to the parent constructor
 *
 * @param Array $config the application configuration. Additionally
 * accepts "sharedSession" as a boolean to turn on a secondary
 * cookie for environments with a shared session (that is, your app
 * shares the domain with other apps).
 * @see BaseFacebook::__construct in facebook.php
 */
 public Facebook(FacebookConfig config)
     : base(config)
 {
     if (!string.IsNullOrWhiteSpace(config.sharedSession)) {
       this.initSharedSession();
     }
 }
        public async Task <string?> PostLinkAsync(Uri link, FacebookConfig config)
        {
            _logger.LogDebug("Post new link to facebook");
            try
            {
                var response =
                    await $"{config.Url}/{config.PageId}/feed"
                    .SetQueryParam("link", link.ToString())
                    .SetQueryParam("access_token", config.AccessToken)
                    .WithTimeout(60)
                    .PostUrlEncodedAsync(new { });
                var data = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    _logger.LogError("Error while sending facebook request");
                    throw new Exception($"Bad facebook response: {data}");
                }

                var postResponse = JsonConvert.DeserializeObject <FacebookNewPostResponse>(data);
                _logger.LogDebug("Link posted to facebook");
                return(postResponse.Id);
            }
            catch (FlurlHttpException ex)
            {
                _logger.LogError(ex, "Error in request to Facebook: {errorText}. Response: {response}", ex.ToString(),
                                 await ex.GetResponseStringAsync());
                return(null);
            }
        }
Esempio n. 3
0
        public example()
        {
            FacebookConfig config = new FacebookConfig(){ appId = "117743971608120", apiSecret = "<secret>" };
            Facebook facebook = new Facebook(config);

            // Get User ID
            String user = facebook.getUser();

            // We may or may not have this data based on whether the user is logged in.
            //
            // If we have a $user id here, it means we know the user is logged into
            // Facebook, but we don't know if the access token is valid. An access
            // token is invalid if the user logged out of Facebook.
            FacebookResponse user_profile = null;
            if (!String.IsNullOrEmpty(user)) {
                try {
                    // Proceed knowing you have a logged in user who's authenticated.
                    user_profile = facebook._graph("/me");
                } catch (Exception e) {
                    user = null;
                }
            }
            String logoutUrl = null;
            String loginUrl = null;
            // Login or logout url will be needed depending on current user state.
            if (!String.IsNullOrEmpty(user)) {
                logoutUrl = facebook.getLogoutUrl();
            } else {
                loginUrl = facebook.getLoginUrl();
            }
        }
Esempio n. 4
0
 public void Start()
 {
     AreaRegistration.RegisterAllAreas();
     FacebookConfig.Register(GlobalFacebookConfiguration.Configuration);
     WebApiConfig.Register(GlobalConfiguration.Configuration);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     Database.SetInitializer(new FacebookBucketListInit());
 }
Esempio n. 5
0
 public FacebookService(IUserRepository repository,
                        IFacebookSender fbSender,
                        IOptions <FacebookConfig> configs,
                        ILogger <FacebookService> logger)
 {
     _repository = repository;
     _fbSender   = fbSender;
     _configs    = configs.Value;
     _logger     = logger;
 }
Esempio n. 6
0
 public MainForm()
 {
     InitializeComponent();
     r_FacebookConfig = FacebookConfig.LoadFromFile(k_ConfigFileName);
     m_FileLoger = new FileLogger(r_FacebookConfig.LogFilePath);
     r_FacebookClient = new FacebookClientTraceLoggerProxy(new FacebookClient(r_FacebookConfig), m_FileLoger);
     m_PopularityFactory = new PopularityFactory(r_FacebookClient);
     OnError += this.showError;
     OnError += (sender, error) => m_FileLoger.Error(error.GetException().Message, error.GetException());
 }
Esempio n. 7
0
        public void TestFacebook()
        {
            var streamInsightInstanceName = Properties.Settings.Default.InstanceName;
            var server      = Server.Create(streamInsightInstanceName);
            var application = server.CreateApplication("facebooktest");

            var inputConfig = new FacebookConfig
            {
                AccessToken        = AccessTokenTbx.Text,
                UsernameOrUniqueId = UsernameOrUniqueIdTbx.Text,
                RefreshPeriod      = int.Parse(RefreshIntervalTbx.Text) * 1000
            };


            var input = CepStream <FacebookItem> .Create("facebook", typeof(FacebookFactory), inputConfig, EventShape.Point);

            // Configure output adapter
            var outputConfig = new StackerConfig
            {
                StackerCtlPipeName = stackerCtl1.PipeName,
                StackerCtlHostName = "localhost"
            };

            // Create query and bind to the output adapter
            var expr = from e in input
                       select new { e.Id, e.FromName, Message = !string.IsNullOrEmpty(e.Message) ? e.Message : e.Description };

            query = expr.ToQuery(application, "query", "...", typeof(StackerFactory), outputConfig, EventShape.Point, StreamEventOrder.FullyOrdered);

            // Start query
            query.Start();

            // Wait until query change state
            DiagnosticView diagnosticView;

            stopFlag = false;
            do
            {
                Thread.Sleep(100);
                diagnosticView = query.Application.Server.GetDiagnosticView(query.Name);
            } while (!stopFlag && (string)diagnosticView["QueryState"] == "Running");

            // Stop query
            query.Stop();

            application.Delete();
            server.Dispose();
        }
Esempio n. 8
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            // TODO: Prepare page for display here.

            // TODO: If your application contains multiple pages, ensure that you are
            // handling the hardware Back button by registering for the
            // Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
            // If you are using the NavigationHelper provided by some templates,
            // this event is handled for you.

            captureMgr = new MediaCapture();
            await captureMgr.InitializeAsync();

            capturePreview.Source = captureMgr;
            await captureMgr.StartPreviewAsync();

            IsPreviewing   = true;
            uploadLocation = new Dictionary <string, Uri>();

            DisplayInformation displayInfo = DisplayInformation.GetForCurrentView();

            displayInfo.OrientationChanged += DisplayInfo_OrientationChanged;
            DisplayInfo_OrientationChanged(displayInfo, null);

            var config = await GoogleConfig.Create(
                "517285908032-11moj33qbn01m7sem6g7gmfco2tp252v.apps.googleusercontent.com",
                new List <string>(new string[] { "https://www.googleapis.com/auth/drive" }),
                "google"
                );

            uploadLocation.Add("google", new Uri("https://www.googleapis.com/upload/drive/v2/files"));
            await AccountManager.AddAccount(config);

            var keyCloak = await KeycloakConfig.Create("shoot-third-party", "https://localhost:8443", "shoot-realm");

            uploadLocation.Add("shoot-third-party", new Uri("https://localhost:8443/shoot/rest/photos"));
            await AccountManager.AddKeyCloak(keyCloak);

            var facebook = FacebookConfig.Create("YYY", "XXX",
                                                 new List <string>(new string[] { "photo_upload, publish_actions" }), "facebook");

            uploadLocation.Add("facebook", new Uri("https://graph.facebook.com/me/photos"));
            await AccountManager.AddFacebook(facebook);
        }
Esempio n. 9
0
        public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {
            List <Setting> settings;

            using (var connection = new MySql.Data.MySqlClient.MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
            {
                connection.Open();
                settings = connection.Query <Setting>("SELECT SettingName, SettingValue FROM settings WHERE SettingName LIKE 'facebook%'").ToList();
            }

            var facebookConfig = new FacebookConfig
            {
                FacebookAppSecret = settings.FirstOrDefault(s => s.SettingName == "FacebookAppSecret").SettingValue,
                FacebookAppId     = settings.FirstOrDefault(s => s.SettingName == "FacebookAppId").SettingValue,
                OAuthCallbackPath = "/facebookoauth.axd"
            };

            container.Register(Component.For <FacebookConfig>().LifestyleSingleton().Instance(facebookConfig));
        }
		public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
		{
			List<Setting> settings;

			using(var connection = new MySql.Data.MySqlClient.MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
			{				
				connection.Open();
				settings = connection.Query<Setting>("SELECT SettingName, SettingValue FROM settings WHERE SettingName LIKE 'facebook%'").ToList();
			}

			var facebookConfig = new FacebookConfig
			{
				FacebookAppSecret = settings.FirstOrDefault(s => s.SettingName == "FacebookAppSecret").SettingValue,
				FacebookAppId = settings.FirstOrDefault(s => s.SettingName == "FacebookAppId").SettingValue,
				OAuthCallbackPath = "/facebookoauth.axd"
			};

			container.Register(Component.For<FacebookConfig>().LifestyleSingleton().Instance(facebookConfig));
		}
Esempio n. 11
0
        public async Task <bool> DeletePostAsync(string postId, FacebookConfig config)
        {
            _logger.LogDebug("Delete post from facebook");
            var response =
                await $"{config.Url}/{postId}"
                .SetQueryParam("access_token", config.AccessToken)
                .DeleteAsync();
            var data = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                _logger.LogError("Error while sending facebook request");
                throw new Exception($"Bad facebook response: {data}");
            }

            var postResponse = JsonConvert.DeserializeObject <FacebookDeleteResponse>(data);

            _logger.LogDebug("Post deleted from facebook: {response}", (postResponse.Success ? "Yes" : "No"));
            return(postResponse.Success);
        }
Esempio n. 12
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            BundleConfig.RegisterBundles(BundleTable.Bundles);
            BundleConfigAuthorPortal.RegisterBundles(BundleTable.Bundles);
            BundleConfigPortalAdmin.RegisterBundles(BundleTable.Bundles);
            BundleConfigUserPortal.RegisterBundles(BundleTable.Bundles);
            BundleConfigWidget.RegisterBundles(BundleTable.Bundles);
            BundleConfigWix.RegisterBundles(BundleTable.Bundles);

            AuthConfig.RegisterAuth();

            //JSON Settings
            var jsonSettings = new JsonSerializerSettings
            {
                NullValueHandling            = NullValueHandling.Ignore
                , ReferenceLoopHandling      = ReferenceLoopHandling.Ignore
                , Formatting                 = Formatting.Indented
                , PreserveReferencesHandling = PreserveReferencesHandling.Objects
            };

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jsonSettings;

            // initializing dependency injection  container
            var builder = new ContainerBuilder();

            // registration all the existing controllers
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            //Repositories registration
            AppExtensions.RegisterRepositories(builder);

            // NLog service registration
            builder.Register(c => new NLogLogger()).AsSelf().InstancePerRequest();

            //Services
            ServicesConfig.Register(builder);

            // build the dependencies
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));


            // Get your HttpConfiguration.
            var config = GlobalConfiguration.Configuration;

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // OPTIONAL: Register the Autofac filter provider.
            builder.RegisterWebApiFilterProvider(config);


            if (!WebSecurity.Initialized)
            {
                WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "Email", autoCreateTables: false);
            }

            FacebookConfig.Register(GlobalFacebookConfiguration.Configuration);

            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
        }
 public static IAppBuilder UseFacebookMessenger(this IAppBuilder appBuilder, FacebookConfig config, Func <IMessageActivity, Task> onActivityAsync)
 {
     return(appBuilder.UseFacebookMessenger(new[] { config }, onActivityAsync));
 }
Esempio n. 14
0
    protected void Page_Load(object sender, EventArgs e)
    {
        FacebookConfig fbConfig = new FacebookConfig()
        {
            appId = "160789593985275",
            apiSecret = "<secret>"
        };
        //for local debugging and custom persistent store - force domain - should allow cross-domain authentication using a single FB app
        //copy your authtoken from your published app in your local app.
        //        fbConfig.appDomain = "fbAsp.hylas.be";
        /*
        note: for quick and easy debugging on localhost:
        1. create facebook app for local debugging:
        - App Domains: localhost
        - Sandbox Mode: enabled (only admins can use app)
        - Website with Facebook Login: http://localhost:<VS debugger or IIS express port>/Example/
        2. it works! (after a minute or two...)
        3. but you should put appId & apiSecrit in your web.config, using a web.config transformation to switch between your debug & release application
        */
        fb = new Facebook(fbConfig);
        this.initPermissions();
        pnlPermissions.Visible = false;
        if (IsPostBack)
        {
            if (txtAccessToken.Text.Length > 0) fb.setAccessToken(txtAccessToken.Text);
            try
            {
                //fb.getUser should only fail when graph is unavailable or respons is corrupt
                user = fb.getUser();
            }
            catch (Exception ex)
            {
                iPanel.Visible = false;
                lblStatus.Text = "Error communicating with graph servers";
                fbURL.NavigateUrl = fb.getLoginUrl();
                ViewState["user"] = null;
                return;
            }
        }
        else
        {
            try
            {
                user = fb.getUser();
            }
            catch (Exception ex) {
                iPanel.Visible = false;
                lblStatus.Text = "Error communicating with graph servers";
                fbURL.NavigateUrl = fb.getLoginUrl();
                ViewState["user"] = null;
                return;
            }
            if (!string.IsNullOrEmpty(user))
            {
                try
                {
                    iPanel.Visible = true;
                    txtAccessToken.Text = fb.getAccessToken();
                    fbr = fb._graph("/me");
                    txtRequests.Text = "/me";
                    txtData.Text = fbr.ToString();
                    //txtUserObect.Text = fbr.ToString();
                    iPicture.ImageUrl = "https://graph.facebook.com/" + fbr["id"].ToString() + "/picture";
                    iProfile.Text = fbr["name"].ToString();// fbr["name"].value.ToString();
                    lblStatus.Text = "Connected";
                    btnConnect1.Text = "Disconnect";
                    btnConnect1.CssClass = "btnDisconnect";
                    fbr = fb._graph("/me/albums");
                    fbURL.NavigateUrl = fb.getLogoutUrl();
                    if (fbr.ContainsKey("data"))
                    {
                        for (var i = 0; i < fbr["data"].Count; i++)
                            AlbumList.Items.Add(new ListItem(fbr["data"][i.ToString()]["name"].ToString(), fbr["data"][i.ToString()]["id"].ToString()));
                        //or different way:
                        /*foreach (KeyValuePair<String, FacebookResponse> entry in fbr["data"])
                        {

                            AlbumList.Items.Add(new ListItem(entry.Value["name"].ToString()));
                        }*/
                    }
                    while (fbr.ContainsKey("paging") && fbr["paging"].ContainsKey("next"))
                    {
                        fbr = fb._graph(fbr["paging"]["next"].ToString());
                        if (fbr.ContainsKey("data"))
                            for (var i = 0; i < fbr["data"].Count; i++)
                                AlbumList.Items.Add(new ListItem(fbr["data"][i.ToString()]["name"].ToString(), fbr["data"][i.ToString()]["id"].ToString()));
                    }
                    Session.Remove("fb_connect_attempt") ;

                }
                catch (FacebookApiException ex)
                {
                    //todo: log error
                    //probably session expired: we still have the persistent data: user_id and access_token, but the token is no longer valid
                    //best is just to clear the session/cookie OR auto reconnect

                    txtAccessToken.Text = "";
                    iPanel.Visible = false;
                    user = null;
                    if (Session["fb_connect_attempt"] == null)
                    {
                        Session["fb_connect_attempt"] = 1;
                        connectToFB();
                    }
                }
            }
            else
            {
                iPanel.Visible = false;
                lblStatus.Text = "Not Connected";
                fbURL.NavigateUrl = fb.getLoginUrl();
                ViewState["user"] = null;
            }
        }
    }
 public DirectConnectorClientFactory(FacebookConfig config)
 {
     this.config = config;
 }
Esempio n. 16
0
 public FacebookClient(FacebookConfig facebookConfig)
     : this(facebookConfig.ClientId, facebookConfig.ClientSecret)
 {
     GraphApiVersion = facebookConfig.GraphApiVersion;
 }
Esempio n. 17
0
        public async Task PublishOrDeleteAsync(Post <string> post,
                                               PropertyChange[] changes)
        {
            var sites = await _sitesRepository.GetByIdsAsync(post.SiteIds);

            foreach (var site in sites)
            {
                if (site.Id == GetMainSiteId(post))
                {
                    var ipbSettings = await _propertiesProvider.GetAsync <IPBSitePropertiesSet>(site);

                    if (ipbSettings != null && ipbSettings.IsEnabled && ipbSettings.ForumId > 0)
                    {
                        await _ipbContentPublisher.PublishAsync(post,
                                                                new IPBPublishConfig(ipbSettings.ForumId, post.AuthorId), true, site,
                                                                true);
                    }
                }

                var twitterSettings = await _propertiesProvider.GetAsync <TwitterSitePropertiesSet>(site);

                if (twitterSettings != null && twitterSettings.IsEnabled)
                {
                    var hasChanges = changes != null && changes.Any(c =>
                                                                    c.Name == nameof(post.Title) || c.Name == nameof(post.Url));

                    var sections = await _sectionsRepository.GetByIdsAsync(post.SectionIds);

                    var tags = new List <string>();
                    foreach (var section in sections)
                    {
                        if (section is Developer developer && !string.IsNullOrEmpty(developer.Data.Hashtag))
                        {
                            tags.Add($"#{developer.Data.Hashtag.Replace("#", "")}");
                        }

                        if (section is Game game && !string.IsNullOrEmpty(game.Data.Hashtag))
                        {
                            tags.Add($"#{game.Data.Hashtag.Replace("#", "")}");
                        }

                        if (section is Topic topic && !string.IsNullOrEmpty(topic.Data.Hashtag))
                        {
                            tags.Add($"#{topic.Data.Hashtag.Replace("#", "")}");
                        }
                    }


                    var twitterConfig = new TwitterPublishConfig(
                        new TwitterConfig(twitterSettings.ConsumerKey, twitterSettings.ConsumerSecret,
                                          twitterSettings.AccessToken, twitterSettings.AccessTokenSecret), tags);

                    if (hasChanges || !post.IsPublished)
                    {
                        await _twitterContentPublisher.DeleteAsync(post, twitterConfig, site);
                    }

                    if (post.IsPublished)
                    {
                        await _twitterContentPublisher.PublishAsync(post, twitterConfig, hasChanges, site);
                    }
                }

                var facebookSettings = await _propertiesProvider.GetAsync <FacebookSitePropertiesSet>(site);

                if (facebookSettings != null && facebookSettings.IsEnabled)
                {
                    var hasChanges = changes != null && changes.Any(c => c.Name == nameof(post.Url));

                    var facebookConfig = new FacebookConfig(new Uri(facebookSettings.ApiUrl), facebookSettings.PageId,
                                                            facebookSettings.AccessToken);

                    if (hasChanges || !post.IsPublished)
                    {
                        await _facebookContentPublisher.DeleteAsync(post, facebookConfig, site);
                    }

                    if (post.IsPublished)
                    {
                        await _facebookContentPublisher.PublishAsync(post, facebookConfig, hasChanges, site);
                    }
                }
            }
        }