-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.js
71 lines (55 loc) · 1.72 KB
/
Client.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
var fs = require('fs');
var crypto = require('crypto');
var FileOrganizer = require('./FileOrganizer.js')();
var DatabaseHandler = require('./DatabaseHandler.js');
var db = new DatabaseHandler('dbFile.db');
var Promise = require("es6-promise").Promise;
var Client = function(){
var allowedNamePattern = /^[A-z0-9_]+$/;
var create = function(){
var clientId = _generateRandomClientId();
FileOrganizer.createFileStorage(clientId);
db.insertClient(clientId);
return clientId;
};
var setName = function(clientId,name){
return new Promise(function(resolve, reject){
var validName = (name.match(allowedNamePattern) !== null
&& name.match(allowedNamePattern).length > 0);
function onSuccess (){ resolve(name); }
function onError (error){ reject(error); }
if(validName){
db.setClientName(clientId,name).then(onSuccess,onError);
}else{
//Set empty if name is illegal
db.setClientName(clientId,"").then(onSuccess,onError);
}
})
}
var setParticipating = function(clientId,value){
return new Promise(function(resolve, reject){
var hasBeenSet = false;
if(value === "false" || value === "true" || value === false || value === true) {
db.setClientParticipating(clientId,value).then(function(){
resolve(value);
},function(error){
reject(error);
});
}else{
reject("Participation value not recognised:"+value);
}
})
}
var _generateRandomClientId = function(){
var hash = crypto.createHash('sha1');
hash.update(Date.now()+" "+Math.random()*1000);
var clientId = hash.digest('hex');
return clientId;
};
return{
create:create,
setParticipating:setParticipating,
setName:setName
};
};
module.exports = Client;