|
@@ -0,0 +1,54 @@
|
|
|
|
+-module(n4u_document).
|
|
|
|
+-include_lib("n4u/include/n4u.hrl").
|
|
|
|
+
|
|
|
|
+-export([run/1]).
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+% N4U Server Pages HTTP endpoint handler
|
|
|
|
+
|
|
|
|
+transition(Actions) ->
|
|
|
|
+ receive
|
|
|
|
+ {'INIT', A} -> transition(A);
|
|
|
|
+ {'N4U', Pid} -> Pid ! {actions, Actions}
|
|
|
|
+ after application:get_env(n4u, transition_timeout, 30000) ->
|
|
|
|
+ {timeout, transition}
|
|
|
|
+ end.
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+run(Req) ->
|
|
|
|
+ erlang:put(status, 200),
|
|
|
|
+ Pid = erlang:spawn(
|
|
|
|
+ fun() ->
|
|
|
|
+ transition([])
|
|
|
|
+ end),
|
|
|
|
+
|
|
|
|
+ Script = ["var transition = {pid: '", wf:pickle(Pid), "', ",
|
|
|
|
+ "port:'", nitro:to_list(application:get_env(n4u, websocket_port, application:get_env(n4u, port, 8000))), "'}"],
|
|
|
|
+ erlang:put(script, Script),
|
|
|
|
+
|
|
|
|
+ Ctx = n4u_cx:init_context(Req),
|
|
|
|
+ Ctx1 = n4u_cx:fold(init, Ctx#cx.handlers, Ctx),
|
|
|
|
+
|
|
|
|
+ erlang:put(actions, Ctx1#cx.actions),
|
|
|
|
+ erlang:put(context, Ctx1),
|
|
|
|
+
|
|
|
|
+ Elements = try (Ctx1#cx.module):main()
|
|
|
|
+ catch E:R:Stk ->
|
|
|
|
+ wf:error(?MODULE, "run main:~n ~p~n ~p~n ~p~n", [E, R, Stk]),
|
|
|
|
+ wf:error_page(E, R, Stk)
|
|
|
|
+ end,
|
|
|
|
+
|
|
|
|
+ Html = nitro:render(Elements),
|
|
|
|
+ Actions = erlang:get(actions),
|
|
|
|
+ Pid ! {'INIT', Actions},
|
|
|
|
+ Ctx2 = n4u_cx:fold(finish, Ctx#cx.handlers, erlang:get(context)),
|
|
|
|
+ Req2 = wf:response(Html, set_cookies(wf:cookies(), Ctx2#cx.req)),
|
|
|
|
+ wf:info(?MODULE, "Cookies Req: ~p~n", [Req2]),
|
|
|
|
+ %erlang:exit(Pid, {}),
|
|
|
|
+ wf:reply(erlang:get(status), Req2). % {ok, New_Req}
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+set_cookies([], Req)-> Req;
|
|
|
|
+set_cookies([{Name, Value, Path, TTL}|Cookies], Req)->
|
|
|
|
+ set_cookies(Cookies, wf:cookie_req(Name, Value, Path, TTL, Req)).
|
|
|
|
+
|