2016-10-14 16:25:57 +00:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
const Dragonfly = global.Dragonfly;
|
|
|
|
const cl = global.botanLoader;
|
|
|
|
|
2016-10-15 03:28:55 +00:00
|
|
|
const Cookie = cl.load( "botanss.net.components.Cookie" );
|
|
|
|
|
2016-10-14 16:25:57 +00:00
|
|
|
class PageCache
|
|
|
|
{
|
|
|
|
constructor()
|
|
|
|
{
|
2016-10-15 03:28:55 +00:00
|
|
|
this.cache = {};
|
|
|
|
this.excepts = {};
|
|
|
|
|
2016-10-14 16:25:57 +00:00
|
|
|
setInterval( () => {
|
|
|
|
var d = new Date().getTime();
|
|
|
|
for( var i in this.cache )
|
|
|
|
{
|
|
|
|
var c = this.cache[ i ];
|
|
|
|
if( c.ttl < d ) delete this.cache[ i ];
|
|
|
|
}
|
2016-10-15 03:28:55 +00:00
|
|
|
|
|
|
|
for( var i in this.excepts )
|
|
|
|
{
|
|
|
|
var c = this.excepts[ i ];
|
|
|
|
if( c.ttl < d ) delete this.excepts[ i ];
|
|
|
|
}
|
2016-10-14 16:25:57 +00:00
|
|
|
}, 30000 );
|
|
|
|
}
|
|
|
|
|
|
|
|
store( req, res, data, ttl )
|
|
|
|
{
|
|
|
|
if( !global.pagecache ) return;
|
|
|
|
var key = req.url;
|
|
|
|
|
|
|
|
var expires = new Date().getTime() + 1000 * ttl;
|
|
|
|
|
|
|
|
this.cache[ key ] = {
|
|
|
|
data: data
|
|
|
|
, headers: {
|
|
|
|
"Content-Length": res.headers[ "Content-Length" ]
|
|
|
|
, "Content-Type": res.headers[ "Content-Type" ]
|
|
|
|
, "X-Cache-Expires": new Date( expires )
|
|
|
|
}
|
|
|
|
, ttl: expires
|
|
|
|
};
|
|
|
|
|
|
|
|
Dragonfly.Debug( "StoreCache: \"" + key + "\", expire " + new Date( expires ) );
|
|
|
|
}
|
|
|
|
|
2016-10-15 03:28:55 +00:00
|
|
|
except( sid, ttl )
|
|
|
|
{
|
|
|
|
if( !global.pagecache ) return;
|
|
|
|
|
|
|
|
var expires = new Date().getTime() + 1000 * ttl;
|
|
|
|
|
|
|
|
this.excepts[ sid ] = { ttl: expires };
|
|
|
|
|
|
|
|
Dragonfly.Debug( "CacheExcept: \"" + sid.substr( 0, 8 ) + "\", expire " + new Date( expires ) );
|
|
|
|
}
|
|
|
|
|
2016-10-14 16:25:57 +00:00
|
|
|
process( req, res )
|
|
|
|
{
|
2016-10-15 03:28:55 +00:00
|
|
|
var cookie = new Cookie( req.headers.cookie );
|
|
|
|
if( cookie.get( "sid" ) in this.excepts ) return false;
|
|
|
|
|
2016-10-14 16:25:57 +00:00
|
|
|
var url = req.url;
|
|
|
|
if( url in this.cache )
|
|
|
|
{
|
|
|
|
Dragonfly.Info(
|
|
|
|
"[C] "
|
|
|
|
+ ( req.headers[ "x-forwarded-for" ] || req.connection.remoteAddress ) + " "
|
|
|
|
+ req.method + ": " + encodeURI( url )
|
|
|
|
+ " - " + req.headers["user-agent"]
|
|
|
|
, Dragonfly.Visibility.VISIBLE
|
|
|
|
);
|
|
|
|
|
|
|
|
var c = this.cache[ url ];
|
|
|
|
res.headers = c.headers;
|
|
|
|
res.write( c.data );
|
|
|
|
res.end();
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = PageCache;
|