forked from FronterAS/top-trumps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
services.js
108 lines (85 loc) · 3.33 KB
/
services.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// Remember that service is a singleton
app.service('Storage', function ($window) {
this.retrieveStoredIds = function () {
var opponentId = $window.localStorage.getItem('opponentId'),
myId = $window.localStorage.getItem('myId'),
ids = {};
// urgh - sorry
if (myId) ids.myId = myId;
if (opponentId) ids.opponentId = opponentId;
return ids;
};
this.clear = function () {
var idTypes = ['opponentId', 'myId'];
idTypes.forEach(function (idType) {
$window.localStorage.removeItem(idType);
});
};
this.saveMyId = function (id) {
$window.localStorage.setItem('myId', id);
return id;
};
this.saveOpponentId = function (id) {
$window.localStorage.setItem('opponentId', id);
return id;
};
})
.service('Connection', function (Storage) {
var connection,
Me,
callbacks,
sendData = function (type, data) {
if (!connection) {
console.error('No, you don\'t have a connection');
return;
}
connection.send({
'type': type,
'value': data
});
},
bindEvents = function (callbacks) {
// When your id is registered with the peer server
connection.on('open', function () {
callbacks.onConnectionToPeerSuccess(connection);
});
// When data is receieved
connection.on('data', callbacks.onDataReceivedFromPeer);
},
onPeerConnectToYou = function (conn) {
connection = conn;
bindEvents(callbacks);
Storage.saveOpponentId(conn.peer);
callbacks.onPeerConnectToYou(conn);
},
onRegisterIdWithPeerServer = function (id) {
Storage.saveMyId(id);
callbacks.onRegisterIdWithPeerServer(id);
},
connectToPeer = function (opponentId) {
if (!Me) {
console.error('You need to set up a Peer instance. Run Connection.init().');
return;
}
Storage.saveOpponentId(opponentId);
connection = Me.connect(opponentId);
bindEvents(callbacks);
},
init = function (_callbacks) {
var storedIds = Storage.retrieveStoredIds();
callbacks = _callbacks;
// This is your PeerJS object which controls all your connections
Me = storedIds.myId ?
new Peer(storedIds.myId, {'key': peerKey}) :
new Peer({'key': peerKey});
// This is when you have registered with the peerjs server
Me.on('open', onRegisterIdWithPeerServer);
// When someone else initialises a connection to you,
Me.on('connection', onPeerConnectToYou);
return Peer;
};
// API
this.init = init;
this.sendData = sendData;
this.connectToPeer = connectToPeer;
});