• Stars
    star
    109
  • Rank 319,077 (Top 7 %)
  • Language
    C#
  • License
    MIT License
  • Created over 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

.NET library for interacting with the Pusher HTTP API

Pusher Channels .NET HTTP API library

NuGet Badge Build

This is a .NET library for interacting with the Pusher Channels HTTP API.

Registering at http://pusher.com/channels and use the application credentials within your app as shown below.

Comprehensive documentation can be found at http://pusher.com/docs/channels.

Supported platforms

  • .NET Standard 1.3
  • .NET Standard 2.0
  • .NET 4.5
  • .NET 4.7.2
  • Unity 2018.1

Note: from release 4.4.0 PusherServer.Core.dll has been removed. Applications should reference PusherServer.dll instead.

Contents

Installation

The compiled library is available on NuGet:

Install-Package PusherServer

Getting started

The minimum configuration required to use the Pusher object are the three constructor arguments which identify your Pusher app - app id, app key and app secret. You can find them by going to "App Keys" on your app at https://dashboard.pusher.com/apps. If your app is not in the default cluster "mt1", you can specify it via the PusherOptions object.

var options = new PusherOptions
{
    Cluster = APP_CLUSTER,
    Encrypted = true,
};

var pusher = new Pusher(APP_ID, APP_KEY, APP_SECRET, options);

For best practise, you should create a Pusher singleton and reuse it.

Please Note: the Cluster option is overridden by HostName option. So, if HostName is set then Cluster will be ignored.

Configuration

In addition to the three app identifiers - app id, app key and app secret needed when constructing a Pusher object; you can specify other options via the PusherOptions object:

Property Type Description
Cluster String The Pusher app cluster name; for example, "eu". The default value is "mt1". This value will be overridden by HostName.
HostName String The Pusher app host name excluding the scheme; for example, "api.pusherapp.com". Overrides Cluster if specified.
Encrypted Boolean Indicates whether calls to the Pusher REST API are over HTTP or HTTPS. The default value is false - communication over HTTP.
Port Integer The REST API port that the HTTP calls will be made to. If Encrypted is true, will default to port 443. If Encrypted is false, will default to port 80.
BatchEventDataSizeLimit Nullable Integer Optional size limit for the Data property of a triggered event. If specified, the size check is done client side before submitting the event to the server. The size limit is normally 10KB but SDK customers can request a larger limit.
EncryptionMasterKey Byte Array Optional 32 byte encryption key required for end-to-end encryption of private channels.
RestClientTimeout TimeSpan The Pusher REST API timeout. The default timeout is 30 seconds.
TraceLogger ITraceLogger Used for tracing diagnostic events. Should not be set in production code.

Triggering events

To trigger an event on one or more channels use the TriggerAsync function.

Single channel

ITriggerResult result = await pusher.TriggerAsync("channel-1", "test_event", new
{
    message = "hello world"
}).ConfigureAwait(false);

Multiple channels

ITriggerResult result = await pusher.TriggerAsync(
    new string[] 
    { 
        "channel-1", "channel-2"
    },
    "test_event",
    new
    {
        message = "hello world"
    }).ConfigureAwait(false);

Batches

var events = new[]
{
    new Event {Channel = "channel-1", EventName = "event-1", Data = "hello world"},
    new Event {Channel = "channel-2", EventName = "event-2", Data = "my name is bob"}
};

ITriggerResult result = await pusher.TriggerAsync(events).ConfigureAwait(false);

Detecting event data that exceeds the 10KB threshold

Rather than relying on the server to validate message size you can now perform this client side before submitting a trigger event. Here is an example on how to do this:

IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions()
{
    HostName = Config.HttpHost,
    BatchEventDataSizeLimit = PusherOptions.DEFAULT_BATCH_EVENT_DATA_SIZE_LIMIT, // 10KB
});

try
{
    var events = new[]
    {
        new Event {Channel = "channel-1", EventName = "event-1", Data = "hello world"},
        new Event {Channel = "channel-2", EventName = "event-2", Data = new string('Q', 10 * 1024 + 1)},
    };
    await pusher.TriggerAsync(events).ConfigureAwait(false);
}
catch (EventDataSizeExceededException eventDataSizeError)
{
    // Handle the error when event data exceeds 10KB
}

Excluding event recipients

In order to avoid the person that triggered the event also receiving it the trigger function can take an optional ITriggerOptions parameter which has a SocketId property. For more information see: https://pusher.com/docs/channels/server_api/excluding-event-recipients.

ITriggerResult result = await pusher.TriggerAsync(channel, event, data, new TriggerOptions
{
    SocketId = "1234.56"
}).ConfigureAwait(false);

Authenticating channel subscription

Authenticating Private channels

To authorise your users to access private channels on Channels, you can use the Authenticate function:

var auth = pusher.Authenticate(channelName, socketId);
var json = auth.ToJson();

The json can then be returned to the client which will then use it for validation of the subscription with Channels.

For more information see: https://pusher.com/docs/channels/server_api/authenticating-users

Authenticating Presence channels

Using presence channels is similar to private channels, but you can specify extra data to identify that particular user:

var channelData = new PresenceChannelData
{
    user_id = "unique_user_id",
    user_info = new
    {
        name = "Phil Leggetter",
        twitter_id = "@leggetter",
    }
};
var auth = pusher.Authenticate(channelName, socketId, channelData);
var json = auth.ToJson();

The json can then be returned to the client which will then use it for validation of the subscription with Channels.

For more information see: https://pusher.com/docs/channels/server_api/authenticating-users

End-to-end encryption

This library supports end-to-end encryption of your private channels. This means that only you and your connected clients will be able to read your messages.

More information on end-to-end encrypted channels can be found here.

Please note: Encrypted channels must be prefixed with private-encrypted-. Currently, only private channels can be encrypted. See channel naming conventions.

You can enable this feature by following these steps:

  1. You should first set up Private channels. This involves creating an authentication endpoint on your server.

  2. Next, generate a 32 byte master encryption key.

    Because it is a secret, store this key securely and do not share it with anyone, not even Pusher.

    To generate a suitable key from a secure random source, you could use System.Security.Cryptography.RandomNumberGenerator:

    byte[] encryptionMasterKey = new byte[32];
    using (RandomNumberGenerator random = RandomNumberGenerator.Create())
    {
        random.GetBytes(encryptionMasterKey);
    }
  3. Pass your master encryption key to the SDK constructor

    Pusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions
    {
        Cluster = Config.Cluster,
        EncryptionMasterKey = encryptionMasterKey,
        Encrypted = true,
    });
    
    await pusher.TriggerAsync("private-encrypted-my-channel", "my-event", new 
    {
        message = "hello world"
    }).ConfigureAwait(false);
  4. Subscribe to these channels in your client, and you're done! You can verify it is working by checking out the debug console on the https://dashboard.pusher.com and seeing the scrambled ciphertext.

Querying application state

It is possible to query the state of your Pusher application using the generic Pusher.GetAsync( resource ) method and overloads.

For full details see: https://pusher.com/docs/channels/library_auth_reference/rest-api

Getting information for all channels

You can get a list of channels that are present within your application:

IGetResult<ChannelsList> result = await pusher.GetAsync<ChannelsList>("/channels");

or

IGetResult<ChannelsList> result = await pusher.FetchStateForChannelsAsync<ChannelsList>();

You can provide additional parameters to filter the list of channels that is returned.

IGetResult<ChannelsList> result = await _pusher.GetAsync<ChannelsList>(
    "/channels",
    new
    {
        filter_by_prefix = "presence-"
    }).ConfigureAwait(false);

or

IGetResult<ChannelsList> result = await pusher.FetchStateForChannelsAsync<ChannelsList>(new
{
    filter_by_prefix = "presence-"
}).ConfigureAwait(false);

Getting information for a channel

Retrieve information about a single channel:

IGetResult<object> result = await pusher.GetAsync<object>("/channels/my_channel" );

or

IGetResult<object> result = await pusher.FetchStateForChannelAsync<object>("my_channel");

Retrieve information about multiple channels:

IGetResult<object> result = await pusher.FetchStateForChannelsAsync<object>();

Note: object has been used above because as yet there isn't a defined class that the information can be serialized on to

Getting user information for a presence channel

Retrieve a list of users that are on a presence channel:

IGetResult<object> result =
    await pusher.FetchUsersFromPresenceChannelAsync<object>("/channels/presence-channel/users");

or

IGetResult<object> result =
    await pusher.FetchUsersFromPresenceChannelAsync<object>("my_channel");

