import be.nikiroo.fanfix.data.Story;
import be.nikiroo.fanfix.library.web.WebLibraryServerIndex;
import be.nikiroo.fanfix.reader.TextOutput;
-import be.nikiroo.utils.CookieUtils;
import be.nikiroo.utils.IOUtils;
import be.nikiroo.utils.Image;
+import be.nikiroo.utils.LoginResult;
import be.nikiroo.utils.NanoHTTPD;
import be.nikiroo.utils.NanoHTTPD.IHTTPSession;
import be.nikiroo.utils.NanoHTTPD.Response;
import be.nikiroo.utils.Version;
public class WebLibraryServer implements Runnable {
- static private String VIEWER_URL_BASE = "/view/story/";
- static private String VIEWER_URL = VIEWER_URL_BASE + "{luid}/{chap}/{para}";
- static private String STORY_URL_BASE = "/story/";
- static private String STORY_URL = STORY_URL_BASE + "{luid}/{chap}/{para}";
- static private String STORY_URL_COVER = STORY_URL_BASE + "{luid}/cover";
- static private String LIST_URL = "/list/";
-
- private class LoginResult {
- private boolean success;
+ private class WLoginResult extends LoginResult {
private boolean rw;
private boolean wl;
private boolean bl;
- private String wookie;
- private String token;
- private boolean badLogin;
- private boolean badToken;
-
- public LoginResult(String who, String key, String subkey,
- boolean success, boolean rw, boolean wl, boolean bl) {
- this.success = success;
+
+ public WLoginResult(boolean badLogin, boolean badCookie) {
+ super(badLogin, badCookie);
+ }
+
+ public WLoginResult(String who, String key, String subkey, boolean rw,
+ boolean wl, boolean bl) {
+ super(who, key, subkey, (rw ? "|rw" : "") + (wl ? "|wl" : "")
+ + (bl ? "|bl" : "") + "|");
this.rw = rw;
this.wl = wl;
this.bl = bl;
- this.wookie = CookieUtils.generateCookie(who + key, 0);
-
- String opts = "";
- if (rw)
- opts += "|rw";
- if (!wl)
- opts += "|wl";
- if (!bl)
- opts += "|bl";
-
- this.token = wookie + "~"
- + CookieUtils.generateCookie(wookie + subkey + opts, 0)
- + "~" + opts;
- this.badLogin = !success;
}
- public LoginResult(String token, String who, String key,
+ public WLoginResult(String cookie, String who, String key,
List<String> subkeys) {
-
- if (token != null) {
- String hashes[] = token.split("~");
- if (hashes.length >= 2) {
- String wookie = hashes[0];
- String rehashed = hashes[1];
- String opts = hashes.length > 2 ? hashes[2] : "";
-
- if (CookieUtils.validateCookie(who + key, wookie)) {
- if (subkeys == null) {
- subkeys = new ArrayList<String>();
- }
- subkeys = new ArrayList<String>(subkeys);
- subkeys.add("");
-
- for (String subkey : subkeys) {
- if (CookieUtils.validateCookie(
- wookie + subkey + opts, rehashed)) {
- this.wookie = wookie;
- this.token = token;
- this.success = true;
-
- this.rw = opts.contains("|rw");
- this.wl = !opts.contains("|wl");
- this.bl = !opts.contains("|bl");
- }
- }
- }
- }
-
- this.badToken = !success;
- }
-
- // No token -> no bad token
- }
-
- public boolean isSuccess() {
- return success;
+ super(cookie, who, key, subkeys,
+ subkeys == null || subkeys.isEmpty());
}
public boolean isRw() {
- return rw;
+ return getOption().contains("|rw|");
}
public boolean isWl() {
- return wl;
+ return getOption().contains("|wl|");
}
public boolean isBl() {
- return bl;
- }
-
- public String getToken() {
- return token;
- }
-
- public boolean isBadLogin() {
- return badLogin;
- }
-
- public boolean isBadToken() {
- return badToken;
+ return getOption().contains("|bl|");
}
}
cookies.put(cookie, session.getCookies().read(cookie));
}
- LoginResult login = null;
+ WLoginResult login = null;
Map<String, String> params = session.getParms();
String who = session.getRemoteHostName()
+ session.getRemoteIpAddress();
login = login(who, params.get("password"),
params.get("login"));
} else {
- String token = cookies.get("token");
- login = login(who, token);
+ String cookie = cookies.get("cookie");
+ login = login(who, cookie);
}
if (login.isSuccess()) {
- // refresh token
- session.getCookies().set(new Cookie("token",
- login.getToken(), "30; path=/"));
+ // refresh cookie
+ session.getCookies().set(new Cookie("cookie",
+ login.getCookie(), "30; path=/"));
// set options
String optionName = params.get("optionName");
}
Response rep = null;
- if (!login.isSuccess() && (uri.equals("/") //
- || uri.startsWith(STORY_URL_BASE) //
- || uri.startsWith(VIEWER_URL_BASE) //
- || uri.startsWith(LIST_URL))) {
+ if (!login.isSuccess() && WebLibraryUrls.isSupportedUrl(uri)) {
rep = loginPage(login, uri);
}
if (rep == null) {
try {
- if (uri.equals("/")) {
- rep = root(session, cookies, login);
- } else if (uri.startsWith(LIST_URL)) {
- rep = getList(uri, login);
- } else if (uri.startsWith(STORY_URL_BASE)) {
- rep = getStoryPart(uri, login);
- } else if (uri.startsWith(VIEWER_URL_BASE)) {
- rep = getViewer(cookies, uri, login);
- } else if (uri.equals("/logout")) {
- session.getCookies().delete("token");
- cookies.remove("token");
- rep = loginPage(login, uri);
+ if (WebLibraryUrls.isSupportedUrl(uri)) {
+ if (WebLibraryUrls.INDEX_URL.equals(uri)) {
+ rep = root(session, cookies, login);
+ } else if (WebLibraryUrls.VERSION_URL.equals(uri)) {
+ rep = newFixedLengthResponse(Status.OK,
+ MIME_PLAINTEXT,
+ Version.getCurrentVersion().toString());
+ } else if (WebLibraryUrls.isListUrl(uri)) {
+ rep = getList(uri, login);
+ } else if (WebLibraryUrls.isStoryUrl(uri)) {
+ rep = getStoryPart(uri, login);
+ } else if (WebLibraryUrls.isViewUrl(uri)) {
+ rep = getViewer(cookies, uri, login);
+ } else if (WebLibraryUrls.LOGOUT_URL.equals(uri)) {
+ session.getCookies().delete("cookie");
+ cookies.remove("cookie");
+ rep = loginPage(new WLoginResult(false, false),
+ uri);
+ } else {
+ getTraceHandler().error(
+ "Supported URL was not processed: "
+ + uri);
+ rep = newFixedLengthResponse(
+ Status.INTERNAL_ERROR,
+ NanoHTTPD.MIME_PLAINTEXT,
+ "An error happened");
+ }
} else {
if (uri.startsWith("/"))
uri = uri.substring(1);
}
rep = newChunkedResponse(Status.OK, mimeType,
in);
- } else {
- getTraceHandler().trace("404: " + uri);
}
- }
- if (rep == null) {
- rep = newFixedLengthResponse(Status.NOT_FOUND,
- NanoHTTPD.MIME_PLAINTEXT, "Not Found");
+ if (rep == null) {
+ getTraceHandler().trace("404: " + uri);
+ rep = newFixedLengthResponse(Status.NOT_FOUND,
+ NanoHTTPD.MIME_PLAINTEXT, "Not Found");
+ }
}
} catch (Exception e) {
Instance.getInstance().getTraceHandler().error(
this.tracer = tracer;
}
- private LoginResult login(String who, String token) {
- List<String> subkeys = Instance.getInstance().getConfig().getList(
- Config.SERVER_ALLOWED_SUBKEYS, new ArrayList<String>());
+ private WLoginResult login(String who, String cookie) {
+ List<String> subkeys = Instance.getInstance().getConfig()
+ .getList(Config.SERVER_ALLOWED_SUBKEYS);
String realKey = Instance.getInstance().getConfig()
- .getString(Config.SERVER_KEY, "");
+ .getString(Config.SERVER_KEY);
- return new LoginResult(token, who, realKey, subkeys);
+ return new WLoginResult(cookie, who, realKey, subkeys);
}
// allow rw/wl
- private LoginResult login(String who, String key, String subkey) {
+ private WLoginResult login(String who, String key, String subkey) {
String realKey = Instance.getInstance().getConfig()
.getString(Config.SERVER_KEY, "");
subkey = subkey == null ? "" : subkey;
if (!realKey.equals(key)) {
- return new LoginResult(null, null, null, false, false, false,
- false);
+ return new WLoginResult(true, false);
}
// defaults are true (as previous versions without the feature)
rw = Instance.getInstance().getConfig().getBoolean(Config.SERVER_RW,
rw);
- if (!subkey.isEmpty()) {
- List<String> allowed = Instance.getInstance().getConfig()
- .getList(Config.SERVER_ALLOWED_SUBKEYS);
- if (allowed != null && allowed.contains(subkey)) {
- if ((subkey + "|").contains("|rw|")) {
- rw = true;
- }
- if ((subkey + "|").contains("|wl|")) {
- wl = false; // |wl| = bypass whitelist
- }
- if ((subkey + "|").contains("|bl|")) {
- bl = false; // |bl| = bypass blacklist
- }
- } else {
- return new LoginResult(null, null, null, false, false, false,
- false);
+
+ List<String> allowed = Instance.getInstance().getConfig().getList(
+ Config.SERVER_ALLOWED_SUBKEYS, new ArrayList<String>());
+
+ if (!allowed.isEmpty()) {
+ if (!allowed.contains(subkey)) {
+ return new WLoginResult(true, false);
+ }
+
+ if ((subkey + "|").contains("|rw|")) {
+ rw = true;
+ }
+ if ((subkey + "|").contains("|wl|")) {
+ wl = false; // |wl| = bypass whitelist
+ }
+ if ((subkey + "|").contains("|bl|")) {
+ bl = false; // |bl| = bypass blacklist
}
}
- return new LoginResult(who, key, subkey, true, rw, wl, bl);
+ return new WLoginResult(who, key, subkey, rw, wl, bl);
}
- private Response loginPage(LoginResult login, String uri) {
+ private Response loginPage(WLoginResult login, String uri) {
StringBuilder builder = new StringBuilder();
appendPreHtml(builder, true);
if (login.isBadLogin()) {
builder.append("<div class='error'>Bad login or password</div>");
- } else if (login.isBadToken()) {
+ } else if (login.isBadCookie()) {
builder.append("<div class='error'>Your session timed out</div>");
}
- if (uri.equals("/logout")) {
- uri = "/";
+ if (WebLibraryUrls.LOGOUT_URL.equals(uri)) {
+ uri = WebLibraryUrls.INDEX_URL;
}
builder.append(
NanoHTTPD.MIME_HTML, builder.toString());
}
- protected Response getList(String uri, LoginResult login)
+ protected Response getList(String uri, WLoginResult login)
throws IOException {
- if (uri.equals("/list/luids")) {
+ if (WebLibraryUrls.LIST_URL_METADATA.equals(uri)) {
List<JSONObject> jsons = new ArrayList<JSONObject>();
for (MetaData meta : metas(login)) {
jsons.add(JsonIO.toJson(meta));
}
private Response root(IHTTPSession session, Map<String, String> cookies,
- LoginResult login) throws IOException {
+ WLoginResult login) throws IOException {
BasicLibrary lib = Instance.getInstance().getLibrary();
MetaResultList result = new MetaResultList(metas(login));
StringBuilder builder = new StringBuilder();
builder.append("<div class='book_line'>");
builder.append("<a href='");
- builder.append(getViewUrl(meta.getLuid(), null, null));
+ builder.append(
+ WebLibraryUrls.getViewUrl(meta.getLuid(), null, null));
builder.append("'");
builder.append(" class='link'>");
// /story/luid/cover <-- image
// /story/luid/metadata <-- json
// /story/luid/json <-- json, whole chapter (no images)
- private Response getStoryPart(String uri, LoginResult login) {
+ private Response getStoryPart(String uri, WLoginResult login) {
String[] cover = uri.split("/");
int off = 2;
}
private Response getViewer(Map<String, String> cookies, String uri,
- LoginResult login) {
+ WLoginResult login) {
String[] cover = uri.split("/");
int off = 2;
String disabledZoomHeight = "";
if (paragraph <= 0) {
- first = getViewUrl(luid, 0, null);
- previous = getViewUrl(luid, (Math.max(chapter - 1, 0)), null);
- next = getViewUrl(luid,
+ first = WebLibraryUrls.getViewUrl(luid, 0, null);
+ previous = WebLibraryUrls.getViewUrl(luid,
+ (Math.max(chapter - 1, 0)), null);
+ next = WebLibraryUrls.getViewUrl(luid,
(Math.min(chapter + 1, story.getChapters().size())),
null);
- last = getViewUrl(luid, story.getChapters().size(), null);
+ last = WebLibraryUrls.getViewUrl(luid,
+ story.getChapters().size(), null);
StringBuilder desc = new StringBuilder();
if (chapter >= story.getChapters().size())
disabledRight = " disabled='disbaled'";
} else {
- first = getViewUrl(luid, chapter, 1);
- previous = getViewUrl(luid, chapter,
+ first = WebLibraryUrls.getViewUrl(luid, chapter, 1);
+ previous = WebLibraryUrls.getViewUrl(luid, chapter,
(Math.max(paragraph - 1, 1)));
- next = getViewUrl(luid, chapter,
+ next = WebLibraryUrls.getViewUrl(luid, chapter,
(Math.min(paragraph + 1, chap.getParagraphs().size())));
- last = getViewUrl(luid, chapter, chap.getParagraphs().size());
+ last = WebLibraryUrls.getViewUrl(luid, chapter,
+ chap.getParagraphs().size());
if (paragraph <= 1)
disabledLeft = " disabled='disbaled'";
// First -> previous *chapter*
if (chapter > 0)
disabledLeft = "";
- first = getViewUrl(luid, (Math.max(chapter - 1, 0)), null);
+ first = WebLibraryUrls.getViewUrl(luid,
+ (Math.max(chapter - 1, 0)), null);
if (paragraph <= 1) {
previous = first;
}
javascript, //
next, //
zoomStyle, //
- getStoryUrl(luid, chapter, paragraph)));
+ WebLibraryUrls.getStoryUrl(luid, chapter,
+ paragraph)));
} else {
content.append(String.format("" //
+ "<div class='viewer text'>%s</div>", //
// List of chap/para links
- appendItemA(builder, 3, getViewUrl(luid, 0, null), "Description",
- paragraph == 0 && chapter == 0);
+ appendItemA(builder, 3, WebLibraryUrls.getViewUrl(luid, 0, null),
+ "Description", paragraph == 0 && chapter == 0);
if (paragraph > 0) {
for (int i = 1; i <= chap.getParagraphs().size(); i++) {
- appendItemA(builder, 3, getViewUrl(luid, chapter, i),
+ appendItemA(builder, 3,
+ WebLibraryUrls.getViewUrl(luid, chapter, i),
"Image " + i, paragraph == i);
}
} else {
chapName += ": " + c.getName();
}
- appendItemA(builder, 3, getViewUrl(luid, i, null), chapName,
+ appendItemA(builder, 3,
+ WebLibraryUrls.getViewUrl(luid, i, null), chapName,
chapter == i);
i++;
return "";
}
- private String getViewUrl(String luid, Integer chap, Integer para) {
- return VIEWER_URL //
- .replace("{luid}", luid) //
- .replace("/{chap}", chap == null ? "" : "/" + chap) //
- .replace("/{para}",
- (chap == null || para == null) ? "" : "/" + para);
- }
-
- private String getStoryUrl(String luid, int chap, Integer para) {
- return STORY_URL //
- .replace("{luid}", luid) //
- .replace("{chap}", Integer.toString(chap)) //
- .replace("{para}", para == null ? "" : Integer.toString(para));
- }
-
- private String getStoryUrlCover(String luid) {
- return STORY_URL_COVER //
- .replace("{luid}", luid);
- }
-
- private boolean isAllowed(MetaData meta, LoginResult login) {
+ private boolean isAllowed(MetaData meta, WLoginResult login) {
if (login.isWl() && !whitelist.isEmpty()
&& !whitelist.contains(meta.getSource())) {
return false;
return true;
}
- private List<MetaData> metas(LoginResult login) throws IOException {
+ private List<MetaData> metas(WLoginResult login) throws IOException {
BasicLibrary lib = Instance.getInstance().getLibrary();
List<MetaData> metas = new ArrayList<MetaData>();
for (MetaData meta : lib.getList().getMetas()) {
return metas;
}
- private MetaData meta(String luid, LoginResult login) throws IOException {
+ private MetaData meta(String luid, WLoginResult login) throws IOException {
BasicLibrary lib = Instance.getInstance().getLibrary();
MetaData meta = lib.getInfo(luid);
if (!isAllowed(meta, login))
return meta;
}
- private Image getCover(String luid, LoginResult login) throws IOException {
+ private Image getCover(String luid, WLoginResult login) throws IOException {
MetaData meta = meta(luid, login);
if (meta != null) {
BasicLibrary lib = Instance.getInstance().getLibrary();
}
// NULL if not whitelist OK or if not found
- private Story story(String luid, LoginResult login) throws IOException {
+ private Story story(String luid, WLoginResult login) throws IOException {
synchronized (storyCache) {
if (storyCache.containsKey(luid)) {
Story story = storyCache.get(luid);