public AuthModule() { var provider = new Pusher(PusherApplicationID, PusherApplicationKey, PusherApplicationSecret); Post["/auth/{username}", (ctx) => ctx.Request.Form.channel_name && ctx.Request.Form.socket_id] = _ => { Console.WriteLine(String.Format("Processing auth request for '{0}' channel, for socket ID '{1}'", Request.Form.channel_name, Request.Form.socket_id)); string channel_name = Request.Form.channel_name; string socket_id = Request.Form.socket_id; string authData = null; if (channel_name.StartsWith("presence-")) { var channelData = new PresenceChannelData(); channelData.user_id = socket_id; channelData.user_info = new { name = _.username }; authData = provider.Authenticate(channel_name, socket_id, channelData).ToJson(); } else { authData = provider.Authenticate(channel_name, socket_id).ToJson(); } return authData; }; }
public async Task <IActionResult> Index() { ViewBag.Username = HttpContext.Session.GetString("username"); var visitors = 0; if (System.IO.File.Exists("visitors.txt")) { string noOfVisitors = System.IO.File.ReadAllText("visitors.txt"); visitors = Int32.Parse(noOfVisitors); } ++visitors; var visit_text = (visitors == 1) ? " view" : " views"; System.IO.File.WriteAllText("visitors.txt", visitors.ToString()); ViewData["visitors"] = visitors; ViewData["visitors_txt"] = visit_text; var options = new PusherOptions(); options.Cluster = "PUSHER_APP_CLUSTER"; var pusher = new Pusher( "PUSHER_APP_ID", "PUSHER_APP_KEY", "PUSHER_APP_SECRET", options); pusher.TriggerAsync( "general", "newVisit", new { visits = visitors.ToString(), message = visit_text }); return(View()); }
public async Task <ActionResult> NewChat([FromBody] ChatDto chatDto) { var chat = _chatRepository.SaveChat(chatDto); var options = new PusherOptions { Cluster = "ap1", Encrypted = true }; var pusher = new Pusher( "957914", "0a3b3bc361a655ea56ac", "1a2506af120a04af2906", options); var result = await pusher.TriggerAsync( chatDto.LectureId.ToString(), "my-event", new { userName = chatDto.UserName, message = chatDto.Message, dateTime = chat.DateTime }); return(Ok(result)); }
/// <summary> /// Create a Pusher Client, and subscribes a user /// </summary> /// <param name="pusherServer">Server to connect to</param> /// <param name="reset">The AutoReset to control the subscription by the client</param> /// <param name="channelName">The name of the channel to subscribe to</param> /// <returns>A subscribed client</returns> public static PusherClient.Pusher CreateClient(Pusher pusherServer, AutoResetEvent reset, string channelName) { PusherClient.Pusher pusherClient = new PusherClient.Pusher(Config.AppKey, new PusherClient.PusherOptions() { Authorizer = new InMemoryAuthorizer( pusherServer, new PresenceChannelData() { user_id = "Mr Pusher", user_info = new { twitter_id = "@pusher" } }) }); pusherClient.Connected += delegate { reset.Set(); }; pusherClient.Connect(); reset.WaitOne(TimeSpan.FromSeconds(5)); var channel = pusherClient.Subscribe(channelName); channel.Subscribed += delegate { reset.Set(); }; reset.WaitOne(TimeSpan.FromSeconds(5)); return pusherClient; }
public static void Start() { pusher = new Pusher(APP_ID, APP_KEY, APP_SECRET); new Timer(BroadcastStats, null, 500, 1500); cpuRandom = new Random(30); memoryRandom = new Random(6); }
internal virtual Replication ReplicationWithDatabase(Database db, Uri remote, bool push, bool create, bool start) { foreach (Replication replicator in replications) { if (replicator.GetLocalDatabase() == db && replicator.GetRemoteUrl().Equals(remote ) && replicator.IsPull() == !push) { return(replicator); } } if (!create) { return(null); } Replication replicator_1 = null; bool continuous = false; if (push) { replicator_1 = new Pusher(db, remote, continuous, GetWorkExecutor()); } else { replicator_1 = new Puller(db, remote, continuous, GetWorkExecutor()); } replications.AddItem(replicator_1); if (start) { replicator_1.Start(); } return(replicator_1); }
private async Task InitialisePusher() { //Environment.SetEnvironmentVariable("PREFER_DNS_IN_ADVANCE", "true"); if (_pusher == null && (APP_KEY != "APP_KEY") && (APP_CLUSTER != "APP_CLUSTER")) { _pusher = new Pusher(APP_KEY, new PusherOptions() { Cluster = APP_CLUSTER, Encrypted = true }); _pusher.Error += OnPusherOnError; _pusher.ConnectionStateChanged += PusherOnConnectionStateChanged; _pusher.Connected += PusherOnConnected; _channel = await _pusher.SubscribeAsync("my-channel"); _channel.Subscribed += OnChannelOnSubscribed; await _pusher.ConnectAsync(); } else { Debug.LogError("APP_KEY and APP_CLUSTER must be correctly set. Find how to set it at https://dashboard.pusher.com"); } }
public async Task <ActionResult> AddMessage([FromBody] AddMessage message) { var sd = message; var yup = _conversationService.addMessage(message.userIdSend, message.conversationId, message.message); if (yup == true) { var options = new PusherOptions { Cluster = "eu", Encrypted = true }; var pusher = new Pusher( "975390", "35935d17e4b0feaca33b", "157278f5b673fba840a3", options); await pusher.TriggerAsync( message.messageChannel, "my-chat-" + message.conversationId, new { message = message.message, userIdSend = message.userIdSend, userId = message.userId, conversationId = message.conversationId }); // await pusher.TriggerAsync( //"my-channel", //"my-event", //new { message = message.message, userIdSend = message.userIdSend, conversationId = message.conversationId }); return(Ok()); } return(Ok()); }
private static Channel SubscribeToChannel(Pusher pusher, string mockChannelName, AutoResetEvent subscribedEvent) { var channel = AsyncContext.Run(() => pusher.Subscribe(mockChannelName)); channel.Subscribed += sender => { subscribedEvent.Set(); }; return(channel); }
public async Task PushesAllChangesWithMultipleWorkers() { Configuration.MaxConcurrentBatches = 32; Changes["NuGet.Core"] = new string[0]; Changes["NuGet.Versioning"] = new string[0]; Changes["EntityFramework"] = new string[0]; Changes["Microsoft.Extensions.Logging"] = new string[0]; Changes["Microsoft.Extensions.DependencyInjection"] = new string[0]; await Target.ExecuteAsync(); Pusher.Verify( x => x.EnqueueIndexActions(It.IsAny <string>(), It.IsAny <IndexActions>()), Times.Exactly(5)); Pusher.Verify( x => x.EnqueueIndexActions("NuGet.Core", It.IsAny <IndexActions>()), Times.Once); Pusher.Verify( x => x.EnqueueIndexActions("NuGet.Versioning", It.IsAny <IndexActions>()), Times.Once); Pusher.Verify( x => x.EnqueueIndexActions("EntityFramework", It.IsAny <IndexActions>()), Times.Once); Pusher.Verify( x => x.EnqueueIndexActions("Microsoft.Extensions.Logging", It.IsAny <IndexActions>()), Times.Once); Pusher.Verify( x => x.EnqueueIndexActions("Microsoft.Extensions.DependencyInjection", It.IsAny <IndexActions>()), Times.Once); Pusher.Verify(x => x.PushFullBatchesAsync(), Times.Exactly(5)); Pusher.Verify(x => x.FinishAsync(), Times.Exactly(32)); }
// GET: api/Pusher/rejectAlert public IHttpActionResult GetPusher(string id) { var pusher = new Pusher("112258", "0a062137e6bd1304c414", "27c853b5d9494a1c8c2b"); var result = pusher.Trigger("test_channel", "my_event", new { message = id }); return(Ok()); }
public async Task <ActionResult> HelloWorld() { var options = new PusherOptions { Cluster = "ap1", Encrypted = true }; ModelTest mdl = new ModelTest(); List <ModelTest> result2 = new List <ModelTest>(); mdl.Mcadress = "1234"; mdl.DeviceID = "DEV001"; mdl.value = 2; result2.Add(mdl); var pusher = new Pusher( "1099541", "4d57b796a305ad74611d", "1033ace6b885d1937090", options); var result = await pusher.TriggerAsync( "Dashboard-device", "my-event", new { message = result2 }); return(new HttpStatusCodeResult((int)HttpStatusCode.OK)); }
// Pusher Initiation / Connection private static void InitPusher() { _pusher = new Pusher(Config.AppKey, new PusherOptions { Authorizer = new HttpAuthorizer("http://localhost:8888/auth/" + HttpUtility.UrlEncode(_name)) }); _pusher.ConnectionStateChanged += _pusher_ConnectionStateChanged; _pusher.Error += _pusher_Error; // Setup private channel _chatChannel = _pusher.Subscribe("private-channel"); _chatChannel.Subscribed += ChatChannel_Subscribed; // Inline binding! _chatChannel.Bind("client-my-event", (dynamic data) => { Console.WriteLine("[" + data.name + "] " + data.message); }); // Setup presence channel _presenceChannel = (PresenceChannel)_pusher.Subscribe("presence-channel"); _presenceChannel.Subscribed += PresenceChannel_Subscribed; _presenceChannel.MemberAdded += PresenceChannel_MemberAdded; _presenceChannel.MemberRemoved += PresenceChannel_MemberRemoved; _pusher.Connect(); }
public async Task <IActionResult> CreateAsync([FromBody] MessageViewModel message) { //messages breaking here Message newMessage = new Message { SentBy = _userManager.GetUserName(User), Messages = message.message, GroupId = message.GroupId }; _context.Message.Add(newMessage); _context.SaveChanges(); var options = new PusherOptions { Cluster = "us3", Encrypted = true }; var pusher = new Pusher( "1088226", "a8e8c58dc5d53b967a82", "a320be2396ef5924f1ed", options ); var result = await pusher.TriggerAsync( "private-" + message.GroupId, "new_message", new { newMessage }, new TriggerOptions() { SocketId = message.SocketId }); return(new ObjectResult(new { status = "success", data = newMessage })); }
public async Task It_should_fail_for_an_event_data_size_greater_than_10KB_async() { IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() { HostName = Config.HttpHost, BatchEventDataSizeLimit = PusherOptions.DEFAULT_BATCH_EVENT_DATA_SIZE_LIMIT, }); List <Event> events = DataHelper.CreateEvents(numberOfEvents: 9, eventSizeInBytes: 84); int size = PusherOptions.DEFAULT_BATCH_EVENT_DATA_SIZE_LIMIT + 1; List <Event> largeEvent = DataHelper.CreateEvents(numberOfEvents: 1, eventSizeInBytes: size); events.AddRange(largeEvent); try { await pusher.TriggerAsync(events.ToArray()); } catch (EventDataSizeExceededException e) { Assert.AreEqual("testChannel", e.ChannelName, nameof(e.ChannelName)); Assert.AreEqual("testEvent", e.EventName, nameof(e.EventName)); throw; } }
public async Task TriggerClientEventAsync() { #region Code snippet // Create client Pusher pusher = new Pusher(Config.AppKey, new PusherOptions { Authorizer = new FakeAuthoriser(), Cluster = Config.Cluster, }); pusher.Error += ErrorHandler; // Connect await pusher.ConnectAsync().ConfigureAwait(false); // Subscribe Channel channel = await pusher.SubscribeAsync("private-chat-channel-1").ConfigureAwait(false); // Trigger event channel.Trigger("client-chat-event", new ChatMessage { Name = "Joe", Message = "Hello from Joe!", }); #endregion Code snippet await pusher.DisconnectAsync().ConfigureAwait(false); }
public JsonResult AuthForChannel(string channel_name, string socket_id) { if (Session["user"] == null) { return(Json(new { status = "error", message = "User is not logged in" })); } var currentUser = (Models.User)Session["user"]; var channelData = new PresenceChannelData() { user_id = currentUser.id.ToString(), user_info = new { id = currentUser.id, name = currentUser.name }, }; var options = new PusherOptions(); options.Cluster = "PUSHER_APP_CLUSTER"; var pusher = new Pusher( "PUSHER_APP_ID", "PUSHER_APP_KEY", "PUSHER_APP_SECRET", options); var auth = pusher.Authenticate(channel_name, socket_id, channelData); return(Json(auth)); }
public async Task ConnectThenSubscribePrivateChannelAsync() { #region Code snippet // Create client Pusher pusher = new Pusher(Config.AppKey, new PusherOptions { Authorizer = new FakeAuthoriser(), Cluster = Config.Cluster, }); pusher.Error += ErrorHandler; // Connect await pusher.ConnectAsync().ConfigureAwait(false); try { // Subscribe Channel channel = await pusher.SubscribeAsync("private-chat-channel-1").ConfigureAwait(false); Assert.AreEqual(true, channel.IsSubscribed); } catch (ChannelUnauthorizedException) { // Handle client unauthorized error } catch (Exception) { // Handle other errors } #endregion Code snippet await pusher.DisconnectAsync().ConfigureAwait(false); }
public async Task BindToGlobalEventAsync() { #region Code snippet // Create client Pusher pusher = new Pusher(Config.AppKey, new PusherOptions { Authorizer = new FakeAuthoriser(), Cluster = Config.Cluster, }); pusher.Error += ErrorHandler; // Global event listener void GlobalListener(string eventName, PusherEvent eventData) { if (eventName == "client-chat-event") { ChatMessage data = JsonConvert.DeserializeObject <ChatMessage>(eventData.Data); Trace.TraceInformation($"Message from '{data.Name}': {data.Message}"); } } // Bind global event listener pusher.BindAll(GlobalListener); // Unbind global event listener pusher.Unbind(GlobalListener); // Unbind all event listeners associated with the Pusher client pusher.UnbindAll(); #endregion Code snippet await pusher.DisconnectAsync().ConfigureAwait(false); }
public async Task ConnectThenSubscribePublicChannelAsync() { #region Code snippet // Create client Pusher pusher = new Pusher(Config.AppKey, new PusherOptions { Cluster = Config.Cluster, }); pusher.Error += ErrorHandler; // Connect await pusher.ConnectAsync().ConfigureAwait(false); // Subscribe try { Channel channel = await pusher.SubscribeAsync("public-channel-1").ConfigureAwait(false); Assert.AreEqual(true, channel.IsSubscribed); } catch (Exception) { // Handle error } #endregion Code snippet await pusher.DisconnectAsync().ConfigureAwait(false); }
public async Task ConnectedAndDisconnectedDelegatesAsync() { Pusher pusher = new Pusher(Config.AppKey, new PusherOptions { Cluster = Config.Cluster, Encrypted = true, }); void OnConnected(object sender) { Console.WriteLine("Connected: " + ((Pusher)sender).SocketID); } void OnDisconnected(object sender) { Console.WriteLine("Disconnected: " + ((Pusher)sender).SocketID); } pusher.Connected += OnConnected; pusher.Disconnected += OnDisconnected; await pusher.ConnectAsync().ConfigureAwait(false); await pusher.DisconnectAsync().ConfigureAwait(false); }
public IActionResult Create([FromBody] MessageViewModel message) { Message new_message = new Message { AddedBy = _userManager.GetUserName(User), message = message.message, GroupId = message.GroupId }; _context.Messages.Add(new_message); _context.SaveChanges(); var options = new PusherOptions { Cluster = _configuration["PUSHER_APP_CLUSTER"], Encrypted = true }; var pusher = new Pusher( _configuration["PUSHER_APP_ID"], _configuration["PUSHER_APP_KEY"], _configuration["PUSHER_APP_SECRET"], options ); var result = pusher.TriggerAsync( "private-" + message.GroupId, "new_message", new { new_message }, new TriggerOptions() { SocketId = message.SocketId }); return(new ObjectResult(new { status = "success", data = new_message })); }
public async void It_should_return_a_200_response_async() { IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() { HostName = Config.HttpHost }); var events = new Event[] { new Event { Channel = "my-channel-1", EventName = "my_event", Data = new { hello = "world" } }, new Event { Channel = "my-channel-2", EventName = "my_other_event", Data = new { hello = "other worlds" } }, }; var result = await pusher.TriggerAsync(events); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); }
public async Task <IActionResult> CreateAsync([FromBody] MessageViewModel message) { Message new_message = new Message { AddedBy = _userManager.GetUserName(User), message = message.message, GroupId = message.GroupId }; _context.Message.Add(new_message); _context.SaveChanges(); var options = new PusherOptions { Cluster = "us2", Encrypted = true }; var pusher = new Pusher( "620160", "87c7848afc7bbeaf081c", "7e6906f867f9e88df0d2", options ); var result = await pusher.TriggerAsync( "private-" + message.GroupId, "new_message", new { new_message }, new TriggerOptions() { SocketId = message.SocketId }); return(new ObjectResult(new { status = "success", data = new_message })); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Main); var infoTb = FindViewById <EditText>(Resource.Id.infoTb); pusher = new Pusher("dc777df44df8be24ae85", new Handler(Looper.MainLooper)); pusher.ConnectAsync(15000, ConnectionTimeoutAction.CloseConnection, 20000, NetworkUnavailableAction.Ignore); pusher.Connected += (sender) => { RunOnUiThread(() => { infoTb.AppendLine("Connected!"); channel = pusher.Subscribe("my-channel"); channel.Bind("my-event", (obj) => { var car = Pusher.ParseMessageToObject(obj.message.Value as string, new Car()); infoTb.AppendLine($"{car.Name}, {car.Color}, {car.Make}"); }); }); }; pusher.ConnectionStateChanged += (s, state) => { switch (state) { case ConnectionState.Disconnected: channel.Unbind("my-event"); break; } }; }
public void SetupTaskManager() { var taskManager = Pusher.SetupTaskManager("release"); Assert.NotNull(taskManager); Assert.AreEqual(5, taskManager.TaskContext.Data.Count); Assert.Contains("WorkingDirectory", (ICollection)taskManager.TaskContext.Data.Keys); Assert.Contains("CurrentVersionFileRelativePath", (ICollection)taskManager.TaskContext.Data.Keys); Assert.Contains("CurrentReleaseVersionFileRelativePath", (ICollection)taskManager.TaskContext.Data.Keys); Assert.Contains("CurrentTestVersionFileRelativePath", (ICollection)taskManager.TaskContext.Data.Keys); Assert.Contains("Mode", (ICollection)taskManager.TaskContext.Data.Keys); Assert.False(string.IsNullOrWhiteSpace(taskManager.TaskContext.Data["WorkingDirectory"] as string)); Assert.False(string.IsNullOrWhiteSpace(taskManager.TaskContext.Data["CurrentVersionFileRelativePath"] as string)); Assert.False(string.IsNullOrWhiteSpace(taskManager.TaskContext.Data["CurrentReleaseVersionFileRelativePath"] as string)); Assert.False(string.IsNullOrWhiteSpace(taskManager.TaskContext.Data["CurrentTestVersionFileRelativePath"] as string)); Assert.False(string.IsNullOrWhiteSpace(taskManager.TaskContext.Data["Mode"] as string)); Assert.AreEqual(5, taskManager.Tasks.Count); Assert.True(taskManager.Tasks.OfType <GetVersion>().Any()); Assert.True(taskManager.Tasks.OfType <IncrementVersionNumberTask>().Any()); Assert.True(taskManager.Tasks.OfType <IncrementVersionNumbersInFiles>().Any()); Assert.True(taskManager.Tasks.OfType <CreatePushBatFile>().Any()); Assert.True(taskManager.Tasks.OfType <AddRecentChanges>().Any()); }
public AuthModule() { var provider = new Pusher(PusherApplicationID, PusherApplicationKey, PusherApplicationSecret); Post["/auth/{username}", (ctx) => ctx.Request.Form.channel_name && ctx.Request.Form.socket_id] = _ => { Console.WriteLine(String.Format("Processing auth request for '{0}' channel, for socket ID '{1}'", Request.Form.channel_name, Request.Form.socket_id)); string channel_name = Request.Form.channel_name; string socket_id = Request.Form.socket_id; string authData = null; if (channel_name.StartsWith("presence-")) { var channelData = new PresenceChannelData(); channelData.user_id = socket_id; channelData.user_info = new { name = _.username }; authData = provider.Authenticate(channel_name, socket_id, channelData).ToJson(); } else { authData = provider.Authenticate(channel_name, socket_id).ToJson(); } return(authData); }; }
public async Task UpdatesBlobStorageAfterIndexing() { var actions = new List <string>(); Pusher .Setup(x => x.FinishAsync()) .Returns(Task.CompletedTask) .Callback(() => actions.Add(nameof(IBatchPusher.FinishAsync))); OwnerDataClient .Setup(x => x.UploadChangeHistoryAsync(It.IsAny <IReadOnlyList <string> >())) .Returns(Task.CompletedTask) .Callback(() => actions.Add(nameof(IOwnerDataClient.UploadChangeHistoryAsync))); OwnerDataClient .Setup(x => x.ReplaceLatestIndexedAsync(It.IsAny <SortedDictionary <string, SortedSet <string> > >(), It.IsAny <IAccessCondition>())) .Returns(Task.CompletedTask) .Callback(() => actions.Add(nameof(IOwnerDataClient.ReplaceLatestIndexedAsync))); Changes["NuGet.Core"] = new string[0]; await Target.ExecuteAsync(); Assert.Equal( new[] { nameof(IBatchPusher.FinishAsync), nameof(IOwnerDataClient.UploadChangeHistoryAsync), nameof(IOwnerDataClient.ReplaceLatestIndexedAsync) }, actions.ToArray()); }
public JsonResult Send(string message) { Pusher pusher = new Pusher(APP_ID, APP_KEY, APP_SECRET); var result = pusher.Trigger("notifications_channel", "new_event", new { message = message }); return Json(new { message = "Sent the notification." }, JsonRequestBehavior.AllowGet); }
public async Task DisposeAsync() { await PusherFactory.DisposePushersAsync(_clients).ConfigureAwait(false); _client = null; _error = null; }
public async Task <IActionResult> Chat(string id, bool id2 = false) { var options = new PusherOptions { Encrypted = true, Cluster = Globals.PusherCluster }; var pusher = new Pusher(Globals.PusherAppId, Globals.PusherKey, Globals.PusherSecret, options); if (id2) { var data = new { username = id, message = NoteDataManager.GetSafeUserDisplayName(_userManager, User, _db) + " wants to chat with you." }; await pusher.TriggerAsync("presence-channel", "chat_request_event", data); } else { var data = new { username = NoteDataManager.GetSafeUserDisplayName(_userManager, User, _db), message = "<<HAS ARRIVED TO CHAT>>" }; await pusher.TriggerAsync("private-notes-chat-" + id, "show_chat_message_event", data); } ViewData["ChatFrom"] = NoteDataManager.GetSafeUserDisplayName(_userManager, User, _db); // me ViewData["ChatTo"] = id; // chat target return(View()); }
private void ProcessEvent(WebhookPushEvent _event) { Pusher pusher = _event.Pusher; string name = pusher.Name; Log("Webhook received: New Push from " + name); string commitSha = _event.HeadCommit; GithubCommit commit = FetchCommit(commitSha); if (commit == null) { return; } GithubWebhookService.Models.File[] changedFiles = commit.Files; foreach (GithubWebhookService.Models.File changedFile in changedFiles) { string filename = changedFile.Filename; if (filename.Contains("surveyQuestionService.json")) { Log("Changes to Consul-Configuration have been detected!"); Console.WriteLine("Changes to Consul-Configuration have been detected!"); } } }
public JsonResult AuthForChannel(string channel_name, string socket_id) { var currentUser = db.UsuariosAsps.Where(u => u.UserName == User.Identity.Name) .ToList()[0]; var options = new PusherOptions(); options.Cluster = "us2"; var pusher = new Pusher( "530632", "ed5c2354a385822ffe87", "0314372fa7f33ce2837a", options); if (channel_name.IndexOf(currentUser.Id.ToString()) == -1) { return(Json( new { status = "error", message = "User cannot join channel" } )); } var auth = pusher.Authenticate(channel_name, socket_id); return(Json(auth)); }
private void HandleNewTransactions(IEnumerable <Transaction> transactions) { var recipients = transactions.GroupBy(t => t.RecipientId); var devicesToNotify = new Dictionary <Device, IEnumerable <Transaction> >(); foreach (var recipient in recipients) { var address = recipient.Key; if (string.IsNullOrWhiteSpace(address)) { continue; } var registeredDevices = Context.Devices.Where(d => d.Address.Equals(recipient.Key)); // TODO: Проверять на дубликаты, добавлять транзакции в имеющиеся коллекции if (registeredDevices != null && registeredDevices.Any()) { foreach (var device in registeredDevices) { devicesToNotify.Add(device, recipient.AsEnumerable()); } } } foreach (var device in devicesToNotify) { var task = new Task(() => Pusher.NotifyDevice(device.Key, device.Value)); task.Start(); } }
public void CanTriggerEventWithPercentInMessage() { var eventJSON = File.ReadAllText("AcceptanceTests/percent-message.json"); var message = new JavaScriptSerializer().Deserialize(eventJSON, typeof(object)); IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret); ITriggerResult result = pusher.Trigger("my-channel", "my_event", message); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); }
public async void It_should_be_possible_to_deserialize_the_a_channels_result_body_as_an_ChannelsList() { IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() { HostName = Config.HttpHost }); IGetResult<ChannelsList> result = await pusher.GetAsync<ChannelsList>("/channels"); Assert.IsTrue(result.Data.Channels.Count >= 0); }
public async void It_should_return_a_200_response() { IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() { HostName = Config.HttpHost }); IGetResult<object> result = await pusher.GetAsync<object>("/channels"); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); }
public async void It_should_be_possible_to_deserialize_the_request_result_body_as_an_object() { IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() { HostName = Config.HttpHost }); IGetResult<object> result = await pusher.GetAsync<object>("/channels"); Assert.NotNull(result.Data); }
public ActionResult Auth(string channel_name, string socket_id) { Debug.WriteLine("trying to auth"); var pusher = new Pusher("72484", "e9473350e86cf2fd89ac", "3e1cbae89445267f362f"); var channelData = new PresenceChannelData(); channelData.user_id = (string) Session["FBID"]; channelData.user_info = new { facebook_id = (string) Session["FBID"] }; var auth = pusher.Authenticate( channel_name, socket_id, channelData ); var json = auth.ToJson(); return new ContentResult { Content = json, ContentType = "application/json" }; }
public void the_authentication_token_for_a_presence_channel_should_be_accepted_by_Pusher() { PusherServer.Pusher pusherServer = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() { HostName = Config.HttpHost }); PusherClient.Pusher pusherClient = new PusherClient.Pusher(Config.AppKey, new PusherClient.PusherOptions() { Authorizer = new InMemoryAuthorizer( pusherServer, new PresenceChannelData() { user_id = "leggetter", user_info = new { twitter_id = "@leggetter" } }) }); pusherClient.Host = Config.WebSocketHost; string channelName = "presence-channel"; bool subscribed = false; AutoResetEvent reset = new AutoResetEvent(false); pusherClient.Connected += new PusherClient.ConnectedEventHandler(delegate(object sender) { Debug.WriteLine("connected"); reset.Set(); }); Debug.WriteLine("connecting"); pusherClient.Connect(); Debug.WriteLine("waiting to connect"); reset.WaitOne(TimeSpan.FromSeconds(10)); Debug.WriteLine("subscribing"); var channel = pusherClient.Subscribe(channelName); channel.Subscribed += new PusherClient.SubscriptionEventHandler(delegate(object s) { Debug.WriteLine("subscribed"); subscribed = true; reset.Set(); }); Debug.WriteLine("waiting to subscribe"); reset.WaitOne(TimeSpan.FromSeconds(5)); Assert.IsTrue(subscribed); }
public void It_should_be_received_by_a_client() { string channelName = "my_channel"; string eventName = "my_event"; bool eventReceived = false; AutoResetEvent reset = new AutoResetEvent(false); var client = new PusherClient.Pusher(Config.AppKey); client.Connected += new PusherClient.ConnectedEventHandler(delegate(object sender) { Debug.WriteLine("connected"); reset.Set(); }); Debug.WriteLine("connecting"); client.Connect(); Debug.WriteLine("waiting to connect"); reset.WaitOne(TimeSpan.FromSeconds(5)); Debug.WriteLine("subscribing"); var channel = client.Subscribe(channelName); channel.Subscribed += new PusherClient.SubscriptionEventHandler(delegate(object s) { Debug.WriteLine("subscribed"); reset.Set(); }); Debug.WriteLine("binding"); channel.Bind(eventName, delegate(dynamic data) { Debug.WriteLine("event received"); eventReceived = true; reset.Set(); }); Debug.WriteLine("waiting to subscribe"); reset.WaitOne(TimeSpan.FromSeconds(5)); Debug.WriteLine("triggering"); IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret); ITriggerResult result = pusher.Trigger(channelName, eventName, new { hello = "world" }); Debug.WriteLine("waiting for event to be received"); reset.WaitOne(TimeSpan.FromSeconds(5)); Assert.IsTrue(eventReceived); }
public MoveMarkerToVertexGoal(Pusher inMe, int turn) : base(inMe,turn) { me = inMe; //IO.ErrorWrite("MoveMarkerToVertexGoal P#" + me.num.ToString()); // Find a marker to move myMarker = Map.mList[GoalUtility.FindNearest(me.pos, Map.RED)]; myMarker.beingUsedBy = this; //IO.ErrorWrite(myMarker.Short()); // Find a place to push it. targetVertextSeq = GoalUtility.PickAVertex(myMarker.pos); targetVertex = Map.vertexList[targetVertextSeq]; //IO.ErrorWrite(targetVertex.Short2D()); targetVertex.target = true; // we should fix this make me the user. dest = new Vector2D(targetVertex.x, targetVertex.y); //IO.ErrorWriteLine(""); }
public ActionResult SendMessage(string message, string username) { var chatMessage = new ChatMessage() { ChatMsgId = Guid.NewGuid(), ChatMsgText = message, Author = username, TimeStamp = DateTime.Now }; chatService.SaveChatMessage(chatMessage); var pusher = new Pusher( WebConfigurationManager.AppSettings["PusherAppId"], WebConfigurationManager.AppSettings["PusherAppKey"], WebConfigurationManager.AppSettings["PusherAppSecret"]); var result = pusher.Trigger("chat_channel", "chat_event", new { message, username, chatMsgId = chatMessage.ChatMsgId }); return new EmptyResult(); }
public void the_authentication_token_for_a_private_channel_should_be_accepted_by_Pusher() { PusherServer.Pusher pusherServer = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret); PusherClient.Pusher pusherClient = new PusherClient.Pusher(Config.AppKey, new PusherClient.PusherOptions() { Authorizer = new InMemoryAuthorizer(pusherServer) }); string channelName = "private-channel"; bool subscribed = false; AutoResetEvent reset = new AutoResetEvent(false); pusherClient.Connected += new PusherClient.ConnectedEventHandler(delegate(object sender) { Debug.WriteLine("connected"); reset.Set(); }); Debug.WriteLine("connecting"); pusherClient.Connect(); Debug.WriteLine("waiting to connect"); reset.WaitOne(TimeSpan.FromSeconds(5)); Debug.WriteLine("subscribing"); var channel = pusherClient.Subscribe(channelName); channel.Subscribed += new PusherClient.SubscriptionEventHandler(delegate(object s) { Debug.WriteLine("subscribed"); subscribed = true; reset.Set(); }); Debug.WriteLine("waiting to subscribe"); reset.WaitOne(TimeSpan.FromSeconds(5)); Assert.IsTrue(subscribed); }
public BasePlan(Pusher p) { myP = p; state = "Initial"; }
public void It_should_return_a_202_response() { IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret); ITriggerResult result = pusher.Trigger("my-channel", "my_event", new { hello = "world" }); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); }
public async void It_should_return_a_200_response_async() { IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() { HostName = Config.HttpHost }); ITriggerResult asyncResult = await pusher.TriggerAsync(new string[] {"my-channel-1", "my-channel-2"}, "my_event", new {hello = "world"}); Assert.AreEqual(HttpStatusCode.OK, asyncResult.StatusCode); }
public PrivateChannel(string channelName, Pusher pusher) : base(channelName, pusher) { }
/* Print out a force vector that will move the given pusher to the given target location. */ public static void MoveTo(Pusher p, Vector2D target) { // Compute a frame with axis a1 pointing at the target. Vector2D a1, a2; // Build a frame (a trivial one if we're already too close). double dist = target.Distance(p.pos); if (dist < 0.0001) { a1 = new Vector2D(1.0, 0.0); a2 = new Vector2D(0.0, 1.0); } else { a1 = (target - p.pos) * (1.0 / dist); a2 = a1.Perp(); } // Represent the pusher velocity WRT that frame. double v1 = a1 * p.vel; double v2 = a2 * p.vel; // Compute a force vector in this frame, first cancel out velocity // perp to the target. double f1 = 0; double f2 = -v2; // If we have remaining force to spend, use it to move toward the target. if (Math.Abs(f2) < PUSHER_ACCEL_LIMIT) { double raccel = Math.Sqrt(PUSHER_ACCEL_LIMIT * PUSHER_ACCEL_LIMIT - v2 * v2); f1 = GoalUtility.MoveTo(-dist, v1, 0.0, raccel); } // Convert force Vector2D force = a1 * f1 + a2 * f2; p.MoveThisTurn = force.x + " " + force.y; }
public ActionResult SendMessage(String message, String username) { Debug.WriteLine(username); var pusher = new Pusher("72484", "e9473350e86cf2fd89ac", "3e1cbae89445267f362f"); IGetResult<object> result = pusher.Get<object>("/channels/presence-channel/users"); PusherUsers users = new JavaScriptSerializer().Deserialize<PusherUsers>(result.Body); pusher.Trigger("presence-channel", "my_event", new { message = message, user = Session["FBID"], username = username }); // Database logging using (ChatContext db = new ChatContext()) { // Insert chat message row ChatMessage c = new ChatMessage { FBID = (String)Session["FBID"], Message = message, UserName = username, TimeSent = DateTime.Now }; db.ChatMessages.Add(c); db.SaveChanges(); // SaveChanges() is called to get a ChatMessageID value from the DB. // Insert user-to-chat rows for all connected users foreach(PusherUser user in users.users){ UserToChatMessage u = new UserToChatMessage { FBID = user.id.ToString(), ChatMessageID = c.ChatMessageID }; db.UserToChatMessages.Add(u); } db.SaveChanges(); } return new HttpStatusCodeResult((int)HttpStatusCode.OK); }
void pusher_EventEmitted(object sender, Pusher.IIncomingEvent e) { System.Diagnostics.Debug.WriteLine(e.Data); }
public async void It_should_return_a_200_response_async() { IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() { HostName = Config.HttpHost }); var events = new Event[] { new Event { Channel = "my-channel-1", EventName = "my_event", Data = new {hello = "world"} }, new Event { Channel = "my-channel-2", EventName = "my_other_event", Data = new {hello = "other worlds"} }, }; var result = await pusher.TriggerAsync(events); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); }
/* Print out a force vector that will move the given pusher around to the side of marker m that's opposite from target. Return true if we're alreay behind the marker. */ public static bool MoveAround(Pusher p, Marker m, Vector2D target) { // Compute vectors pointing from marker-to-target and Marker-to-pusher Vector2D mToT = (target - m.pos).Norm(); Vector2D mToP = (p.pos - m.pos).Norm(); // See if we're already close to behind the marker. if (mToT * mToP < -0.8) return true; // Figure out how far around the target we need to go, we're // going to move around a little bit at a time so we don't hit // the target. double moveAngle = Math.PI - Math.Acos(mToT * mToP); if (moveAngle > Math.PI * 0.25) moveAngle = Math.PI * 0.25; // We're not, decide which way to go around. if (mToT.Cross(mToP) > 0) { // Try to go around to the right. MoveTo(p, m.pos + mToP.Rotate(moveAngle) * 4.0); } else { // Try to go around to the left. MoveTo(p, m.pos + mToP.Rotate(-moveAngle) * 4.0); } return false; }
public SwitchingPlan2(Pusher me) : base(me) { }
private void OnPusherEnter(Pusher pusher) { Vector3 force = pusher.GetPushForce(this); pusher.PunchTowards(transform.position); SoundManager.Instance.PlayPushedEffect(); _move.Push(force); }
public TurnGreyMarkerRedGoal(Pusher inMe, int turn) : base(inMe, turn) { me = inMe; // Find a marker to move int tmp = GoalUtility.FindNearest(me.pos, Map.GREY); if (tmp == -1) tmp = GoalUtility.FindNearest(me.pos, Map.BLUE); if (tmp == -1) donefor = true; else { myMarker = Map.mList[tmp]; myMarker.beingUsedBy = this; } }
public BaseGoal(Pusher me,int turn) { startTime = turn; startLoc = me.pos; }
public TurnGreyMarkerRedGoal2(Pusher inMe, int turn) : base(inMe, turn) { me = inMe; // Find a marker to move int tmp = GoalUtility.FindNearest(me.pos, Map.GREY); if (tmp == -1) tmp = GoalUtility.FindNearest(me.pos, Map.BLUE); if (tmp == -1) { donefor = true; return; } else { myMarker = Map.mList[tmp]; myMarker.beingUsedBy = this; } double goalDistance = myMarker.pos.Distance(dest); // find nearest area to move to -- for now lets do a brute force search for the closest that returns red. for (int regionNumber = 1; regionNumber < Map.regionList.Length; regionNumber++) { Region r = Map.regionList[regionNumber]; if ((r.redCount > r.blueCount) && (r.redCount > r.greyCount)) { Point2D loc = r.midPoint; double d = myMarker.pos.Distance(loc); if (d < goalDistance) { goalDistance = d; dest = loc; destRegion = regionNumber; } } } }
private void PushEventToUserInterface(string eventId) { var pusher = new Pusher(PusherCredentials.AppId, PusherCredentials.AppKey, PusherCredentials.AppSecret); var result = pusher.Trigger("collapse", eventId, null); }
private void Stream_FilteredStreamExample(string trackersKeywords, PusherConfig pusherConfig) { var trackersKeywordsList = trackersKeywords.Split(COMMA, StringSplitOptions.RemoveEmptyEntries).ToList(); for (; ; ) { try { var stream = Stream.CreateFilteredStream(); foreach (var trackersKeyword in trackersKeywordsList) stream.AddTrack(trackersKeyword); var tweetCount = 0; var timer = Stopwatch.StartNew(); // Generate credentials that we want to use Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("\tTweet to {0}", string.Join(",", trackersKeywordsList.ToArray())); stream.MatchingTweetReceived += (sender, args) => { tweetCount++; var tweet = args.Tweet; // Push to Dashboard. if (timer.ElapsedMilliseconds > 1000) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\n{0}: {1} {2}", tweet.Id, tweet.Language.ToString(), tweet.Text); Console.ForegroundColor = ConsoleColor.White; if (tweet.Coordinates != null) Console.WriteLine("\tLocation: {0}, {1}", tweet.Coordinates.Longitude, tweet.Coordinates.Latitude); timer.Restart(); Console.WriteLine("\tTweets/sec: {0}", tweetCount); tweetCount = 0; Console.WriteLine("\tPushing to Dashboard..."); var pusher = new Pusher(pusherConfig.AppId, pusherConfig.AppKey, pusherConfig.AppSecret, new PusherOptions() { Encrypted = true }); var result = pusher.Trigger(pusherConfig.Channel, pusherConfig.Event, tweet); } }; stream.StartStreamMatchingAllConditions(); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Exception: {0}", ex.Message); } } }