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

708
LINES

< > BotCompany Repo | #1024297 // agi.blue source [backup before slices 2]

JavaX module (desktop)

Download Jar.

1  
!7
2  
3  
// See #1023660 for the older 99 lines version
4  
5  
concept PhysicalSlice {
6  
  new Ref<Page> slicePage; // page that describes this slice
7  
}
8  
9  
concept Page {
10  
  new Ref<PhysicalSlice> slice; // where are we stored
11  
  S globalID = aGlobalID();
12  
  S url, q;
13  
}
14  
15  
concept Entry {
16  
  S globalID = aGlobalID();
17  
  new Ref<Page> page;
18  
  int count;
19  
  S key, value;
20  
  S ip;
21  
  new Ref<Signer> signer;
22  
}
23  
24  
concept Signer {
25  
  S globalID = aGlobalID();
26  
  S publicKey;
27  
  bool trusted;
28  
  S approvedBy;
29  
}
30  
31  
concept Session {
32  
  S cookie;
33  
  Page slicePage;
34  
}
35  
36  
static SS searchTypeToText = litmap(
37  
  leven := "Leven",
38  
  literal := "Literal",
39  
  scored := "Scored");
40  
41  
static int displayLength = 140;
42  
static int sideDisplayLength = 50; // when in side bar
43  
static int searchResultsToShow = 50;
44  
sS sideSearchType = 'literal;
45  
46  
static int lines;
47  
sbool asyncSearch = false;
48  
sbool allowMultipleCasesInValues = true;
49  
sbool showSliceSelector = false;
50  
static ConceptFieldIndexDesc idx_latestEntries, idx_latestCreatedPages, idx_latestChangedPages;
51  
52  
p {
53  
  dbIndexingCI(Page, 'url, Page, 'q, Entry, 'key, Entry, 'value);
54  
  dbIndexing(Signer, 'publicKey);
55  
  dbIndexing(Session, 'cookie);
56  
  
57  
  // legacy conversions!
58  
  //for (Page p) cset(p, q := p.url);
59  
  moveSlicelessPagesToTheWildSlice();
60  
61  
  idx_latestCreatedPages = new ConceptFieldIndexDesc(Page, 'created);
62  
  idx_latestChangedPages = new ConceptFieldIndexDesc(Page, '_modified);
63  
  idx_latestEntries = new ConceptFieldIndexDesc(Entry, 'created);
64  
  
65  
  // Approve this machine's key
66  
  PKIKeyPair machineKey = agiBot_trustedKeyForMachine();
67  
  if (machineKey != null) {
68  
    print("Approving this machine's key: " + machineKey.publicKey);
69  
    cset(uniq_sync(Signer, publicKey := machineKey.publicKey), trusted := true, approvedBy := "local");
70  
  }
71  
  
72  
  lines = countLines(mySource());
73  
}
74  
75  
// DB functions
76  
77  
sbool hasPage(S q) { ret hasConceptWhereIC(Page, +q); }
78  
sS getValue(Page page, S key) {
79  
  ret page == null || empty(key) ? null : getString value(highestByField count(objectsWhereIC(findBackRefs(page, Entry), +key)));
80  
}
81  
sS getValue(S page, S key) {
82  
  ret getValue(findPageFromQ(page), key);
83  
}
84  
sS pageDisplayName(Page page) {
85  
  /*S name = getValue(page, "read as");
86  
  bool unnaturalName = nempty(name) && !eq(makeAGIDomain(name), page.url);
87  
  ret unnaturalName ? name + " " + squareBracketed(page.url) : or2(name, unpackAGIDomainOpt(page.url));*/
88  
  ret page.q;
89  
}
90  
91  
// Serve page
92  
93  
set flag NoNanoHTTPD. html {
94  
  ret new Request().serve(uri, params);
95  
}
96  
97  
sclass Request {
98  
  S cookie;
99  
  Session session;
100  
  S uri;
101  
  SS params;
102  
103  
  // should also work for standalone
104  
  bool isHomeDomain() {
105  
    S domain = domain();
106  
    ret eqic(domain, "www.agi.blue") || !ewic(domain, ".agi.blue");
107  
  }
108  
  
109  
  O serve(S uri, SS params) {
110  
    this.uri = uri;
111  
    this.params = params;
112  
    new Matches m;
113  
    
114  
    print(uri + " ? " + unnull(subBot_query()));
115  
    
116  
    cookie = cookieFromUser();
117  
    if (cookie != null)
118  
      session = uniq_sync(Session, +cookie);
119  
    else
120  
      session = unlistedWithValues(Session);
121  
      
122  
    // Check for special URIs
123  
124  
    if (swic(uri, "/bot/")) ret serveBot();
125  
    
126  
    // eleu appends a slash to the URI if it's a single identifier, so we drop it again
127  
    S uri2 = dropTrailingSlash(uri);
128  
    
129  
    if (eqic(uri2, "/search")) ret serveScoredSearch();
130  
    if (eqic(uri2, "/literalSearch")) ret serveLiteralSearch();
131  
    if (eqic(uri2, "/levenSearch")) ret serveLevenSearch();
132  
    
133  
    if (eqic(uri2, "/query")) ret serveQueryPage();
134  
    
135  
    S selectSlice = params.get('slice);
136  
    if (nempty(selectSlice))
137  
      cset(session, slicePage := pageFromQ(selectSlice));
138  
139  
    S q = params.get('q);
140  
    S domain = or2(params.get('domain), domain());
141  
    
142  
    S raw = firstKeyWithValue("", params); // agi.blue?something
143  
    if (nempty(raw) && empty(q)) q = raw;
144  
    /*if (nempty(q)) {
145  
      domain = makeAGIDomain(q);
146  
      if (l(domain) > maximumDomainPartLength()) // escape with "domain="
147  
        ret hrefresh("http://agi.blue/" + hquery(+domain, key := "read as", value := q));
148  
      ret hrefresh("http://" + domain + (eq(q, domain) ? "" : "/" +  hquery(key := "read as", value := q)));
149  
      //uri = "/"; replaceMapWithParams(params, key := "read as", value := q);
150  
    }*/
151  
    S url = domain + dropTrailingSlash(uri);
152  
    
153  
    // domain to query
154  
    //if (empty(q)) q = url;
155  
    if (empty(q)) q = agiBlue_urlToQuery(url);
156  
    
157  
    Page page, bool newPage = unpair uniqCI2_sync(Page, +q);
158  
    if (newPage) dbLog("New page", +q);
159  
    //printStructs(+params, +raw, +q);
160  
  
161  
    S top = hcomment("cookie: " + takeFirst(4, session.cookie))
162  
      + hSilentComputatorWithFlag("agi.blue: " + q)
163  
      + p(ahref("http://agi.blue",
164  
        //hsnippetimg(#1101682, width := 565/5, height := 800/5, title := "Robot by Peerro @ DeviantArt")
165  
        hsnippetimg(#1101778, width := 96, height := 96, title := "agi.blue - a database for everything")
166  
      ))
167  
        + p(small(b(ahref("http://agi.blue", "agi.blue"))
168  
        + " " /*+ htooltip("It's very new.", "alpha")*/ + " | " + targetBlank(progLink(), "source code") + " of this web site (" + nLines(lines) + ") | " + targetBlank("https://gitter.im/agi-blue/community", "sponsor https?") + " | by " + targetBlank("https://BotCompany.de", "BC") + " | " + targetBlank("http://fiverr.tinybrain.de/", "Fiverr") + " | " + targetBlank("https://discordapp.com/invite/SEAjPqk", "Discord") + " | " + targetBlank("https://www.youtube.com/watch?v=b6jtRdV3Ev8", "Video")
169  
        + " | " + targetBlank("http://code.botcompany.de/1024233", "Notes")
170  
        + " | " + ahref("/query", "Query")
171  
      ));
172  
    
173  
    if (empty(params.get('q)) && empty(raw) && isHomeDomain()) {
174  
      L<Page> pages = sortedByFieldDesc _modified(list(Page)); // TODO: use index
175  
      int start = parseInt(params.get("start")), step = 100;
176  
      S nav = pageNav2("/", l(pages), start, step, "start");
177  
      ret hhtml2(hhead_title("agi.blue Overview") // SERVE HOME PAGE
178  
        + hbody(hfullcenterAndTopLeft(top
179  
          + hform(b("GIVE ME INPUT:") + "<br><br>" + htextinput('q, autofocus := true) + " " + hsubmit("Ask"))
180  
          + h1("agi.blue has " + nPages(countConcepts(Page)) + " and " + nEntries(countConcepts(Entry)))
181  
          + p(nav)
182  
          + p_nemptyLines(map(pageToHTMLLink(), subList(pages, start, start+step))),
183  
          !showSliceSelector ? "" : hform("Select reality slice: " + hselect_list(availableSlices(), getString q(session.slicePage), name := 'slice) + " " + hsubmit("Go"))
184  
        )));
185  
    }
186  
        
187  
    S key = trim(params.get('key)), value = trim(params.get('value));
188  
    L<Entry> entries = GetEntriesAndPost().go(page, params).entries;
189  
    
190  
    Set<S> get = asCISet(nempties(subBot_paramsAsMultiMap().get('get)));
191  
    //S get = params.get('get);
192  
    if (nempty(get))
193  
      ret serveJSON(collect value(llNotNulls(firstThat(entries, e -> get.contains(e.key)))));
194  
    
195  
    S key2 = key, value2 = value; if (nempty(key) && nempty(value)) key2 = value2 = ""; // input reset
196  
  
197  
    bool withHidden = eq(params.get('withHidden), "1");
198  
    new Set<Int> hide;
199  
    if (!withHidden) for (Entry e : entries) if (eqic(e.key, 'hide) && isSquareBracketedInt(e.value)) addAll(hide, e.count, parseInt(unSquareBracket(e.value)));
200  
    new MultiMap<Int, S> mmMeta;
201  
    for (Entry e : entries) if (isSquareBracketedInt(e.key)) mmMeta.put(parseInt(unSquareBracket(e.key)), e.value);
202  
    new MultiMap<S> mm;
203  
    for (Entry e : entries) mm.put(e.key, e.value);
204  
    
205  
    //S name = or2(/* ouch */ last(mm.get("read as")), /* end ouch */ unpackAGIDomain(page.url), page.url);
206  
    S name = page.q;
207  
    
208  
    // Find references
209  
    
210  
    L<Entry> refs = concatLists(conceptsWhereIC Entry(value := name),
211  
      conceptsWhereIC Entry(key := name));
212  
    Set<Page> refPages = asSet(ccollect page(refs));
213  
    refPages.remove(page); // don't list current page as reference
214  
    
215  
    // Search in page names (depending on default search type)
216  
    
217  
    L<Page> searchResults;
218  
    if (eq(sideSearchType, 'leven))
219  
      searchResults = levenSearch(page.q, max := 50);
220  
    else if (eq(sideSearchType, 'literal))
221  
      searchResults = literalSearch(page.q, max := 50);
222  
    else
223  
      searchResults = (L<Page>) dm_call('agiBlueSearch, 'search, page.q, maxResult := searchResultsToShow+1);
224  
    searchResults.remove(page);
225  
226  
    S mainContents =
227  
        top + h1(ahref_unstyled("http://" + url + hquery(+q), htmlEncode2(shorten(displayLength, name))) + (newPage ? " [huh????]" : ""))
228  
      + p_nemptyLines(map(entries, func(Entry e) -> S {
229  
        !withHidden && (hide.contains(e.count) || eqic(e.key, "read as") && eqic(e.value, name)) ? ""
230  
        : "[" + e.count + "] " +
231  
          renderThing(e.key, false) + ": " +
232  
          b(renderThing(e.value, cic(mmMeta.get(e.count), "is a URL")))
233  
        }))
234  
      + hpostform(h3("Add an entry")
235  
        + "Key: " + hinputfield(key := key2) + " Value: " + hinputfield(value := value2) + "<br><br>" + hsubmit("Add")
236  
        )
237  
        
238  
      + p(ahref("http://agi.blue/literalSearch" + hquery(q := page.q), "[literal search]", title := "Search pages with a name containing this page's name literally")
239  
       + " " +
240  
       ahref("http://agi.blue/levenSearch" + hquery(q := page.q), "[leven search 1]", title := "Search pages with a Levenshtein similarity of 1 containing this page's name literally")
241  
       + " " +
242  
       ahref("http://agi.blue/search" + hquery(q := page.q), "[scored search]", title := "Search pages with ScoredSearch"));
243  
        
244  
    S sideContents =
245  
      hform(b("GIVE ME INPUT:") + " "
246  
        + htextinput('q) + " "
247  
        + hsubmit("Ask", onclick := "document.getElementById('newInputForm').target = '';") + " "
248  
        + hsubmit("+Tab", title := "Ask and show result in a new tab", onclick := "document.getElementById('newInputForm').target = '_blank';"),
249  
        id := 'newInputForm)
250  
      
251  
      + h3("References (" + l(refPages) + ")")
252  
      
253  
      + p_nemptyLines_showFirst(10, map(pageToHTMLLink(displayLength := sideDisplayLength), refPages))
254  
      
255  
      + h3(searchTypeToText.get(sideSearchType) + " search results (" + (l(searchResults) >= searchResultsToShow ? searchResultsToShow + "+" : str(l(searchResults))) + ")")
256  
      
257  
      + p_nemptyLines_showFirst(searchResultsToShow, map(pageToHTMLLink(displayLength := sideDisplayLength), searchResults))
258  
      
259  
      + hdiv("", id := 'extraStuff);
260  
      
261  
    // TODO: sync search delivery with WebSocket creation
262  
    if (asyncSearch)
263  
      doLater(6.0, r { dm_call('agiBlueSearch, 'searchAndPost, page.q) });
264  
      
265  
    // serve a concept page
266  
    ret hhtml2(hhead_title(pageDisplayName(page)) + hbody(
267  
      tag('table, tr(
268  
        td(mainContents, align := 'center, valign := 'top) +
269  
        td(sideContents, align := 'right, valign := 'top)),
270  
        width := "100%", height := "100%")));
271  
  }
272  
  
273  
  O servePagesToBot(Iterable<Page> pages) {
274  
    ret serveListToBot(map(pageToMap(wrapMapAsParams(params)), pages));
275  
  }
276  
277  
  O serveListToBot(Collection l) {
278  
    if (nempty(params.get('max)))
279  
      l = takeFirst(parseInt(params.get('max)), l);
280  
    ret serveJSON(l);
281  
  }
282  
283  
  // uri starts with "/bot/"
284  
  O serveBot() {
285  
    S q = params.get('q);
286  
    
287  
    if (eqic(uri, "/bot/hello")) ret serveJSON("hello");
288  
    if (eqic(uri, "/bot/hasPage")) ret serveJSON(hasPage(q));
289  
    if (eqic(uri, "/bot/randomPageContaining")) {
290  
      assertNempty(q);
291  
      ret servePageToBot(random(filter(list(Page), p -> cic(p.q, q))), params);
292  
    }
293  
    if (eqic(uri, "/bot/allPages"))
294  
      ret servePagesToBot(list(Page));
295  
    if (eqic(uri, "/bot/allPagesStartingWith")) {
296  
      assertNempty(q);
297  
      ret servePagesToBot(filter(list(Page), p -> swic(p.q, q)));
298  
    }
299  
    if (eqic(uri, "/bot/allPagesEndingWith")) {
300  
      assertNempty(q);
301  
      ret servePagesToBot(filter(list(Page), p -> ewic(p.q, q)));
302  
    }
303  
    if (eqic(uri, "/bot/allPagesContaining")) {
304  
      assertNempty(q);
305  
      ret servePagesToBot(filter(list(Page), p -> cic(p.q, q)));
306  
    }
307  
    if (eqic(uri, "/bot/allPagesContainingRegexp")) {
308  
      assertNempty(q);
309  
      Pattern pat = regexpIC(q);
310  
      ret servePagesToBot(filter(list(Page), p -> regexpFindIC(pat, p.q)));
311  
    }
312  
    
313  
    if (eqicOneOf(uri, "/bot/postSigned", "/bot/makePhysicalSlice", "/bot/approveTrustRequest")) {
314  
      S text = rtrim(params.get('text));
315  
      S key = getSignerKey(text);
316  
      if (empty(key)) ret subBot_serve500("Please include your public key");
317  
      if (!isSignedWithKey(text, key)) ret subBot_serve500("Signature didn't verify");
318  
      text = dropLastTwoLines(text); // drop signer + sig line
319  
      
320  
      Signer signer = uniq_sync Signer(publicKey := key);
321  
      
322  
      if (eqic(uri, "/bot/makePhysicalSlice")) {
323  
        if (!signer.trusted) ret subBot_serve500("Untrusted signer");
324  
        Page page = findPageFromParams(jsonDecodeMap(text));
325  
        if (page == null) ret subBot_serve500("Page not found");
326  
        ret serveJSON(uniq2_sync(PhysicalSlice, slicePage := page).b ? "Slice made" : "Slice exists");
327  
      }
328  
    
329  
      if (eqic(uri, "/bot/postSigned")) {
330  
        new L out;
331  
        for (S line : tlft(text)) {
332  
          SS map = jsonDecodeMap(line);
333  
          new GetEntriesAndPost x;
334  
          x.signer = signer;
335  
          Page page = findOrMakePageFromParams(map);
336  
          if (page == null) continue with out.add("Invalid page reference");
337  
          x.go(page, map);
338  
          out.add(x.newEntry ? "Saved" : x.entry != null ? "Entry exists" : "Need key and value");
339  
        }
340  
        ret serveJSON(out);
341  
      }
342  
      
343  
      if (eqic(uri, "/bot/approveTrustRequest")) {
344  
        if (!signer.trusted) ret subBot_serve500("Untrusted signer");
345  
        Signer toApprove = conceptWhere Signer(publicKey := trim(text));
346  
        if (toApprove == null) ret subBot_serve500("Signer to approve not found");
347  
        cset(toApprove, trusted := true, approvedBy := signer.globalID);
348  
        ret serveJSON("Approved: " + trim(text));
349  
      }
350  
      
351  
      ret subBot_serve500("CONFUSION");
352  
    }
353  
    
354  
    if (eqic(uri, "/bot/post")) {
355  
      new GetEntriesAndPost x;
356  
      x.go(pageFromQ(q), params);
357  
      ret serveJSON(x.newEntry ? "Saved" : x.entry != null ? "Entry exists" : "Need key and value");
358  
    }
359  
    
360  
    if (eqic(uri, "/bot/entriesOnPage"))
361  
      ret serveJSON(map(entriesOnPage(findPageFromParams(params)), entryToMap(false)));
362  
  
363  
    if (eqic(uri, "/bot/lookup")) {
364  
      S key = params.get('key);
365  
      if (empty(key)) ret serveJSON("Need key");
366  
      S value = getValue(findPageFromParams(params), key);
367  
      ret serveJSON(empty(value) ? "" : litmap(+value));
368  
    }
369  
  
370  
    if (eqic(uri, "/bot/latestEntries"))
371  
      ret serveJSON(map(takeFirst(10, idx_latestEntries.objectIterator()), entryToMap(true)));
372  
    if (eqic(uri, "/bot/latestPages"))
373  
      ret serveJSON(map(takeFirst(10, idx_latestCreatedPages.objectIterator()), pageToMap()));
374  
    if (eqic(uri, "/bot/latestChangedPages"))
375  
      ret serveJSON(map(takeFirst(10, idx_latestChangedPages.objectIterator()), pageToMap()));
376  
      
377  
    if (eqic(uri, "/bot/totalPageCount"))
378  
      ret serveJSON(countConcepts(Page));
379  
    if (eqic(uri, "/bot/pageWithoutPhysicalSliceCount"))
380  
      ret serveJSON(countConceptsWhere(Page, slice := null));
381  
    if (eqic(uri, "/bot/physicalSliceCount"))
382  
      ret serveJSON(countConcepts(PhysicalSlice));
383  
    if (eqic(uri, "/bot/trustedSignersCount"))
384  
      ret serveJSON(countConcepts(Signer, trusted := true));
385  
      
386  
    if (eqic(uri, "/bot/valueSearch")) {
387  
      S value = params.get('value);
388  
      L<Entry> entries = conceptsWhereIC Entry(+value);
389  
      ret serveJSON(map(takeFirst(100, entries), entryToMap(true)));
390  
    }
391  
      
392  
    if (eqic(uri, "/bot/keyAndValueSearch")) {
393  
      S key = params.get('key), value = params.get('value);
394  
      Cl<Page> pages = pagesForKeyAndValue(key, value);
395  
      ret servePagesToBot(pages);
396  
    }
397  
    
398  
    if (eqic(uri, "/bot/keyValuePairsByPopularity")) {
399  
      L<PairS> pairs = map(list(Entry), e -> pair(e.key, e.value));
400  
      LPair<S, Int> pairs2 = multiSetTopPairs(ciMultiSet(map pairToUglyStringForCIComparison(pairs)));
401  
      ret serveJSON(map(pairs2, p -> {
402  
        S key, value = unpair pairFromUglyString(p.a);
403  
        ret litorderedmap(n := p.b, +key, +value);
404  
      }));
405  
    }
406  
    
407  
    if (eqic(uri, "/bot/allKeys"))
408  
      ret serveListToBot(distinctCIFieldValuesOfConcepts Entry('key));
409  
      
410  
    if (eqic(uri, "/bot/allKeysByPopularity"))
411  
      ret serveListToBot(mapMultiSetByPopularity(distinctCIFieldValuesOfConcepts_multiSet Entry('key), (key, n) -> litorderedmap(+n, +key)));
412  
      
413  
    if (eqic(uri, "/bot/dbSize"))
414  
      ret serveJSON(l(conceptsFile()));
415  
      
416  
    if (eqic(uri, "/bot/query")) {
417  
      S query = params.get('query);
418  
      L<ALQLLine> lines = agiBlue_parseQueryScript(query);
419  
      
420  
      SS vars = ciMap();
421  
      for (ALQLLine line : lines) {
422  
        if (line cast ALQLReturn)
423  
          ret serveJSON(ll(getOrKeep(vars, line.var)));
424  
        else if (line cast ALQLTriple) {
425  
          T3S t = line.triple;
426  
          t = tripleMap(t, s -> getOrKeep(vars, s));
427  
          Cl<Page> pages;
428  
          S var;
429  
          if (isDollarVar(t.c)) {
430  
            var = t.c;
431  
            if (isDollarVar(t.a)) {
432  
              if (isDollarVar(t.b)) todo(t);
433  
              Entry e = random(conceptsWhereCI Entry(key := t.b));
434  
              if (e == null) ret serveJSON("No results for " + var);
435  
              pages = pagesForKeyAndValue(t.b, t.c);
436  
              vars.put(t.a, e.page->q);
437  
              vars.put(t.c, e.value);
438  
              continue;
439  
            } else if (isDollarVar(t.b)) {
440  
              Page page = findPageFromQ(t.a);
441  
              Entry e = random(findBackRefs(page, Entry));
442  
              if (e == null) ret serveJSON("No results for " + var);
443  
              vars.put(t.b, e.key);
444  
              vars.put(t.c, e.value);
445  
              continue;
446  
            } else {
447  
              S val = getValue(t.a, t.b);
448  
              if (val == null) ret serveJSON("No results for " + var);
449  
              pages = ll(pageFromQ(val));
450  
            }
451  
          } else if (isDollarVar(t.b)) {
452  
            var = t.b;
453  
            if (isDollarVar(t.c)) todo(t);
454  
            if (isDollarVar(t.a)) {
455  
              L<Entry> entries = conceptsWhereCI Entry(value := t.c);
456  
              if (empty(entries)) ret serveJSON("No results for " + var);
457  
              Entry e = random(entries);
458  
              vars.put(t.a, e.page->q);
459  
              vars.put(t.b, e.key);
460  
              continue;
461  
            } else {
462  
              Cl<S> keys = keysForPageAndValue(t.a, t.c);
463  
              if (empty(keys)) ret serveJSON("No results for " + var);
464  
              pages = map pageFromQ(keys);
465  
            }
466  
          } else {
467  
            var = t.a;
468  
            if (!isDollarVar(t.a)) todo(t);
469  
            if (isDollarVar(t.b)) todo(t);
470  
            if (isDollarVar(t.c)) todo(t);
471  
            pages = pagesForKeyAndValue(t.b, t.c);
472  
          }
473  
          if (empty(pages)) ret serveJSON("No results for " + var);
474  
          vars.put(var, random(pages).q);
475  
        } else
476  
          fail("Can't interpret: " + line);
477  
      }
478  
      
479  
      ret serveJSON("No return statement");
480  
    }
481  
482  
    // end of serveBot()
483  
  
484  
    ret subBot_serve404();
485  
  }
486  
  
487  
  O serveLiteralSearch() {
488  
    S q = params.get('q);
489  
    L<Page> searchResults = literalSearch(q);
490  
    ret serveSearchResults("literal search" , q, searchResultsToShow, searchResults);
491  
  }
492  
  
493  
  L<Page> literalSearch(S q, O... _) {
494  
    int searchResultsToShow = optPar max(_, 100);
495  
    
496  
    // quick search in random order
497  
    //L<Page> searchResults = takeFirst(searchResultsToShow+1, filterIterator(iterator(list(Page)), p -> cic(p.q, q));
498  
    
499  
    // full search, order by length
500  
    ret takeFirst(searchResultsToShow+1, pagesSortedByLength(filter(list(Page), p -> cic(p.q, q))));
501  
  }
502  
  
503  
  O serveScoredSearch() {
504  
    S q = params.get('q);
505  
    L<Page> searchResults = (L<Page>) dm_call('agiBlueSearch, 'search, q);
506  
    ret serveSearchResults("scored search" , q, searchResultsToShow, searchResults);
507  
  }
508  
  
509  
  O serveLevenSearch() {
510  
    S q = params.get('q);
511  
    L<Page> searchResults = levenSearch(q);
512  
    ret serveSearchResults("leven search with distance 1" , q, searchResultsToShow, searchResults);
513  
  }
514  
  
515  
  L<Page> levenSearch(S q, O... _) {
516  
    int searchResultsToShow = optPar max(_, 100);
517  
    int maxEditDistance = 1;
518  
    
519  
    new Map<Page, Int> map;
520  
    for (Page p) {
521  
      int distance = leven_limitedIC(q, p.q, maxEditDistance+1);
522  
      if (distance <= maxEditDistance) map.put(p, distance);
523  
    }
524  
    ret takeFirst(searchResultsToShow+1, keysSortedByValue(map));
525  
  }
526  
  
527  
  O serveSearchResults(S searchType, S q, int searchResultsToShow, Collection<Page> searchResults) {
528  
    S title = "agi.blue " + searchType + " for " + htmlEncode2(quote(q)) + " (" + (l(searchResults) >= searchResultsToShow ? searchResultsToShow + "+ results" : nResults(l(searchResults))) + ")";
529  
    
530  
    ret hhtml2(hhead_title(htmldecode_dropAllTags(title))
531  
      + hbody(hfullcenter(//top +
532  
        h3(title)
533  
      + p_nemptyLines_showFirst(searchResultsToShow, map(pageToHTMLLink(), searchResults)))));
534  
  }
535  
  
536  
  O serveQueryPage() {
537  
    S query = params.get('query);
538  
    if (query == null) query = loadSnippet(#1024258);
539  
    S title = ahref("/", "agi.blue") + " | Execute a query script (" + targetBlank("http://code.botcompany.de/1024274", "ALQL") + ")";
540  
    ret hhtml2(hhead_title(htmldecode_dropAllTags(title))
541  
      + hbody(hfullcenter(
542  
        h3(title)
543  
      + form(
544  
        htextarea(query, name := 'query, cols := 80, rows := 10, autofocus := true)
545  
        + "<br><br>"
546  
        + hsubmit("Execute"), action := "/bot/query")
547  
      )));    
548  
  }
549  
550  
} // end of class Request
551  
552  
svoid dbLog(O... params) {
553  
  logStructure(programFile("db.log"), ll(params));
554  
}
555  
556  
static IF1<Page, Map> pageToMap(O... _) {
557  
  optPar bool withEntries;
558  
  
559  
  bool nameOnly = eqOneOf(optPar nameOnly(_), "1", true);
560  
  if (nameOnly) ret (IF1<Page, Map>) p -> litmap(q := p.q);
561  
  
562  
  ret (IF1<Page, Map>) p -> {
563  
    L<Entry> entries = findBackRefs(p, Entry);
564  
    ret litorderedmap(
565  
      q := p.q,
566  
      nEntries := l(entries),
567  
      created := p.created,
568  
      modified := p._modified,
569  
      entries := !withEntries ? null : map(entries, entryToMap(false)));
570  
  };
571  
}
572  
573  
static IF1<Entry, Map> entryToMap(bool withPage) {
574  
  ret (IF1<Entry, Map>) e -> litorderedmap(
575  
    created := e.created,
576  
    i := e.count,
577  
    key := e.key,
578  
    value := e.value,
579  
    q := withPage ? e.page->q : null,
580  
    signer := getString globalID(e.signer!));
581  
}
582  
583  
sO servePageToBot(Page page, SS params) {
584  
  if (page == null) ret serveJSON(null);
585  
  params = asCIMap(params);
586  
  Map map = pageToMap(withEntries := valueIs1 withEntries(params)).get(page);
587  
  ret serveJSON(map);
588  
}
589  
590  
sclass GetEntriesAndPost {
591  
  L<Entry> entries;
592  
  Entry entry;
593  
  bool newEntry;
594  
  Signer signer;
595  
  
596  
  GetEntriesAndPost go(Page page, SS params) {
597  
    S key = trim(params.get('key)), value = trim(params.get('value));
598  
    print("GetEntriesAndPost: " + quote(page.q) + ", " + quote(key) + " := " + quote(value));
599  
    withDBLock {
600  
      entries = findBackRefs(page, Entry);
601  
      if (nempty(key) && nempty(value)) {
602  
        S ip = subBot_clientIP();
603  
        entry = firstThat(e -> eqic(e.key, key) && eq_icIf(!allowMultipleCasesInValues, e.value, value) && eq(e.ip, ip), entries);
604  
        if (entry == null) {
605  
          print("SAVING");
606  
          Entry e = cnew Entry(+page, +key, +value, +ip, count := l(entries) + 1, +signer);
607  
          page.change(); // bump modification date
608  
          entry = e;
609  
          newEntry = true;
610  
          entries.add(entry);
611  
          dbLog("New entry", page := page.q, globalID := e.globalID, count := e.count, +key, +value);
612  
        }
613  
      }
614  
    }
615  
616  
    sortByFieldInPlace created(entries);
617  
    numberEntriesInConceptField count(entries);
618  
    this;
619  
  }
620  
}
621  
622  
static Page findPageFromParams(Map map) {
623  
  S q = getString q(map);
624  
  ret empty(q) ? null : findPageFromQ(q);
625  
}
626  
627  
static Page findOrMakePageFromParams(Map map) {
628  
  ret pageFromQ(getString q(map));
629  
}
630  
631  
static Page findPageFromQ(S q) {
632  
  ret conceptWhereCI Page(+q);
633  
}
634  
635  
static Page pageFromQ(S q) {
636  
  ret empty(q) ? null : uniqCI_sync Page(+q);
637  
}
638  
639  
static F1<Page, S> pageToHTMLLink(O... _) {
640  
  optPar int displayLength = main.displayLength;
641  
  ret func(Page p) -> S {
642  
    S name = pageDisplayName(p);
643  
    ret ahref("http://agi.blue" + hquery(q := p.q),
644  
      htmlEncode2(shorten(displayLength, name)),
645  
      title := name);
646  
  };
647  
}
648  
649  
static Collection<S> backSearch(S key, S value) {
650  
  // we query the index for the value field because that yields fewer results
651  
  ret map(conceptsWhereCI Entry(value := "a slice of reality", key := "is"), e -> e.page->q);
652  
}
653  
654  
static Collection<S> availableSlices() {
655  
  ret moveElementToBeginningIC("the default slice", backSearch("is", "a slice of reality"));
656  
  //ret ll("the default slice", "the everything slice", "the robot slice");
657  
}
658  
659  
static PhysicalSlice getOrMakePhysicalSlice(Page p) {
660  
  PhysicalSlice slice = first(findBackRefs PhysicalSlice(p));
661  
  if (slice == null)
662  
    slice = uniq_sync(PhysicalSlice, slicePage := p);
663  
  ret slice;
664  
}
665  
666  
static PhysicalSlice theWildSlice() {
667  
  ret getOrMakePhysicalSlice(pageFromQ("the wild slice"));
668  
}
669  
670  
svoid moveSlicelessPagesToTheWildSlice() {
671  
  PhysicalSlice slice = theWildSlice();
672  
  for (Page p : conceptsWhere Page(slice := null))  {
673  
    print("Moving to wild slice: " + p.q);
674  
    cset_sync(p, +slice);
675  
  }
676  
}
677  
678  
sS renderThing(S s, bool forceURLDisplay) {
679  
  ret forceURLDisplay || isURL(s) || isAGIDomain(s)
680  
    ? ahref(fixAGILink(absoluteURL(s)), htmlencode2(shorten(displayLength, s)))
681  
    : ahref(agiBlue_linkForPhrase(s), htmlencode2(shorten(displayLength, s)));
682  
}
683  
684  
static L<Entry> entriesOnPage(Page p) {
685  
  ret p == null ? null : sortedByField count(findBackRefs(p, Entry));
686  
}
687  
688  
static L<Page> pagesSortedByLength(L<Page> l) {
689  
  ret sortedByCalculatedField(l, p -> l(p.q));
690  
}
691  
692  
sS hhtml2(S contents) {
693  
  ret hhtml(hAddToHead_fast(contents, 
694  
    hIncludeGoogleFont("Source Sans Pro")
695  
    + hmobilefix()
696  
    + hstylesheet("body { font-family: Source Sans Pro }")));
697  
}
698  
699  
static Set<Page> pagesForKeyAndValue(S key, S value) {
700  
  L<Entry> entries = conceptsWhereIC Entry(+value, +key);
701  
  ret asSet(ccollect page(entries));
702  
}
703  
704  
static Cl<S> keysForPageAndValue(S q, S value) {
705  
  Page page = findPageFromQ(q);
706  
  if (page == null) null;
707  
  ret collect key(conceptsWhereIC Entry(+page, +value));
708  
}

Author comment

Began life as a copy of #1023558

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1024297
Snippet name: agi.blue source [backup before slices 2]
Eternal ID of this version: #1024297/1
Text MD5: e1de44ad0b7ab6e6f75cc264049ae383
Author: stefan
Category: javax / html
Type: JavaX module (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-07-30 14:09:03
Source code size: 26910 bytes / 708 lines
Pitched / IR pitched: No / No
Views / Downloads: 309 / 497
Referenced in: [show references]