-------------------------------------------------------------------------------- -- Title: LWFileService.lua -- Description: Like a square peg in a round hole -- Author: Raphaël Szwarc http://alt.textdrive.com/lua/ -- Creation Date: February 1, 2005 -- Legal: Copyright (C) 2005 Raphaël Szwarc -------------------------------------------------------------------------------- -- import dependencies local LWService = require( "LWService" ) local LWResponse = require( "LWResponse" ) local LFSFile = require( "LFSFile" ) local MIMEType = require( "MIMEType" ) local LULog = require( "LULog" ) -- define the class local super = LWService local self = super() -- class variable(s) local _filter = nil -- constants local MaximumSize = 10000000 -- initialization method function self:init( aPrefix, aPath, anAuthenticator ) super.init( self, aPrefix, anAuthenticator ) self._path = aPath return self end -- method to access this service directory function self:directory() if self._directory == nil then self._directory = LFSFile( self:path() ) end return self._directory end -- method to access this service path function self:path() return self._path end -- method to handle a GET method function self:handleGet( aContext, hasContent ) local aDirectory = self:directory() local aName = self:pathWithContext( aContext ) local aFilter = self:filter() LULog:debug( aName ) if aFilter( aDirectory, aName ) == true then local aFile = LFSFile( self:path(), aName ) if aFile:size() < MaximumSize then local someHeaders = aContext:response():headers() local lastModified = aFile:lastModified() someHeaders:put( "content-type", MIMEType:typeWithExtension( aFile:extension() ) ) someHeaders:put( "etag", aFile:id() ) someHeaders:put( "last-modified", LWResponse:stringWithTime( lastModified ) ) aContext:response():writeContent( aFile:content(), hasContent ) else aContext:response():writeStatus( 413, hasContent ) end else aContext:response():writeStatus( 404, hasContent ) end return self end -- method to access the service file filter for a given context function self:filter() if _filter == nil then _filter = function( aDirectory, aFileName ) if aFileName ~= nil and aFileName:sub( 1, 1 ) ~= "." and aFileName:find( "%.%." ) == nil then local aFile = LFSFile( aDirectory:path(), aFileName ) if aFile:isFile() == true then return true end end return false end end return _filter end return self