1 module hunt.http.server.HttpSession; 2 3 import hunt.container.HashMap; 4 import hunt.container.Map; 5 6 import hunt.datetime; 7 import hunt.lang.exception; 8 import std.datetime; 9 10 11 /** 12 * 13 */ 14 class HttpSession { 15 16 private string id; 17 private long creationTime; 18 private long lastAccessedTime; 19 private int maxInactiveInterval; 20 private Map!(string, Object) attributes; 21 private bool newSession; 22 23 string getId() { 24 return id; 25 } 26 27 void setId(string id) { 28 this.id = id; 29 } 30 31 long getCreationTime() { 32 return creationTime; 33 } 34 35 void setCreationTime(long creationTime) { 36 this.creationTime = creationTime; 37 } 38 39 long getLastAccessedTime() { 40 return lastAccessedTime; 41 } 42 43 void setLastAccessedTime(long lastAccessedTime) { 44 this.lastAccessedTime = lastAccessedTime; 45 } 46 47 /** 48 * Get the max inactive interval. The time unit is second. 49 * 50 * @return The max inactive interval. 51 */ 52 int getMaxInactiveInterval() { 53 return maxInactiveInterval; 54 } 55 56 /** 57 * Set the max inactive interval. The time unit is second. 58 * 59 * @param maxInactiveInterval The max inactive interval. 60 */ 61 void setMaxInactiveInterval(int maxInactiveInterval) { 62 this.maxInactiveInterval = maxInactiveInterval; 63 } 64 65 Map!(string, Object) getAttributes() { 66 return attributes; 67 } 68 69 void setAttributes(Map!(string, Object) attributes) { 70 this.attributes = attributes; 71 } 72 73 bool isNewSession() { 74 return newSession; 75 } 76 77 void setNewSession(bool newSession) { 78 this.newSession = newSession; 79 } 80 81 bool isInvalid() { 82 long currentTime = convert!(TimeUnit.HectoNanosecond, TimeUnit.Millisecond)(Clock.currStdTime); 83 return (currentTime - lastAccessedTime) > (maxInactiveInterval * 1000); 84 } 85 86 static HttpSession create(string id, int maxInactiveInterval) { 87 long currentTime = convert!(TimeUnit.HectoNanosecond, TimeUnit.Millisecond)(Clock.currStdTime); 88 HttpSession session = new HttpSession(); 89 session.setId(id); 90 session.setMaxInactiveInterval(maxInactiveInterval); 91 session.setCreationTime(currentTime); 92 session.setLastAccessedTime(session.getCreationTime()); 93 session.setAttributes(new HashMap!(string, Object)()); 94 session.setNewSession(true); 95 return session; 96 } 97 98 override bool opEquals(Object o) { 99 if (this is o) return true; 100 HttpSession that = cast(HttpSession) o; 101 if(that is null) return false; 102 return id == that.id; 103 } 104 105 override size_t toHash() @trusted nothrow { 106 return hashOf(id); 107 } 108 } 109 110 111 112 113 /** 114 * 115 */ 116 class SessionInvalidException : RuntimeException { 117 this() { 118 super(""); 119 } 120 121 this(string msg) { 122 super(msg); 123 } 124 } 125 126 /** 127 * 128 */ 129 class SessionNotFound : RuntimeException { 130 this() { 131 super(""); 132 } 133 134 this(string msg) { 135 super(msg); 136 } 137 }