Note: object has been used above because as yet there isn't a defined class that the information can be serialized on to

Webhooks

Channels will trigger Webhooks based on the settings you have for your application. You can consume these and use them within your application as follows.

For more information see https://pusher.com/docs/channels/server_api/webhooks.

// How you get these depends on the framework you're using

// HTTP_X_PUSHER_SIGNATURE from HTTP Header
var receivedSignature = "value";

// Body of HTTP request
var receivedBody = "value";

var pusher = new Pusher(...);
var webHook = pusher.ProcessWebHook(receivedSignature, receivedBody);
if(webHook.IsValid)
{
  // The Webhook validated
  // Dictionary<string,string>[]
  var events = webHook.Events;

  foreach(var webHookEvent in webHook.Events)
  {
    var eventType = webHookEvent["name"];
    var channelName = webHookEvent["channel"];

    // depending on the type of event (eventType)
    // there may be other values in the Dictionary<string,string>
  }

}
else {
  // Log the validation errors to work out what the problem is
  // webHook.ValidationErrors
}

Developer notes

  • Developed using Visual Studio 2017 Community Edition
  • PusherServer acceptance tests depends on PusherClient.

The Pusher test application settings are now loaded from a JSON config file stored in the root of the source tree and named AppConfig.test.json. Make a copy of ./AppConfig.sample.json and name it AppConfig.test.json. Modify the contents of AppConfig.test.json with your test application settings. You should be good to run all the tests successfully.

Code signing key generation

To generate a new signing key, open a PowerShell command console and execute the command

./StrongName/GeneratePusherKey.ps1

Copy the public key file PusherServer.public.snk to the source root folder.

Take the base 64 encoded string and add it to the environment secret named CI_CODE_SIGN_KEY. This is used by publish.yml. Once this step is done remove all traces of the private signing key file.

Also copy the PublicKey and apply it to the code file ./PusherServer/Properties/AssemblyInfo.Signed.cs; for example

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("PusherServer.Tests, PublicKey=002400000...7dd")]

Debug tracing

Debug tracing is now off by default. To enable it use the new Pusher option: TraceLogger.

IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions()
{
    HostName = Config.HttpHost,
    TraceLogger = new DebugTraceLogger(),
});

Asynchronous programming

From v4.0.0 onwards, this library uses the async / await syntax from .NET 4.5+.

This means that you can now use the Channels .NET library asynchronously using the following code style:

using PusherServer;

var options = new PusherOptions();
options.Cluster = APP_CLUSTER;

var pusher = new Pusher(APP_ID, APP_KEY, APP_SECRET, options);

Task<ITriggerResult> resultTask = pusher.TriggerAsync("my-channel", "my-event", new
{
    message = "hello world"
});

// You can do work here that doesn't rely on the result of TriggerAsync  
DoIndependentWork();

ITriggerResult result = await resultTask;

This also means that the library is now only officially compatible with .NET 4.5 and above (including .NET Core). If you need to support older versions of the .NET framework then you have a few options:

Please note that neither of these workarounds will be officially supported by Pusher.

Alternative environments

The solution can be opened and compiled in Xamarin Studio on OSX.

Alternatively, the solution can be built from the command line if Mono is installed. First of all, open up a terminal and navigate to the root directory of the solution. The second step is to restore the Nuget packages, which can be done with this command

nuget restore pusher-dotnet-server.sln

and finally build the solution, now that the packages have been restored

xbuild pusher-dotnet-server.sln

During the build, there will be a warning about a section called TestCaseManagementSettings in the GlobalSection. Please ignore this, as it is a Visual Studio specific setting.

License

This code is free to use under the terms of the MIT license.

More Repositories

1

pusher-js

Pusher Javascript library
JavaScript
1,970
star
2

atom-pair

An Atom package that allows for epic pair programming
JavaScript
1,454
star
3

pusher-http-php

PHP library for interacting with the Pusher Channels HTTP API
PHP
1,355
star
4

pusher-http-ruby

Ruby library for Pusher Channels HTTP API
Ruby
659
star
5

libPusher

An Objective-C interface to Pusher Channels
C
409
star
6

pusher-http-laravel

[DEPRECATED] A Pusher Channels bridge for Laravel
PHP
405
star
7

pusher-http-python

Pusher Channels HTTP API library for Python
Python
368
star
8

k8s-spot-rescheduler

Tries to move K8s Pods from on-demand to spot instances
Go
313
star
9

pusher-websocket-java

Pusher Channels client library for Java targeting general Java and Android
Java
302
star
10

pusher-websocket-swift

Pusher Channels websocket library for Swift
Swift
267
star
11

build-a-slack-clone-with-react-and-pusher-chatkit

In this tutorial, you'll learn how to build a chat app with React, complete with typing indicators, online status, and more.
JavaScript
235
star
12

pusher-angular

Pusher Angular Library | owner=@leesio
JavaScript
233
star
13

pusher-http-go

Pusher Channels HTTP API library for Go
Go
196
star
14

NWWebSocket

A WebSocket client written in Swift, using the Network framework from Apple.
Swift
123
star
15

k8s-spot-termination-handler

Monitors AWS for spot termination notices when run on spot instances and shuts down gracefully
Makefile
118
star
16

go-interface-fuzzer

Automate the boilerplate of fuzz testing Go interfaces | owner: @willsewell
Go
110
star
17

pusher-websocket-dotnet

Pusher Channels Client Library for .NET
C#
107
star
18

k8s-auth-example

Example Kubernetes Authentication helper. Performs OIDC login and configures Kubectl appropriately.
Go
107
star
19

faros

Faros is a CRD based GitOps controller
Go
99
star
20

backbone-todo-app

JavaScript
92
star
21

chatkit-client-js

JavaScript client SDK for Pusher Chatkit
JavaScript
90
star
22

pusher-channels-flutter

Pusher Channels client library for Flutter targeting IOS, Android, and WEB
Dart
72
star
23

quack

In-Cluster templating for Kubernetes manifests
Go
70
star
24

pusher-websocket-react-native

React Native official Pusher SDK
TypeScript
61
star
25

websockets-from-scratch-tutorial

Tutorial that shows how to implement a websocket server using Ruby's built-in libs
Ruby
60
star
26

push-notifications-php

Pusher Beams PHP Server SDK
PHP
56
star
27

backpusher

JavaScript
54
star
28

chatkit-android

Android client SDK for Pusher Chatkit
Kotlin
53
star
29

django-pusherable

Real time notification when an object view is accessed via Pusher
Python
52
star
30

cli

A CLI for Pusher (beta)
Go
51
star
31

notify

Ruby
51
star
32

k8s-spot-price-monitor

Monitors the spot prices of instances in a Kubernetes cluster and exposes them as prometheus metrics
Python
44
star
33

chatkit-command-line-chat

A CLI chat, built with Chatkit
JavaScript
41
star
34

pusher-http-java

Java client to interact with the Pusher HTTP API
Java
40
star
35

chatkit-swift

Swift SDK for Pusher Chatkit
Swift
40
star
36

push-notifications-web

Beams Browser notifications
JavaScript
39
star
37

electron-desktop-chat

A desktop chat built with React, React Desktop and Electron
JavaScript
38
star
38

crank

Process slow restarter
Go
37
star
39

pusher-websocket-android

Library built on top of pusher-websocket-java for Android. Want Push Notifications? Check out Pusher Beams!
Java
35
star
40

chameleon

A collection of front-end UI components used across Pusher ✨
CSS
35
star
41

chatkit-server-php

PHP SDK for Pusher Chatkit
PHP
35
star
42

push-notifications-swift

Swift SDK for the Pusher Beams product:
Swift
34
star
43

cide

Isolated test runner with Docker
Ruby
33
star
44

pusher-phonegap-android

JavaScript
30
star
45

push-notifications-python

Pusher Beams Python Server SDK
Python
30
star
46

pusher-websocket-unity

Pusher Channels Unity Client Library
C#
27
star
47

hacktoberfest

24
star
48

laravel-chat

PHP
23
star
49

push-notifications-android

Android SDK for Pusher Beams
Kotlin
21
star
50

push-notifications-node

Pusher Beams Node.js Server SDK
JavaScript
20
star
51

pusher-test-iOS

iOS app for developers to test connections to Pusher
Objective-C
19
star
52

push-notifications-ruby

Pusher Beams Ruby Server SDK
Ruby
18
star
53

chatkit-server-node

Node.js SDK for Pusher Chatkit
TypeScript
16
star
54

rack-headers_filter

Remove untrusted headers from Rack requests | owner=@zimbatm
Ruby
15
star
55

pusher-test-android

Test and diagnostic app for Android, based on pusher-java-client
Java
14
star
56

pusher-realtime-tfl-cameras

Realtime TfL Traffic Camera API, powered by Pusher
JavaScript
14
star
57

buddha

Buddha command execution and health checking | owner: @willsewell
Go
14
star
58

chatkit-server-go

Chatkit server SDK for Golang
Go
13
star
59

pusher-channels-auth-example

A simple server exposing a pusher auth endpoint
JavaScript
13
star
60

pusher-platform-js

Pusher Platform client library for browsers and react native
TypeScript
13
star
61

stronghold

[DEPRECATED] A configuration service | owner: @willsewell
Haskell
12
star
62

sample-chatroom-ios-chatkit

How to make an iOS Chatroom app using Swift and Chatkit
PHP
12
star
63

pusher-twilio-example

CSS
12
star
64

chatkit-server-ruby

Ruby server SDK for Chatkit
Ruby
12
star
65

prom-rule-reloader

Watches configmaps for prometheus rules and keeps prometheus in-sync
Go
12
star
66

electron-desktop-starter-template

JavaScript
11
star
67

realtime-visitor-tracker

Realtime location aware visitor tracker for a web site or application
PHP
11
star
68

push-notifications-server-java

Pusher Beams Java Server SDK
Kotlin
10
star
69

android-slack-clone

Android chat application, built with Chatkit
Kotlin
10
star
70

filtrand

JavaScript
10
star
71

vault

Front-end pattern library
Ruby
9
star
72

git-store

Go git abstraction for use in Kubernetes Controllers
Go
9
star
73

pusher-platform-android

Pusher Platform SDK for Android
Kotlin
9
star
74

push-notifications-go

Pusher Beams Go Server SDK
Go
9
star
75

pusher-platform-swift

Swift SDK for Pusher platform products
Swift
8
star
76

realtime_survey_complete

JavaScript
8
star
77

docs

The all new Pusher docs, powered by @11ty and @vercel
CSS
8
star
78

push-notifications-server-swift

Pusher Beams Swift Server SDK
Swift
8
star
79

pusher-python-rest

Python client to interact with the Pusher REST API. DEPRECATED in favour of https://github.com/pusher/pusher-http-python
Python
8
star
80

real-time-progress-bar-tutorial

Used inthe realtime progress bar tutorial blog post - http://blog.pusher.com
JavaScript
7
star
81

pusher-channels-chunking-example

HTML
7
star
82

pusher-http-swift

Swift library for interacting with the Pusher Channels HTTP API
Swift
7
star
83

feeds-client-js

JS client for Pusher Feeds
JavaScript
6
star
84

pusher-test

Simple website which allows manual testing of pusher-js versions
JavaScript
6
star
85

java-websocket

A fork of https://github.com/TooTallNate/Java-WebSocket | owner=@zmarkan
HTML
6
star
86

navarchos

Node replacing controller
Go
5
star
87

bridge-troll

A Troll that ensures files don't change
Go
5
star
88

realtime-notifications-tutorial

Create realtime notifications in minutes, not days =)
4
star
89

pusher-socket-protocol

Protocol for pusher sockets
HTML
4
star
90

icanhazissues

Github issues kanban
JavaScript
4
star
91

textsync-server-node

[DEPRECATED] A node.js library to simplify token generation for TextSync authorization endpoints.
TypeScript
4
star
92

pusher_tutorial_realtimeresults

JavaScript
3
star
93

pusher-js-diagnostics

JavaScript
3
star
94

react-rest-api-tutorial

Accompanying tutorial for consuming RESTful APIs in React
CSS
3
star
95

feeds-server-node

The server Node SDK for Pusher Feeds
JavaScript
3
star
96

testing

Configuration for Pusher's Open Source Prow instance
Go
3
star
97

spacegame_example

Simple example of a space game using node.js and Pusher
JavaScript
3
star
98

chatkit-quickstart-swift

A project to get started with Chatkit.
Swift
2
star
99

pusher-whos-in

Ruby
2
star
100

healthz-proxy

healthz proxy for zero downtime rollouts
Go
2
star