|
export default class ChatController { |
|
|
|
/** |
|
* In order to set up the chat feature we need to complete a number of tasks |
|
* in a particular order. In order to achieve this we call the initialize |
|
* method which is a generator and has a #next method. |
|
*/ |
|
constructor($scope, $http, datastore, chateventhandler){ |
|
'ngInject'; |
|
this.scope = $scope; |
|
this.http = $http; |
|
this.directory = 'http://192.168.99.100:3010' |
|
this.chatEventHandler = chateventhandler; |
|
this.connected = false; |
|
this.config = {"withCredentials": true, "Access-Control-Allow-Origin": true}; |
|
this.host = null; |
|
this.ws = null; |
|
this.account = datastore.retrieve('account'); |
|
this.username = datastore.retrieve('username'); |
|
this.signature = datastore.retrieve('signature'); |
|
this.initializer = this.initialize(); |
|
this.initializer.next(); |
|
this.initializer.next(); |
|
this.initializer.next(); |
|
this.initializer.next(); |
|
} |
|
|
|
*initialize(){ |
|
yield this.authorize(); |
|
yield this.makeConnection(); |
|
yield this.setConnected(); |
|
yield this.setUpEventHandlers(); |
|
} |
|
|
|
authorize(){ |
|
return new Promise((resolve, reject) => { |
|
var body = JSON.stringify({ |
|
account: this.account, |
|
username: this.username, |
|
signature: this.signature |
|
}) |
|
this.http.post(this.directory + '/authorize', body, this.config) |
|
.then(response => { |
|
if (response['status'] == 200){ |
|
this.host = response['host']; |
|
resolve(); |
|
} |
|
else { |
|
reject(); |
|
} |
|
}) |
|
}) |
|
} |
|
|
|
makeConnection(){ |
|
return new Promise((resolve, reject) => { |
|
var ws = new WebSocket(this.host + '/connect'); |
|
if (ws) { |
|
this.ws = ws; |
|
resolve(ws); |
|
} |
|
else { |
|
console.log('connection wasnt made', response) |
|
reject(); |
|
} |
|
}) |
|
} |
|
|
|
setUpEventHandlers(){ |
|
this.chatEventHandler['ws'] = this.ws |
|
this.chatEventHandler['signature'] = this.signature |
|
this.ws.onopen = this.chatEventHandler['onopen']; |
|
this.ws.onmessage = this.chatEventHandler['onmessage']; |
|
this.ws.onerror = this.chatEventHandler['onerror']; |
|
this.ws.onclose = this.chatEventHandler['onclose']; |
|
} |
|
|
|
setConnected(){ |
|
if (this.ws.readyState == 1){ |
|
this.connected = true |
|
return |
|
} |
|
this.connected = false |
|
} |
|
|
|
reconnect(){ |
|
|
|
} |
|
|
|
} |