-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpadCookie.js
101 lines (90 loc) · 2.61 KB
/
padCookie.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
var sessions = require("client-sessions");
var secret = require("./cookie-secret.js");
var options = {
cookieName: 'my_pads',
secret: secret,
duration: 365 * 24 * 60 * 60 * 1000, // how long the session will stay valid in ms
activeDuration: 24 * 60 * 60 * 1000 // if expiresIn < activeDuration, the session will be extended by activeDuration milliseconds
}
var sortAndAdd = function(padsArray, padURL, padType){
var compare = function(a,b){
// we want favorites sorted at the top
// then we want to sort by date
if(a.favorite && !b.favorite){
return -1;
}
else if(!a.favorite && b.favorite){
return 1;
}
else{
if (a.date > b.date)
return -1;
if (a.date < b.date)
return 1;
}
return 0;
}
var containsObject = function(obj, list){
for(var i = 0; i < list.length; i++) {
var current = list[i];
var obj1 = {}, obj2 = {};
obj1[list[i].type] = list[i].url;
obj2[obj.type] = obj.url;
if (JSON.stringify(obj1) === JSON.stringify(obj2)) {
return true;
}
}
return false;
}
var uniqueObjects = function(a){
var returnObj = [];
for(var i = 0; i<a.length; i++){
if(!containsObject(a[i], returnObj)){
returnObj.push(a[i]);
}
}
return returnObj;
}
var findFavorites = function(a){
var favorites = [];
for(var i = 0; i < a.length; i++){
if(a[i].favorite){
favorites.push(a[i].url);
}
}
for(var i = 0; i < a.length; i++){
if(favorites.indexOf(a[i].url) > -1){
a[i].favorite = true;
}
}
return a;
}
var currentPads = padsArray || [];
currentPads.push({type: padType, url: padURL, date: new Date().toISOString(), favorite: false});
currentPads = findFavorites(currentPads);
currentPads.sort(compare);
currentPads = uniqueObjects(currentPads);
return currentPads;
}
var format = function(cookie){
if(typeof cookie !== 'object') return false;
var privatePads = [], sharedPads = [], publicPads = [];
for(var i=0; i<cookie.length; i++){
var p = cookie[i];
if(typeof p.type !== 'undefined'){
if(p.type == 'private'){
privatePads.push({url: p.url, favorite: p.favorite});
}
else if(p.type == 'shared'){
sharedPads.push({url: p.url, favorite: p.favorite});
}
else if(p.type == 'public'){
publicPads.push({url: p.url, favorite: p.favorite});
}
}
}
return {privatePads: privatePads, sharedPads: sharedPads, publicPads: publicPads}
}
module.exports = sessions(options);
module.exports.sortAndAdd = sortAndAdd;
module.exports.format = format;