Skip to content

Instantly share code, notes, and snippets.

@ArnaudRinquin
Created October 10, 2015 23:12
Show Gist options
  • Save ArnaudRinquin/1904240dd15ad1edfec3 to your computer and use it in GitHub Desktop.
Save ArnaudRinquin/1904240dd15ad1edfec3 to your computer and use it in GitHub Desktop.
peristream

Peristream

A wrapper around periscope.tv event streams, allowing you to easilly access them

Usage

npm i -S peristream
var peristream = require('peristream');

var stream = peristream(urlOrId);

stream.connect().then(function(emitter){
  emitter.on(peristream.HEARTS, function(message){
    // ...
  });
  
  emitter.on(peristream.COMMENT, function(message){
    // ...
  });
  
  emitter.on(peristream.DISCONNECT, function(message){
    // ...
  });
  
});

// eventually...
stream.disconnect();
import pubnub from 'pubnub';
import EventEmitter from 'EventEmitter';
const API_URL_ROOT = 'https://api.periscope.tv/api/v2/getAccessPublic?broadcast_id=';
export function extractTokenFromUrl(urlOrId) {
return url.split('https://www.periscope.tv/w/')[1];
}
export function fetchPeriscopeDetails(periscopeId) {
return fetch(`${API_URL_ROOT}{periscopeID}`)
.then(response => response.json());
}
export function extractKeysFromDetails({auth_token, subscriber, publisher, channel}) {
return {
auth_key: auth_token,
subscribe_key: subscriber,
publish_key: publisher,
channel
};
}
export function generateStream({auth_key, subscribe_key, publish_key, channel}) {
const pub = pubnub({
ssl: true,
publish_key,
subscribe_key,
});
return {
disconnect() {
pub.unsubscribe();
},
connect() {
const bus = new EventEmitter();
return new Promise(function(resolve, reject){
pub.subscribe({
channel,
auth_key,
callback: payload => {
bus.emit(payload.type, payload);
},
connect: () => {
resolve(bus);
},
disconnect: (){
bus.emit(DISCONNECTED);
},
error: reject,
});
});
},
};
}
export default function peristream(urlOrId) {
const id = extractTokenFromUrl(urlOrId);
let stream;
return {
connect() {
return fetchPeriscopeDetails()
.then(extractKeysFromDetails)
.then(generateStream)
.then((_stream) => {
stream = stream;
return stream.connect();
});
},
disconnect() {
if (!stream) throw new Error('Stream is not connected yet');
stream.disconnect();
}
};
};
export const DISCONNECTED = 'DISCONNECTED';
export const HEARTS = 2;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment