Skip to content

Instantly share code, notes, and snippets.

@ultimatemonty
Last active January 19, 2017 09:19
Show Gist options
  • Save ultimatemonty/5e3f4e1f9bbb84442518 to your computer and use it in GitHub Desktop.
Save ultimatemonty/5e3f4e1f9bbb84442518 to your computer and use it in GitHub Desktop.
PubNub with Ember CLI
// config/environment.js
module.exports = function(environment) {
var ENV = {
modulePrefix: 'ember-cli-pubnub',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
// you could set this per ENV if desired. This is set globally for all ENVs
ENV['pubnub'] = {
subscribe_key: 'your-sub-key',
publish_key: 'your-pub-key',
uuid: 'whatevs'
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
// app/initializers/pubnub.js
// import the pubnub service
import PubNub from '../services/pubnub';
export function initialize(container, application) {
application.register('pubnub:main', PubNub, { singleton: true });
application.inject('controller', 'pubnub', 'pubnub:main');
application.inject('route', 'pubnub', 'pubnub:main');
}
export default {
name: 'pubnub-service',
initialize: initialize
};
// app/services/pubnub.js
import Ember from 'ember';
import ENV from 'ember-cli-pubnub/config/environment';
var PubNubService = Ember.Object.extend(Ember.Evented, {
NAMESPACE: 'pubnub',
pubnub: null,
pnstate: {},
cfg: null,
init: function() {
var PubNub;
// set the config from the ENV var set in config/environment.js
this.set('cfg', ENV['pubnub']);
if (!this.get('cfg')) {
throw 'no configuration `cfg` provided!';
}
// Change to PUBNUB.init to reference the PUBNUB global hanging off WINDOW
PubNub = PUBNUB.init(this.get('cfg'));
this.get('pnstate')['_channels'] = [];
this.get('pnstate')['_presence'] = {};
this.get('pnstate')['_presData'] = {};
return this.set('pubnub', PubNub);
},
emListChannels: function() {
return this.get('pnstate')['_channels'].slice(0);
},
emListPresence: function(channel) {
var _ref;
return (_ref = this.get('pnstate')['_presence'][channel]) != null ? _ref.slice(0) : void 0;
},
emPresenceData: function(channel) {
return this.get('pnstate')['_presData'][channel] || {};
},
emMsgEv: function(channel) {
return "pn-message:" + channel;
},
emPrsEv: function(channel) {
return "pn-presence:" + channel;
},
emPublish: function(args) {
return this.get('pubnub')['publish'].apply(this.get('pubnub'), [args]);
},
_emInstallHandlers: function(args) {
var inst, oldmessage, oldpresence, pnstate, self;
self = this.get('pubnub');
pnstate = this.get('pnstate');
inst = this;
oldmessage = args.message;
args.message = function() {
inst.trigger(inst.emMsgEv(args.channel), {
message: arguments[0],
env: arguments[1],
channel: args.channel
});
if (oldmessage) {
return oldmessage(arguments);
}
};
oldpresence = args.presence;
args.presence = function() {
var channel, cpos, event, _base, _base1;
event = arguments[0];
channel = args.channel;
if (event.uuids) {
self.each(event.uuids, function(uuid) {
var state, _base, _base1;
state = uuid.state ? uuid.state : null;
uuid = uuid.uuid ? uuid.uuid : uuid;
(_base = pnstate['_presence'])[channel] || (_base[channel] = []);
if (pnstate['_presence'][channel].indexOf(uuid) < 0) {
pnstate['_presence'][channel].push(uuid);
}
(_base1 = pnstate['_presData'])[channel] || (_base1[channel] = {});
if (state) {
return pnstate['_presData'][channel][uuid] = state;
}
});
} else {
if (event.uuid && event.action) {
(_base = pnstate['_presence'])[channel] || (_base[channel] = []);
(_base1 = pnstate['_presData'])[channel] || (_base1[channel] = {});
if (event.action === 'leave') {
cpos = pnstate['_presence'][channel].indexOf(event.uuid);
if (cpos !== -1) {
pnstate['_presence'][channel].splice(cpos, 1);
}
delete pnstate['_presData'][channel][event.uuid];
} else {
if (pnstate['_presence'][channel].indexOf(event.uuid) < 0) {
pnstate['_presence'][channel].push(event.uuid);
}
if (event.data) {
pnstate['_presData'][channel][event.uuid] = event.data;
}
}
}
}
return inst.trigger(inst.emPrsEv(args.channel), {
event: event,
message: arguments[1],
channel: channel
});
};
return args;
},
emSubscribe: function(args) {
var inst, pnstate, self, _base, _name;
self = this.get('pubnub');
pnstate = this.get('pnstate');
inst = this;
inst._emInstallHandlers(args);
if (pnstate['_channels'].indexOf(args.channel) < 0) {
pnstate['_channels'].push(args.channel);
}
(_base = pnstate['_presence'])[_name = args.channel] || (_base[_name] = []);
return self['subscribe'].apply(this.get('pubnub'), [args]);
},
emUnsubscribe: function(args) {
var cpos, inst, pnstate, self;
self = this.get('pubnub');
pnstate = this.get('pnstate');
inst = this;
cpos = pnstate['_channels'].indexOf(args.channel);
if (cpos !== -1) {
pnstate['_channels'].splice(cpos, 1);
}
pnstate['_presence'][args.channel] = null;
inst.off(inst.emMsgEv(args.channel));
inst.off(inst.emPrsEv(args.channel));
return self['unsubscribe'](args);
},
emHistory: function(args) {
var inst, self;
self = this.get('pubnub');
inst = this;
args.callback = inst._emFireMessages(args.channel);
return self['history'](args);
},
emHereNow: function(args) {
var inst, self;
self = this.get('pubnub');
inst = this;
args = inst._emInstallHandlers(args);
args.state = true;
args.callback = args.presence;
delete args.presence;
delete args.message;
return self['here_now'](args);
},
_emFireMessages: function(realChannel) {
var inst, self;
self = this.get('pubnub');
inst = this;
return function(messages, t1, t2) {
return self.each(messages[0], function(message) {
return inst.trigger(inst.emMsgEv(realChannel), {
message: message,
channel: realChannel
});
});
};
},
emWhereNow: function(args) {
return this.get('pubnub')['where_now'](args);
},
emState: function(args) {
return this.get('pubnub')['state'](args);
},
emAuth: function() {
return this.get('pubnub')['auth'].apply(this.get('pubnub'), arguments);
},
emAudit: function() {
return this.get('pubnub')['audit'].apply(this.get('pubnub'), arguments);
},
emGrant: function() {
return this.get('pubnub')['grant'].apply(this.get('pubnub'), arguments);
}
});
export default PubNubService;
@rafaltrojanowski
Copy link

great job!

in my console JSHint throws:
services/pubnub.js: line 73, col 76, Expected an assignment or function call and instead saw an expression.
services/pubnub.js: line 77, col 78, Expected an assignment or function call and instead saw an expression.
services/pubnub.js: line 84, col 76, Expected an assignment or function call and instead saw an expression.
services/pubnub.js: line 85, col 78, Expected an assignment or function call and instead saw an expression.
services/pubnub.js: line 119, col 81, Expected an assignment or function call and instead saw an expression.
services/pubnub.js: line 22, col 16, 'PUBNUB' is not defined.
services/pubnub.js: line 158, col 37, 't2' is defined but never used.
services/pubnub.js: line 158, col 33, 't1' is defined but never used.

8 errors

===== 1 JSHint Error

Is it possible to fix these errors in your gist?

@shivendrasoni
Copy link

I am unable to use it in my Ember CLI app.

Can someone explain how to go about using this ?

@rafaltrojanowski
Copy link

@shivendrasoni It's described in this comment pubnub/pubnub-ember#1 (comment)

Could you give more information about you problem?

@fredguth
Copy link

I get the same erros that @rafaltrojanowski got

@villander
Copy link

This works in Ember-CLI 💃

import Ember from 'ember';

export default Ember.Service.extend(Ember.Evented, {
  NAMESPACE: 'pubnub',
  pubnub: {
    cfg: {
        subscribe_key : 'subscribe_key',
        publish_key   : 'publish_key',
        uuid          : 'user_id',
        ssl           : true
    }
  },
  pnstate: {},

  init: function() {
    var PubNub;
    if (!this.get('pubnub').cfg) {
      throw 'no configuration `cfg` provided!';
    }
    PubNub = PUBNUB.init(this.get('pubnub').cfg);
    this.get('pnstate')['_channels'] = [];
    this.get('pnstate')['_presence'] = {};
    this.get('pnstate')['_presData'] = {};
    return this.set('pubnub', PubNub);
  },
  emListChannels: function() {
    return this.get('pnstate')['_channels'].slice(0);
  },
  emListPresence: function(channel) {
    var _ref;
    return (_ref = this.get('pnstate')['_presence'][channel]) != null ? _ref.slice(0) : void 0;
  },
  emPresenceData: function(channel) {
    return this.get('pnstate')['_presData'][channel] || {};
  },
  emMsgEv: function(channel) {
    return "pn-message:" + channel;
  },
  emPrsEv: function(channel) {
    return "pn-presence:" + channel;
  },
  emPublish: function(args) {
    return this.get('pubnub')['publish'].apply(this.get('pubnub'), [args]);
  },
  _emInstallHandlers: function(args) {
    var inst, oldmessage, oldpresence, pnstate, self;
    self = this.get('pubnub');
    pnstate = this.get('pnstate');
    inst = this;
    oldmessage = args.message;
    args.message = function() {
      inst.trigger(inst.emMsgEv(args.channel), {
        message: arguments[0],
        env: arguments[1],
        channel: args.channel
      });
      if (oldmessage) {
        return oldmessage(arguments);
      }
    };
    oldpresence = args.presence;
    args.presence = function() {
      var channel, cpos, event, _base, _base1;
      event = arguments[0];
      channel = args.channel;
      if (event.uuids) {
        self.each(event.uuids, function(uuid) {
          var state, _base, _base1;
          state = uuid.state ? uuid.state : null;
          uuid = uuid.uuid ? uuid.uuid : uuid;
          (_base = pnstate['_presence'])[channel] || (_base[channel] = []);
          if (pnstate['_presence'][channel].indexOf(uuid) < 0) {
            pnstate['_presence'][channel].push(uuid);
          }
          (_base1 = pnstate['_presData'])[channel] || (_base1[channel] = {});
          if (state) {
            return pnstate['_presData'][channel][uuid] = state;
          }
        });
      } else {
        if (event.uuid && event.action) {
          (_base = pnstate['_presence'])[channel] || (_base[channel] = []);
          (_base1 = pnstate['_presData'])[channel] || (_base1[channel] = {});
          if (event.action === 'leave') {
            cpos = pnstate['_presence'][channel].indexOf(event.uuid);
            if (cpos !== -1) {
              pnstate['_presence'][channel].splice(cpos, 1);
            }
            delete pnstate['_presData'][channel][event.uuid];
          } else {
            if (pnstate['_presence'][channel].indexOf(event.uuid) < 0) {
              pnstate['_presence'][channel].push(event.uuid);
            }
            if (event.data) {
              pnstate['_presData'][channel][event.uuid] = event.data;
            }
          }
        }
      }
      return inst.trigger(inst.emPrsEv(args.channel), {
        event: event,
        message: arguments[1],
        channel: channel
      });
    };
    return args;
  },
  emSubscribe: function(args) {
    var inst, pnstate, self, _base, _name;
    self = this.get('pubnub');
    pnstate = this.get('pnstate');
    inst = this;
    inst._emInstallHandlers(args);
    if (pnstate['_channels'].indexOf(args.channel) < 0) {
      pnstate['_channels'].push(args.channel);
    }
    (_base = pnstate['_presence'])[_name = args.channel] || (_base[_name] = []);
    return self['subscribe'].apply(this.get('pubnub'), [args]);
  },
  emUnsubscribe: function(args) {
    var cpos, inst, pnstate, self;
    self = this.get('pubnub');
    pnstate = this.get('pnstate');
    inst = this;
    cpos = pnstate['_channels'].indexOf(args.channel);
    if (cpos !== -1) {
      pnstate['_channels'].splice(cpos, 1);
    }
    pnstate['_presence'][args.channel] = null;
    inst.off(inst.emMsgEv(args.channel));
    inst.off(inst.emPrsEv(args.channel));
    return self['unsubscribe'](args);
  },
  emHistory: function(args) {
    var inst, self;
    self = this.get('pubnub');
    inst = this;
    //args.callback = inst._emFireMessages(args.channel);
    return self['history'](args);
  },
  emHereNow: function(args) {
    var inst, self;
    self = this.get('pubnub');
    inst = this;
    args = inst._emInstallHandlers(args);
    args.state = true;
    args.callback = args.presence;
    delete args.presence;
    delete args.message;
    return self['here_now'](args);
  },
  _emFireMessages: function(realChannel) {
    var inst, self;
    self = this.get('pubnub');
    inst = this;
    return function(messages, t1, t2) {
      return self.each(messages[0], function(message) {
        return inst.trigger(inst.emMsgEv(realChannel), {
          message: message,
          channel: realChannel
        });
      });
    };
  },
  emWhereNow: function(args) {
    return this.get('pubnub')['where_now'](args);
  },
  emState: function(args) {
    return this.get('pubnub')['state'](args);
  },
  emAuth: function() {
    return this.get('pubnub')['auth'].apply(this.get('pubnub'), arguments);
  },
  emAudit: function() {
    return this.get('pubnub')['audit'].apply(this.get('pubnub'), arguments);
  },
  emGrant: function() {
    return this.get('pubnub')['grant'].apply(this.get('pubnub'), arguments);
  }
});

After in any component

import Ember from 'ember';


export default Ember.Component.extend({

pubnubEmber: Ember.inject.service('pubnub'),
subscribe: function(theChannel){
   var pn = this.get('pubnubEmber');
   pn.emSubscribe({ channel: 'channel' });
}

});

@jrdn91
Copy link

jrdn91 commented Dec 1, 2015

Where do I put the code to take action when a message is received?

@mervinva
Copy link

How can I create a channel using this ?
Is there any updated tutorial for pubnub with ember cli ?

@mervinva
Copy link

@rafaltrojanowski I am also getting the same errors.

@mervinva
Copy link

@villander PUBNUB is not defined .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment