Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

193
LINES

< > BotCompany Repo | #1021844 // Gazelle Web Server v1 [backup]

JavaX source code (Dynamic Module) [tags: use-pretranspiled] - run with: Stefan's OS

Uses 911K of libraries. Click here for Pure Java version (13346L/80K).

!7

cmodule GazelleWebServer > DynPrintLogAndEnabled {
  transient MyHTTPD server;
  new Set<S> authedCookies;
  
  void start() ctex {
    super.start();
    if (!enabled) ret;
    
    dm_useLocalMechListCopies();
    
    server = new MyHTTPD(80);
    server.serveFunction = func(S uri, SS parms) {
      serve(uri, parms)
    };
    server.start();
    print("HTTP server started on port " + server.getPort());
  }
  
  void cleanMeUp {
    server.stop();
    server = null;
  }
  
  O serve(S uri, SS params) {
    new Matches m;
    
    S cookie = serveHttp_cookieHandling();
    bool authed = nempty(cookie) && syncContains(authedCookies, cookie);
    print("Cookie: " + cookie + ", authed: " + authed);
    S master = trim(loadTextFile(javaxSecretDir("gazelle-master-pw")));
    S attempt = params.get('_pass);
    if (nempty(attempt) && nempty(cookie) && nempty(master)) {
      if (eq(attempt, master)) {
        print("Login SUCCEEDED");
        syncAdd(authedCookies, cookie);
        change();
        authed = true;
      } else
        print("Login FAILED");
    }
    
    if (eq(uri, "/favicon.ico"))
      ret serveFile(loadLibrary(#1400189), faviconMimeType());
      
    if (eq(uri, "/login"))
      ret nempty(master) ? hpostform(hpasswordfield('_pass)) : "No master PW";
    
    O[] bodyParams = litobjectarray(style := "font-family: Roboto Mono; " + (authed ? "background-color: #FFFF88" : ""));
    
    if (swic(uri, "/texts/", m)) {
      S textID = m.rest();
      if (!possibleMD5(textID)) ret serve404();
      ret serveTextFileAsUTF8(javaxDataDir("Gazelle Texts/" + textID));
    }
      
    if (swic(uri, "/rule/", m)) {
      S ruleID = assertGlobalID(m.rest());
      PairS textAndComment = unnull(dm_textAndCommentForRule(ruleID));
      L feedback = dm_gazelle_feedbackForRule(ruleID);
      L applications = dm_gazelle_applicationsForRule(ruleID);
      Map<S, O> feedbackByContext = indexByFieldNotNull context(feedback);
      S title = "Rule " + ruleID;
      bool showStruct = eq("1", params.get('struct));
      L list = cloneList(feedback);
      for (O o : applications)
        if (!containsKey(feedbackByContext, getString context(o)))
          list.add(o);
          
      // add comments
      
      for (S applicationID, S text : subMapStartingWith_dropPrefix(params, "comment_")) {
        continue if empty(text = trim(text));
        if (!authed) text = "[anon] " + text;
        O app = findByField(list, globalID := applicationID);
        print("Processing comment for " + applicationID + " - " + app);
        if (app == null) continue;
        Set<S> comments = asSet(tlft(getString comments(app)));
        if (!contains(comments, text))
          call(app, '_setField, comments := appendWithNewLine(getString comments(app), text));
      }
      
      // Serve Rule & Applications & Feedback
      
      ret hhtml_head_title_body(title + " | Gazelle",
        hprelude() +
        heading(htmlEncode2(title))
        + h3("Rule")
        + hblock(textAndComment.a)
        + (nempty(textAndComment.b) ? h3("Comments") + hblock(textAndComment.b) : "")
        + h3("Feedback")
        + htmlTable2(map(list, func(O o) -> Map {
          litorderedmap(
            "Judgement" := getString judgement(o),
            "Rewritten Rule" := getString_htmlEncode modifiedRule(o),
            "Generated Output" := getString_htmlEncode outText(o),
            "Mapping" := dropPrefix("cimap", getString_htmlEncode varMap(o)),
            "Context" := getString_htmlEncode context(o),
            "Comments" := hform(
              appendIfNempty(nlToBr(rtrim(getString_htmlEncode comments(o))), "<br>")
              + htextfield("comment_" + getString globalID(o))),
            "Struct" := showStruct ? getString matchedRuleStruct(o) : null)
        }), tdParams := litobjectarray(align := 'center, valign := 'top), htmlEncode := false), bodyParams);
    }
    
    if (eq(uri, "/commands"))
      ret hhtml_head_title_body("Commands | Gazelle",
        hprelude() +
        linesLL(heading("Commands"),
          h3("!eval"),
        
          p([[You can evaluate Java code directly through Discord.
          Unless you are specifically authorized, only a ]] + ahref(rawSelfLink("safeIdentifiers"), "safe subset
          of identifiers") + " is allowed."),
          
          p("Example: " + tt("!eval 1+2")),
          p("In rare cases " + tt("!eval") + " may fail and you need to type " + tt("!real-eval") + " instead (which invokes an actual Java compiler).")), bodyParams);

    if (eq(uri, "/safeIdentifiers"))
      ret hhtml_head_title_body("Safe Java Identifiers | Gazelle",
        hprelude() +
        linesLL(
          heading("Safe Java(X) identifiers for !eval"),
          hpre(lines(sortedIC(codeAnalysis_allSafeIdentifiers())))), bodyParams);
          
    if (!eq(uri, "/"))
      ret serve404();
    
    //final Map<S, Int> feedbackStats = dm_gazelle_feedbackStats();
    final Map<S, Int> feedbackStats2 = dm_gazelle_feedbackStatsByJudgement();
    final Map<S, Int> feedbackStats3 = dm_gazelle_feedbackStatsForNonJudged();
    
    // Home Page
    
    L<T3<S>> rules = dm_allRulesFromRulesModuleWithCommentsAndIDs();
      // dm_gazelle_allRulesWithComment("discord");
    
    ret hhtml_head_title_body("Gazelle - Next-Gen Chat Bot",
      hprelude() +
      hopeningTag link(rel :="icon", href := "/favicon.ico?v=2") +
      hcenter(
        p(b("GAZELLE 2019", style := "font-size: 5em")) +
        p(hsnippetimg(#1101500, height := 150, title := "Gazelle")) +
        p(span("<b>Hello! I am a next-generation chat bot in training.</b>", style := "font-size: 1.4em") + "<br>"
          + span(targetBlank("https://BotCompany.de", "Maker.") + " "
          + targetBlank("https://slides.com/stefanreich/how-about-thinking-machines/", "Slides.") + " "
          + targetBlank("https://discordapp.com/invite/SEAjPqk", b("Join my Discord server!")), style := "font-size: 1.2em"))
        + p(ahref(rawSelfLink("commands"), "Commands."))
        
        + h3("Rules (" + l(rules) + ")")
      + htmlTable2(mapReversed(rules,
        func(T3<S> t) -> SS {
          S ruleID = t.c;
          ret litorderedmap(
            "Rule ID" := htmlEncode2(ruleID),
            "Rule Text" := htmlEncode_nlToBr(t.a),
            "Comments" := nlToBr(
              mapEachLine(/*withoutLine("discord",*/ t.b/*)*/, func(S s) -> S {
                new Matches m;
                if "use helper table mech list *"
                  ret "use helper table mech list " +
                    ahref(neatMechListURL($1), m.get(0));
                ret s;
              })),
            "Feedback" := ahref(rawSelfLink("rule/" + ruleID),
              toInt(feedbackStats2.get(ruleID + "/good"))
                + " / " +
              toInt(feedbackStats3.get(ruleID))
                + " / " + 
              toInt(feedbackStats2.get(ruleID + "/bad"))));
        }),
          htmlEncode := false,
          paramsByColName := litmap("Feedback" := litobjectarray(align := 'center)),
          tdParams := litobjectarray(valign := 'top)
          )), bodyParams);
  }
}

sS rawSelfLink(S uri) { ret addSlashPrefix(uri); }

sS heading(O contents) {
  ret h2(ahref(rawSelfLink(""), "Gazelle") + " | " + contents;
}

sS hprelude() {
  ret [[<link href="https://fonts.googleapis.com/css?family=Roboto+Mono" rel="stylesheet">]] +
    hmobilefix();
}

sS hblock(S s) {
  ret htmlEncode_nlToBr(s);
}

Author comment

Began life as a copy of #1021679

download  show line numbers  debug dex  old transpilations   

Travelled to 7 computer(s): bhatertpkbcr, cfunsshuasjs, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt

No comments. add comment

-
Snippet ID: #1021844
Snippet name: Gazelle Web Server v1 [backup]
Eternal ID of this version: #1021844/1
Text MD5: 7cce4d6fac56d4ecbfd4c64f2b9b2c5d
Transpilation MD5: 8ac887e715fc02696c5c7e83ae3c78da
Author: stefan
Category: javax / stefan's os / a.i. / web
Type: JavaX source code (Dynamic Module)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-03-02 13:18:45
Source code size: 7657 bytes / 193 lines
Pitched / IR pitched: No / No
Views / Downloads: 295 / 353
Referenced in: