webmcp
view framework/env/request/default_router.lua @ 215:ba3dd4a17e3d
Some code cleanup/rearrangement for request handling
| author | jbe | 
|---|---|
| date | Mon Jan 12 01:48:11 2015 +0100 (2015-01-12) | 
| parents | framework/env/request/handler.lua@47ebf4213716 | 
| children | fd0360594636 | 
 line source
     1 -- TODO: function incomplete yet
     3 local function file_exists(filename)
     4   local file = io.open(filename, "r")
     5   if file then
     6     io.close(file)
     7     return true
     8   else
     9     return false
    10   end
    11 end
    13 function request.default_router(path)
    14   request._http_request = http_request
    15   local path = http_request.path
    16   local function parse_path()
    17     if not path then
    18       return
    19     end
    20     if path == "/" then
    21       return {module = "index", view = "index"}
    22     end
    23     module = string.match(path, "^/([^/]+)/$")
    24     if module then
    25       return {module = module, view = "index"}
    26     end
    27     module, action = string.match(path, "^/([^/]+)/([^/.]+)$")
    28     if module then
    29       return {module = module, action = action}
    30     end
    31     module, view, suffix = string.match(path, "^/([^/]+)/([^/.]+)%.([^/]+)$")
    32     if module then
    33       return {module = module, view = view, suffix = suffix}
    34     end
    35     module, view, id, suffix = string.match(path, "^/([^/]+)/([^/]+)/([^/.]+)%.([^/]+)$")
    36     if module then
    37       return {module = module, view = view, id = id, suffix = suffix}
    38     end
    39   end
    40   request._data = parse_path()
    41   if path then
    42     local elements = {}
    43     for match in string.gmatch(path, "/") do
    44       elements[#elements+1] = "../"
    45     end
    46     elements[#elements] = nil
    47     if #elements > 0 then
    48       request._relative_baseurl = table.concat(elements)
    49     else
    50       request._relative_baseurl = "./"
    51     end
    52   end
    53   local success, error_info = xpcall(
    54     function()
    56       -- restore slots if coming from http redirect
    57       local tempstore_value = request.get_param{method = "GET", name = "_tempstore"}
    58       if tempstore_value then
    59         trace.restore_slots{}
    60         local blob = tempstore.pop(tempstore_value)
    61         if blob then slot.restore_all(blob) end
    62       end
    65       if request.is_404() then
    66         request.set_status("404 Not Found")
    67         if request.get_404_route() then
    68           request.forward(request.get_404_route())
    69         else
    70           error("No 404 page set.")
    71         end
    72       elseif request.get_action() then
    73         trace.request{
    74           module = request.get_module(),
    75           action = request.get_action()
    76         }
    77         if
    78           request.get_404_route() and
    79           not file_exists(
    80             encode.action_file_path{
    81               module = request.get_module(),
    82               action = request.get_action()
    83             }
    84           )
    85         then
    86           request.set_status("404 Not Found")
    87           request.forward(request.get_404_route())
    88         else
    89           if cgi.method ~= "POST" then
    90             request.set_status("405 Method Not Allowed")
    91             cgi.add_header("Allow: POST")
    92             error("Tried to invoke an action with a GET request.")
    93           end
    94           local action_status = execute.filtered_action{
    95             module = request.get_module(),
    96             action = request.get_action(),
    97           }
    98           if not request.is_rerouted() then
    99             local routing_mode, routing_module, routing_view
   100             routing_mode   = cgi.params["_webmcp_routing." .. action_status .. ".mode"]
   101             routing_module = cgi.params["_webmcp_routing." .. action_status .. ".module"]
   102             routing_view   = cgi.params["_webmcp_routing." .. action_status .. ".view"]
   103             routing_anchor = cgi.params["_webmcp_routing." .. action_status .. ".anchor"]
   104             if not (routing_mode or routing_module or routing_view) then
   105               action_status = "default"
   106               routing_mode   = cgi.params["_webmcp_routing.default.mode"]
   107               routing_module = cgi.params["_webmcp_routing.default.module"]
   108               routing_view   = cgi.params["_webmcp_routing.default.view"]
   109               routing_anchor = cgi.params["_webmcp_routing.default.anchor"]
   110             end
   111             assert(routing_module, "Routing information has no module.")
   112             assert(routing_view,   "Routing information has no view.")
   113             if routing_mode == "redirect" then
   114               local routing_params = {}
   115               for key, value in pairs(cgi.params) do
   116                 local status, stripped_key = string.match(
   117                   key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
   118                 )
   119                 if status == action_status then
   120                   routing_params[stripped_key] = value
   121                 end
   122               end
   123               request.redirect{
   124                 module = routing_module,
   125                 view   = routing_view,
   126                 id     = cgi.params["_webmcp_routing." .. action_status .. ".id"],
   127                 params = routing_params,
   128                 anchor = routing_anchor
   129               }
   130             elseif routing_mode == "forward" then
   131               request.forward{ module = routing_module, view = routing_view }
   132             else
   133               error("Missing or unknown routing mode in request parameters.")
   134             end
   135           end
   136         end
   137       else
   138         -- no action
   139         trace.request{
   140           module = request.get_module(),
   141           view   = request.get_view()
   142         }
   143         if
   144           request.get_404_route() and
   145           not file_exists(
   146             encode.view_file_path{
   147               module = request.get_module(),
   148               view   = request.get_view()
   149             }
   150           )
   151         then
   152           request.set_status("404 Not Found")
   153           request.forward(request.get_404_route())
   154         end
   155       end
   157       if not request.get_redirect_data() then
   158         request.process_forward()
   159         local view = request.get_view()
   160         if string.find(view, "^_") then
   161           error("Tried to call a private view (prefixed with underscore).")
   162         end
   163         execute.filtered_view{
   164           module = request.get_module(),
   165           view   = view,
   166         }
   167       end
   169       -- force error due to missing absolute base URL until its too late to display error message
   170       --if request.get_redirect_data() then
   171       --  request.get_absolute_baseurl()
   172       --end
   174     end,
   176     function(errobj)
   177       return {
   178         errobj = errobj,
   179         stacktrace = string.gsub(
   180           debug.traceback('', 2),
   181           "^\r?\n?stack traceback:\r?\n?", ""
   182         )
   183       }
   184     end
   185   )
   187   if not success then trace.error{} end
   189   -- laufzeitermittlung
   190   trace.exectime{ real = extos.monotonic_hires_time(), cpu = os.clock() }
   192   slot.select('trace', trace.render)  -- render trace information
   194   local redirect_data = request.get_redirect_data()
   196   -- log error and switch to error layout, unless success
   197   if not success then
   198     local errobj     = error_info.errobj
   199     local stacktrace = error_info.stacktrace
   200     if not request.get_status() and not request.get_json_request_slots() then
   201       request.set_status("500 Internal Server Error")
   202     end
   203     slot.set_layout('system_error')
   204     slot.select('system_error', function()
   205       if getmetatable(errobj) == mondelefant.errorobject_metatable then
   206         slot.put(
   207           "<p>Database error of class <b>",
   208           encode.html(errobj.code),
   209           "</b> occured:<br/><b>",
   210           encode.html(errobj.message),
   211           "</b></p>"
   212         )
   213       else
   214         slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
   215       end
   216       slot.put("<p>Stack trace follows:<br/>")
   217       slot.put(encode.html_newlines(encode.html(stacktrace)))
   218       slot.put("</p>")
   219     end)
   220   elseif redirect_data then
   221     local redirect_params = {}
   222     for key, value in pairs(redirect_data.params) do
   223       redirect_params[key] = value
   224     end
   225     local slot_dump = slot.dump_all()
   226     if slot_dump ~= "" then
   227       redirect_params.tempstore = tempstore.save(slot_dump)
   228     end
   229     local json_request_slots = request.get_json_request_slots()
   230     if json_request_slots then
   231       redirect_params["_webmcp_json_slots[]"] = json_request_slots  
   232     end
   233     cgi.redirect(
   234       encode.url{
   235         base   = request.get_absolute_baseurl(),
   236         module = redirect_data.module,
   237         view   = redirect_data.view,
   238         id     = redirect_data.id,
   239         params = redirect_params,
   240         anchor = redirect_data.anchor
   241       }
   242     )
   243     cgi.send_data()
   244   end
   246   if not success or not redirect_data then
   248     local http_status = request.get_status()
   249     if http_status then
   250       cgi.set_status(http_status)
   251     end
   253     local json_request_slots = request.get_json_request_slots()
   254     if json_request_slots then
   255       cgi.set_content_type('application/json')
   256       local data = {}
   257       for idx, slot_ident in ipairs(json_request_slots) do
   258         data[slot_ident] = slot.get_content(slot_ident)
   259       end
   260       cgi.send_data(encode.json(data))
   261     else
   262       cgi.set_content_type(slot.get_content_type())
   263       cgi.send_data(slot.render_layout())
   264     end
   265   end
   267 end
