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

1459
LINES

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

JavaX source code (Dynamic Module) - run with: Stefan's OS

1  
!7
2  
3  
// See #1023660 for the older 99 lines version
4  
5  
// Customizations:
6  
7  
sbool asyncSearch = false;
8  
sbool allowMultipleCasesInValues = true;
9  
sbool showSliceSelector = true;
10  
sbool showGoogleLogIn = true;
11  
sbool makeAllKeysPages = true;
12  
sbool makeAllValuesPages = true; 
13  
sbool legacy = true; // We still have slices without applied fixes
14  
15  
static int maxSliceNameLength = 1024;
16  
static int displayLength = 140;
17  
static int sideDisplayLength = 50; // when in side bar
18  
static int searchResultsToShow = 50;
19  
sS sideSearchType = 'literal;
20  
static int maxBackgroundSlices = 1000;
21  
22  
// end of customizations
23  
24  
// in main DB
25  
concept Slice {
26  
  GlobalID globalID = aGlobalIDObject();
27  
  S caseID;
28  
  S name;
29  
  bool indexed = true;
30  
  long sliceDumped; // wall time, set before dump starts
31  
32  
  new Ref<User> owner;
33  
34  
  S defaultCaseID() {
35  
    ret uniqueFileNameUsingMD5_80_v2(name + " " + globalID);
36  
  }
37  
}
38  
39  
// in any DB
40  
concept Page {
41  
  S globalID = aGlobalID();
42  
  S url, q;
43  
  
44  
  // for in-VM helper bots
45  
  void quickPost(S key, S value) {
46  
    new GetEntriesAndPost(_concepts).go(this, litmap(+key, +value));
47  
  }
48  
}
49  
50  
abstract concept AbstractEntry {
51  
  new Ref<Page> page;
52  
  int count;
53  
  S key;
54  
  S ip;
55  
  new Ref<Signer> signer;
56  
  
57  
  S q() { Page p = page!; ret p == null ? null : page->q; }
58  
}
59  
60  
concept Entry > AbstractEntry {
61  
  S globalID = aGlobalID(); // TODO: migrate to object
62  
  S value;
63  
}
64  
65  
concept MultiLineEntry > AbstractEntry {
66  
  GlobalID globalID = aGlobalIDObject();
67  
  S value;
68  
}
69  
70  
concept BlobEntry > AbstractEntry {
71  
  GlobalID globalID = aGlobalIDObject();
72  
  long length;
73  
  S md5;
74  
}
75  
76  
// in main DB?
77  
concept Signer {
78  
  S globalID = aGlobalID();
79  
  S publicKey;
80  
  bool trusted;
81  
  S approvedBy;
82  
}
83  
84  
concept User {
85  
  GlobalID globalID = aGlobalIDObject();
86  
  long lastSeen;
87  
}
88  
89  
concept CookieUser > User {
90  
  S cookie;
91  
92  
  toString { ret "[cookieUser]"; }
93  
}
94  
95  
concept GoogleUser > User {
96  
  long googleLogInDate;
97  
  S googleEmail, googleFirstName, googleLastName;
98  
  bool googleEmailVerified;
99  
100  
  toString { ret googleFirstName + " " + googleLastName; }
101  
}
102  
103  
concept MinimalUser > User {
104  
  S userName, encryptedPassword; // TODO
105  
106  
  toString { ret "[minimalUser] " + userName; }
107  
}
108  
109  
// in main DB
110  
concept Session {
111  
  S cookie;
112  
  S selectedSlice; // global ID
113  
  Page slicePage; // phasing out
114  
  new Ref<User> user;
115  
}
116  
117  
// singleton concept in every DB
118  
concept SliceInfo {
119  
  GlobalID globalID;
120  
  LS mandatoryBotVMBusIDs;
121  
}
122  
123  
sclass CentralIndexEntry {
124  
  Set<Slice> slices = synchroLinkedHashSet();
125  
}
126  
127  
// global constants
128  
129  
static SS searchTypeToText = litmap(
130  
  leven := "Leven",
131  
  literal := "Literal",
132  
  scored := "Scored");
133  
  
134  
// global vars
135  
136  
static volatile bool started, broken;
137  
static int sourceCodeLines;
138  
static ConceptsLoadedOnDemand fan;
139  
static ConceptsLoadedOnDemand backgroundFan;
140  
static Map<S, LoadedSlice> loadedSlices = syncMap();
141  
static Map<S, LoadedSlice> backgroundSlices = syncMap();
142  
static Map<S, CentralIndexEntry> centralIndex = ciMap();
143  
static Map<S, CentralIndexEntry> newCentralIndex = ciMap();
144  
static long centralIndexMade; // wall time
145  
static ReliableSingleThread rst_index = new(r makeCentralIndex);
146  
static TimedCache<Long> sizeOnDisk = new(60.0, f guessClusteredSizeOfProgramDirWithoutBackups);
147  
static ConceptFieldIndexDesc idx_slicesByModification, idx_usersBySeen;
148  
static ConceptFieldIndexCI idx_slicesByName, idx_usersByName;
149  
150  
// end of global data
151  
152  
sclass LoadedSlice { // non-persistent class
153  
  S caseID;
154  
  Concepts cc;
155  
  Slice sliceConcept;
156  
  long lastAccess = sysNow();
157  
  
158  
  ConceptFieldIndexDesc idx_latestEntries, idx_latestCreatedPages, idx_latestChangedPages;
159  
  
160  
  *(S *caseID, Concepts *cc) {
161  
    indexThings();
162  
    
163  
    // forward changes to Slice concept
164  
    onConceptsChange(cc, r {
165  
      cset(sliceConcept, _modified := now())
166  
    });
167  
    
168  
    if (makeAllKeysPages && legacy)
169  
      for (Entry e : list(cc, Entry))
170  
        pageFromQ(e.key);
171  
        
172  
    if (makeAllValuesPages && legacy)
173  
      for (Entry e : list(cc, Entry))
174  
        pageFromQ(e.value);
175  
  }
176  
  
177  
  void initialSetup(GlobalID globalID) {
178  
    SliceInfo info = uniq(cc, SliceInfo);
179  
    cset(info, +globalID);
180  
  }
181  
  
182  
  // create if not there
183  
  Page pageFromQ(S q) {
184  
    ret main.pageFromQ(cc, q);
185  
  }
186  
187  
  void indexThings() {
188  
    indexConceptFieldsCI(cc, Page, 'url, Page, 'q, Entry, 'key, Entry, 'value);
189  
    indexConceptFields(cc, Signer, 'publicKey);
190  
    indexConceptFields(cc, Session, 'cookie);
191  
    indexSingletonConcept(cc, SliceInfo);
192  
    idx_latestCreatedPages = new ConceptFieldIndexDesc(cc, Page, 'created);
193  
    idx_latestChangedPages = new ConceptFieldIndexDesc(cc, Page, '_modified);
194  
    idx_latestEntries = new ConceptFieldIndexDesc(cc, Entry, 'created);
195  
  }
196  
  
197  
  bool isMainSlice() { ret empty(caseID); }
198  
  GlobalID globalID() { ret sliceConcept.globalID; }
199  
}
200  
201  
p {
202  
  try {
203  
    if (bootstrapDataFrom(#1023558)) deleteMyBackups();
204  
    thinMyBackups();
205  
    fan = slicesLoadedOnDemand(loadedSlices);
206  
    mainConcepts = fan.get("", null);
207  
    
208  
    // index main DB
209  
210  
    indexConceptFields(Slice, 'globalID, Slice, 'caseID);
211  
    indexConceptField(CookieUser, 'cookie);
212  
    idx_slicesByName = new ConceptFieldIndexCI(Slice, 'name);
213  
    idx_slicesByModification = new ConceptFieldIndexDesc(Slice, '_modified);
214  
    idx_usersByName = new ConceptFieldIndexCI(GoogleUser, 'googleLastName);
215  
    idx_usersBySeen = new ConceptFieldIndexDesc(User, 'lastSeen);
216  
217  
    cset(uniq_returnIfNew Slice(caseID := ""), name := "main slice");
218  
    loadedSlices.get("").initialSetup(toGlobalIDObj(mainSliceGlobalID()));
219  
    
220  
    backgroundFan = slicesLoadedOnDemand(backgroundSlices);
221  
    backgroundFan.lock = fan.lock;
222  
    
223  
    // legacy conversions!
224  
    //deleteConcepts(Slice, globalID := GlobalID('wftlawbagrwprywn));
225  
  
226  
    // Approve this machine's key
227  
    PKIKeyPair machineKey = agiBot_trustedKeyForMachine();
228  
    if (machineKey != null) {
229  
      print("Approving this machine's key: " + machineKey.publicKey);
230  
      cset(uniq_sync(Signer, publicKey := machineKey.publicKey), trusted := true, approvedBy := "local");
231  
    }
232  
    
233  
    sourceCodeLines = countLines(mySource());
234  
    
235  
    rst_index.trigger();
236  
  } catch print e {
237  
    set broken;
238  
  } finally {
239  
    set started;
240  
  }
241  
  
242  
  // do stuff after we are officially started
243  
  
244  
  // calculate DB size regularly iff there were changes
245  
  sizeOnDisk.keepValueWhileCalculating = true;
246  
  doEveryAndNow(60.0, rWatcher(() -> db_mainConceptsChangeCount(), r { sizeOnDisk! }));
247  
  
248  
} // end of main program
249  
250  
// Serve page
251  
252  
set flag NoNanoHTTPD. html {
253  
  sleepWhile(() -> !started);
254  
  if (broken) ret serve500("Internal error");
255  
  ret new Request().serve(uri, params);
256  
}
257  
258  
sclass WorksOnSlice {
259  
  Concepts cc;
260  
  LoadedSlice slice;
261  
  
262  
  *() {}
263  
  *(LoadedSlice *slice) { cc = slice.cc; }
264  
  
265  
  void setSlice(LoadedSlice slice) {
266  
    this.slice = slice;
267  
    cc = slice.cc;
268  
  }
269  
  
270  
  Page findPageFromParams(Map map) {
271  
    S q = getString q(map);
272  
    ret empty(q) ? null : findPageFromQ(q);
273  
  }
274  
275  
  Page findOrMakePageFromParams(Map map) {
276  
    ret pageFromQ(getString q(map));
277  
  }
278  
  
279  
  Page findPageFromQ(S q) {
280  
    ret conceptWhereCI(cc, Page, +q);
281  
  }
282  
  
283  
  Page pageFromQ(S q) {
284  
    ret slice.pageFromQ(q);
285  
  }
286  
  
287  
  Set<Page> pagesForKeyAndValue(S key, S value) {
288  
    L<Entry> entries = conceptsWhereIC(cc, Entry, +value, +key);
289  
    ret asSet(ccollect page(entries));
290  
  }
291  
  
292  
  Cl<S> keysForPageAndValue(S q, S value) {
293  
    Page page = findPageFromQ(q);
294  
    if (page == null) null;
295  
    ret collect key(conceptsWhereIC(cc, Entry, +page, +value));
296  
  }
297  
298  
  // DB functions
299  
300  
  bool hasPage(S q) { ret hasConceptWhereIC(Page, +q); }
301  
  S getValue(Page page, S key) {
302  
    ret page == null || empty(key) ? null : getString value(highestByField count(objectsWhereIC(findBackRefs(page, Entry), +key)));
303  
  }
304  
  S getValue(S page, S key) {
305  
    ret getValue(findPageFromQ(page), key);
306  
  }
307  
  S pageDisplayName(Page page) {
308  
    /*S name = getValue(page, "read as");
309  
    bool unnaturalName = nempty(name) && !eq(makeAGIDomain(name), page.url);
310  
    ret unnaturalName ? name + " " + squareBracketed(page.url) : or2(name, unpackAGIDomainOpt(page.url));*/
311  
    ret page.q;
312  
  }
313  
  
314  
  S renderThing(S s, bool forceURLDisplay) {
315  
    ret forceURLDisplay || isURL(s) || isAGIDomain(s)
316  
      ? ahref(fixAGILink(absoluteURL(s)), htmlencode2(shorten(displayLength, s)))
317  
      : ahref(agiBlue_linkForPhrase(s,
318  
          slice := slice.isMainSlice() ? null : slice.sliceConcept.globalID),
319  
        htmlencode2(shorten(displayLength, s)));
320  
  }
321  
322  
} // end of WorksOnSlice
323  
324  
sclass Request extends WorksOnSlice {
325  
  S cookie;
326  
  Session session;
327  
  S uri;
328  
  SS params;
329  
  long started = sysNow();
330  
  S q, domain;
331  
  Set<S> get;
332  
  
333  
  // when serving a concept page, info that may be grabbed
334  
  // by thought bots
335  
  L<Entry> usesAsKey;
336  
  
337  
  // should also work for standalone
338  
  bool isHomeDomain() {
339  
    S domain = domain();
340  
    ret eqic(domain, "www.agi.blue") || !ewic(domain, ".agi.blue");
341  
  }
342  
  
343  
  O serve(S uri, SS params) {
344  
    this.uri = dropMultipleSlashes(uri);
345  
    this.params = params;
346  
    new Matches m;
347  
    
348  
    print(uri + " ? " + unnull(subBot_query()));
349  
    
350  
    // get cookie & session
351  
    
352  
    cookie = cookieFromUser();
353  
    if (cookie != null)
 {
354  
      session = uniq_sync(Session, +cookie);
355  
      if (session.user! == null)
356  
        cset(session, user := uniq_sync CookieUser(+cookie));
357  
    } else
358  
      session = unlistedWithValues(Session);
359  
      
360  
    // check if user wants to change slices
361  
      
362  
    S selectSlice = params.get('slice);
363  
    if (isGlobalID(selectSlice))
364  
      cset(session, selectedSlice := selectSlice);
365  
    if (session.selectedSlice == null)
366  
      cset(session, selectedSlice := str(mainSliceGlobalID()));
367  
368  
    // get slice's case ID
369  
    
370  
    S caseID = "";
371  
    Slice sliceConcept = sliceConceptForGlobalID(session.selectedSlice);
372  
    print("Selected slice: " + session.selectedSlice + ", obj? " + (sliceConcept != null));
373  
    if (sliceConcept != null) caseID = sliceConcept.caseID;
374  
    print("caseID: " + caseID);
375  
    
376  
    // load slice
377  
    
378  
    slice = assertNotNull(loadSlice(caseID, session.selectedSlice));
379  
    cc = slice.cc;
380  
    slice.sliceConcept = sliceConcept;
381  
    
382  
    // Check for special URIs
383  
384  
    if (swic(uri, "/bot/")) ret serveBot();
385  
386  
    if (swic(uri, "/user/", m)) {
387  
      User user = conceptWhere User(globalID := toGlobalIDObj(assertGlobalID(m.rest())));
388  
      if (user == null) ret subBot_serve404("User not found");
389  
      S title = "User " + user;
390  
      ret hhtml_miniPage(title, h3(agiBlueNameHTML() + " | " + title)
391  
        + "User type: " + classShortName(user));
392  
    }
393  
394  
    // eleu appends a slash to the URI if it's a single identifier, so we drop it again
395  
    S uri2 = dropTrailingSlash(uri);
396  
    
397  
    if (eqic(uri2, "/google-verify")) {
398  
      print("Google-verify started.");
399  
      Payload payload = printStruct(googleVerifyUserToken2(googleSignInID(), params.get("token")));
400  
      if (payload == null) ret print("google-verify", "No");
401  
      S email = payload.getEmail();
402  
      if (empty(email)) ret print("google-verify", "No");
403  
      
404  
      GoogleUser user = uniqCI_sync GoogleUser(googleEmail := email);
405  
      cset(user,
406  
        googleEmailVerified := payload.getEmailVerified(),
407  
        googleFirstName := strOrNull(payload.get("given_name")),
408  
        googleLastName := strOrNull(payload.get("family_name")));
409  
      
410  
      cset(session,
 +user);
411  
        
412  
      ret print("google-verify", payload.getEmail() + " " + (payload.getEmailVerified() ? "(verified)" : "(not verified)"));
413  
    }
414  
415  
    cset(session.user!, lastSeen := now());      
416  
    
417  
    if (eqic(uri2, "/users")) ret serveUsersList();
418  
    
419  
    if (eqic(uri2, "/slices")) ret serveSlicesList();
420  
    
421  
    if (eqic(uri2, "/search")) ret serveScoredSearch();
422  
    if (eqic(uri2, "/literalSearch")) ret serveLiteralSearch();
423  
    if (eqic(uri2, "/levenSearch")) ret serveLevenSearch();
424  
    
425  
    if (eqic(uri2, "/query")) ret serveQueryPage();
426  
    if (eqic(uri2, "/createSlice")) ret serveCreateSlicePage();
427  
    
428  
    q = params.get('q);
429  
    get = asCISet(nempties(subBot_paramsAsMultiMap().get('get)));
430  
    
431  
    domain = or2(params.get('domain), domain());
432  
    
433  
    S raw = firstKeyWithValue("", params); // agi.blue?something
434  
    if (nempty(raw) && empty(q)) q = raw;
435  
    /*if (nempty(q)) {
436  
      domain = makeAGIDomain(q);
437  
      if (l(domain) > maximumDomainPartLength()) // escape with "domain="
438  
        ret hrefresh(agiBlueURL() + hquery(+domain, key := "read as", value := q));
439  
      ret hrefresh("http://" + domain + (eq(q, domain) ? "" : "/" +  hquery(key := "read as", value := q)));
440  
      //uri = "/"; replaceMapWithParams(params, key := "read as", value := q);
441  
    }*/
442  
    S url = domain + dropTrailingSlash(uri);
443  
    
444  
    // domain to query
445  
    //if (empty(q)) q = url;
446  
    if (empty(q)) {
447  
      S qq = agiBlue_urlToQuery(url);
448  
      if (neqic(qq, "agi.blue")) q = qq;
449  
    }
450  
    
451  
    Page page, bool newPage = unpair uniqCI2_sync(cc, Page, +q);
452  
    if (newPage) dbLog("New page", +q);
453  
    //printStructs(+params, +raw, +q);
454  
  
455  
    if (empty(params.get('q)) && empty(raw) && isHomeDomain()) {
456  
      //L<Page> pages = sortedByFieldDesc _modified(list(cc, Page)); // TODO: use index
457  
      L<Page> pages = cloneList(slice.idx_latestChangedPages.objectIterator());
458  
      int start = parseInt(params.get("start")), step = 100;
459  
      S nav = pageNav2("/", l(pages), start, step, "start");
460  
      S content = hform(b("GIVE ME INPUT: &nbsp; ") + htextinput('q, autofocus := true) + " " + hsubmit("Ask"))
461  
        + h1(sliceAsHTML() + " has " + nPages(countConcepts(cc, Page)) + " and " + nConnections(countConcepts(cc, Entry)))
462  
        + p(nav)
463  
        + p_nemptyLines(map(pageToHTMLLink(), subList(pages, start, start+step)));
464  
465  
      ret hhtml_agiBlue(hhead_title("Slice " + sliceConcept().name + " | agi.blue") // SERVE SLICE HOME PAGE
466  
        + hbody(hfullcenterAndTopLeft(top() + content
467  
          + footer(),
468  
          sliceSelector()
469  
        )));
470  
    }
471  
        
472  
    S key = trim(params.get('key)), value = trim(params.get('value));
473  
    L<Entry> entries = GetEntriesAndPost(cc).go(page, params).entries;
474  
    
475  
    //S get = params.get('get);
476  
    if (nempty(get))
477  
      ret serveJSON(collect value(llNotNulls(firstThat(entries, e -> get.contains(e.key)))));
478  
    
479  
    S key2 = key, value2 = value; if (nempty(key) && nempty(value)) key2 = value2 = ""; // input reset
480  
  
481  
    bool withHidden = eq(params.get('withHidden), "1");
482  
    new Set<Int> hide;
483  
    if (!withHidden) for (Entry e : entries) if (eqic(e.key, 'hide) && isSquareBracketedInt(e.value)) addAll(hide, e.count, parseInt(unSquareBracket(e.value)));
484  
    new MultiMap<Int, S> mmMeta;
485  
    for (Entry e : entries) if (isSquareBracketedInt(e.key)) mmMeta.put(parseInt(unSquareBracket(e.key)), e.value);
486  
    new MultiMap<S> mm;
487  
    for (Entry e : entries) mm.put(e.key, e.value);
488  
    
489  
    //S name = or2(/* ouch */ last(mm.get("read as")), /* end ouch */ unpackAGIDomain(page.url), page.url);
490  
    S name = page.q;
491  
    
492  
    // Find references
493  
    
494  
    L<Entry> refs = concatLists(conceptsWhereIC(cc, Entry, value := name),
495  
      conceptsWhereIC(cc, Entry, key := name));
496  
    Set<Page> refPages = asSet(ccollect page(refs));
497  
    refPages.remove(page); // don't list current page as reference
498  
    
499  
    // Search in page names (depending on default search type)
500  
    
501  
    L<Page> searchResults;
502  
    if (eq(sideSearchType, 'leven))
503  
      searchResults = levenSearch(page.q, max := 50);
504  
    else if (eq(sideSearchType, 'literal))
505  
      searchResults = literalSearch(page.q, max := 50);
506  
    else
507  
      searchResults = (L<Page>) dm_call('agiBlueSearch, 'search, page.q, maxResult := searchResultsToShow+1, agiBlueBotID := programID(), +cc);
508  
    searchResults.remove(page);
509  
    
510  
    // Find uses as key
511  
    usesAsKey = conceptsWhereIC(cc, Entry, key := page.q);
512  
    
513  
    S pageName_html = htmlEncode2(shorten(displayLength, name));
514  
515  
    S mainContents =
516  
        top() + h1(ahref_unstyled(agiBlue_pageURLWithSlice(page), pageName_html) + (newPage ? " [huh????]" : ""))
517  
      + p_nemptyLines(map(entries, func(Entry e) -> S {
518  
        !withHidden && (hide.contains(e.count) || eqic(e.key, "read as") && eqic(e.value, name)) ? ""
519  
        : "[" + e.count + "] " +
520  
          renderThing(e.key, false) + ": " +
521  
          b(renderThing(e.value, cic(mmMeta.get(e.count), "is a URL")))
522  
        }))
523  
      + hpostform(h3("Add an entry")
524  
        + "Key: " + hinputfield(key := key2) + " Value: " + hinputfield(value := value2) + "<br><br>" + hsubmit("Add")
525  
        )
526  
        
527  
      + p(ahref(agiBlueURL() + "/literalSearch" + hquery(q := page.q), "[literal search]", title := "Search pages with a name containing this page's name literally")
528  
       + " " +
529  
       ahref(agiBlueURL() + "/levenSearch" + hquery(q := page.q), "[leven search 1]", title := "Search pages with a Levenshtein similarity of 1 containing this page's name literally")
530  
       + " " +
531  
       ahref(agiBlueURL() + "/search" + hquery(q := page.q), "[scored search]", title := "Search pages with ScoredSearch"))
532  
       
533  
       + (empty(usesAsKey) ? "" : h3(quote(pageName_html) + " as key")
534  
       + p_nemptyLines_showFirst(50, map(usesAsKey, e ->
535  
         pageToHTMLLink().get(e.page!) + unicode_spacedRightPointingTriangle() +
536  
           pageName_html + unicode_spacedRightPointingTriangle() +
537  
         pageToHTMLLink().get(pageFromQ(e.value))
538  
       )));
539  
       
540  
      // end of mainContents
541  
        
542  
    S sideContents =
543  
      hform(b("GIVE ME INPUT:") + " "
544  
        + htextinput('q) + " "
545  
        + hsubmit("Ask", onclick := "document.getElementById('newInputForm').target = '';") + " "
546  
        + hsubmit("+Tab", title := "Ask and show result in a new tab", onclick := "document.getElementById('newInputForm').target = '_blank';"),
547  
        id := 'newInputForm)
548  
      
549  
      + h3("References (" + l(refPages) + ")")
550  
      
551  
      + p_nemptyLines_showFirst(10, map(pageToHTMLLink(displayLength := sideDisplayLength), refPages))
552  
      
553  
      + h3(searchTypeToText.get(sideSearchType) + " search results (" + (l(searchResults) >= searchResultsToShow ? searchResultsToShow + "+" : str(l(searchResults))) + ")")
554  
      
555  
      + p_nemptyLines_showFirst(searchResultsToShow, map(pageToHTMLLink(displayLength := sideDisplayLength), searchResults))
556  
      
557  
      + hdiv("", id := 'extraStuff);
558  
      
559  
    // TODO: sync search delivery with WebSocket creation
560  
    if (asyncSearch)
561  
      doLater(6.0, r { dm_call('agiBlueSearch, 'searchAndPost, page.q, agiBlueBotID := programID(), +cc) });
562  
      
563  
    // notify local interested parties
564  
    vmBus_send('agiBlue_servingConceptPage, this, page);
565  
    
566  
    S iframe = params.get('render_iframe);
567  
      
568  
    // serve a concept page
569  
    ret hhtml_agiBlue(hhead_title(pageDisplayName(page)) + hbody(
570  
      tag('table,
571  
        tr(
572  
          td(sliceSelector(), valign := 'top)
573  
        + td(sideContents, align := 'right, valign := 'top, rowspan := 2))
574  
      + tr(td(mainContents +
575  
        (empty(iframe) ? "" : iframe(iframe, width := 600, height := 400)) +
576  
      footer(), align := 'center, valign := 'top)),
577  
      width := "100%", height := "100%")));
578  
  }
579  
  
580  
  O servePagesToBot(Iterable<Page> pages) {
581  
    ret serveListToBot(map(pageToMap(wrapMapAsParams(params)), pages));
582  
  }
583  
584  
  O serveListToBot(Collection l) {
585  
    if (nempty(params.get('max)))
586  
      l = takeFirst(parseInt(params.get('max)), l);
587  
    ret serveJSON(l);
588  
  }
589  
590  
  // uri starts with "/bot/"
591  
  O serveBot() {
592  
    S q = params.get('q);
593  
    
594  
    if (eqic(uri, "/bot/hello")) ret serveJSON("hello");
595  
    if (eqic(uri, "/bot/hasPage")) ret serveJSON(hasPage(q));
596  
    if (eqic(uri, "/bot/randomPageContaining")) {
597  
      assertNempty(q);
598  
      ret servePageToBot(random(filter(list(cc, Page), p -> cic(p.q, q))), params);
599  
    }
600  
    if (eqic(uri, "/bot/allPages"))
601  
      ret servePagesToBot(list(cc, Page));
602  
    if (eqic(uri, "/bot/allPagesStartingWith")) {
603  
      assertNempty(q);
604  
      ret servePagesToBot(filter(list(cc, Page), p -> swic(p.q, q)));
605  
    }
606  
    if (eqic(uri, "/bot/allPagesEndingWith")) {
607  
      assertNempty(q);
608  
      ret servePagesToBot(filter(list(cc, Page), p -> ewic(p.q, q)));
609  
    }
610  
    if (eqic(uri, "/bot/allPagesContaining")) {
611  
      assertNempty(q);
612  
      ret servePagesToBot(filter(list(cc, Page), p -> cic(p.q, q)));
613  
    }
614  
    if (eqic(uri, "/bot/allPagesContainingRegexp")) {
615  
      assertNempty(q);
616  
      Pattern pat = regexpIC(q);
617  
      ret servePagesToBot(filter(list(cc, Page), p -> regexpFindIC(pat, p.q)));
618  
    }
619  
    
620  
    if (eqicOneOf(uri, "/bot/postSigned", /*"/bot/makePhysicalSlice",*/ "/bot/approveTrustRequest")) {
621  
      S text = rtrim(params.get('text));
622  
      S key = getSignerKey(text);
623  
      if (empty(key)) ret subBot_serve500("Please include your public key");
624  
      if (!isSignedWithKey(text, key)) ret subBot_serve500("Signature didn't verify");
625  
      text = dropLastTwoLines(text); // drop signer + sig line
626  
      
627  
      Signer signer = uniq_sync Signer(publicKey := key);
628  
      
629  
      /*if (eqic(uri, "/bot/makePhysicalSlice")) {
630  
        if (!signer.trusted) ret subBot_serve500("Untrusted signer");
631  
        Page page = findPageFromParams(jsonDecodeMap(text));
632  
        if (page == null) ret subBot_serve500("Page not found");
633  
        ret serveJSON(uniq2_sync(PhysicalSlice, slicePage := page).b ? "Slice made" : "Slice exists");
634  
      }*/
635  
    
636  
      if (eqic(uri, "/bot/postSigned")) {
637  
        new L out;
638  
        for (S line : tlft(text)) {
639  
          SS map = jsonDecodeMap(line);
640  
          GetEntriesAndPost x = new(db_mainConcepts());
641  
          x.signer = signer;
642  
          Page page = findOrMakePageFromParams(map);
643  
          if (page == null) continue with out.add("Invalid page reference");
644  
          x.go(page, map);
645  
          out.add(x.newEntry ? "Saved" : x.entry != null ? "Entry exists" : "Need key and value");
646  
        }
647  
        ret serveJSON(out);
648  
      }
649  
      
650  
      if (eqic(uri, "/bot/approveTrustRequest")) {
651  
        if (!signer.trusted) ret subBot_serve500("Untrusted signer");
652  
        Signer toApprove = conceptWhere Signer(publicKey := trim(text));
653  
        if (toApprove == null) ret subBot_serve500("Signer to approve not found");
654  
        cset(toApprove, trusted := true, approvedBy := signer.globalID);
655  
        ret serveJSON("Approved: " + trim(text));
656  
      }
657  
      
658  
      ret subBot_serve500("CONFUSION");
659  
    }
660  
    
661  
    if (eqic(uri, "/bot/post")) {
662  
      GetEntriesAndPost x = new(db_mainConcepts());
663  
      x.go(pageFromQ(q), params);
664  
      ret serveJSON(x.newEntry ? "Saved" : x.entry != null ? "Entry exists" : "Need key and value");
665  
    }
666  
    
667  
    if (eqic(uri, "/bot/entriesOnPage"))
668  
      ret serveJSON(map(entriesOnPage(findPageFromParams(params)), entryToMap(false)));
669  
      
670  
    if (eqic(uri, "/bot/entriesForKey"))
671  
      ret serveJSON(map(conceptsWhereIC(cc, Entry, key := params.get('key)), entryToMap(true)));
672  
      
673  
    if (eqic(uri, "/bot/lookup")) {
674  
      S key = params.get('key);
675  
      if (empty(key)) ret serveJSON("Need key");
676  
      S value = getValue(findPageFromParams(params), key);
677  
      ret serveJSON(empty(value) ? "" : litmap(+value));
678  
    }
679  
  
680  
    if (eqic(uri, "/bot/latestEntries"))
681  
      ret serveJSON(map(takeFirst(10, slice.idx_latestEntries.objectIterator()), entryToMap(true)));
682  
    if (eqic(uri, "/bot/latestPages"))
683  
      ret serveJSON(map(takeFirst(10, slice.idx_latestCreatedPages.objectIterator()), pageToMap()));
684  
    if (eqic(uri, "/bot/latestChangedPages"))
685  
      ret serveJSON(map(takeFirst(10, slice.idx_latestChangedPages.objectIterator()), pageToMap()));
686  
      
687  
    if (eqic(uri, "/bot/googleUsersCount"))
688  
      ret serveJSON(countConcepts(GoogleUser));
689  
      
690  
    if (eqic(uri, "/bot/totalPageCount"))
691  
      ret serveJSON(countConcepts(Page));
692  
    /*if (eqic(uri, "/bot/pageWithoutPhysicalSliceCount"))
693  
      ret serveJSON(countConceptsWhere(Page, slice := null));
694  
    if (eqic(uri, "/bot/physicalSliceCount"))
695  
      ret serveJSON(countConcepts(PhysicalSlice));*/
696  
    if (eqic(uri, "/bot/trustedSignersCount"))
697  
      ret serveJSON(countConcepts(Signer, trusted := true));
698  
      
699  
    if (eqic(uri, "/bot/valueSearch")) {
700  
      S value = params.get('value);
701  
      L<Entry> entries = conceptsWhereIC(cc, Entry, +value);
702  
      ret serveJSON(map(takeFirst(100, entries), entryToMap(true)));
703  
    }
704  
      
705  
    if (eqic(uri, "/bot/keyAndValueSearch")) {
706  
      S key = params.get('key), value = params.get('value);
707  
      Cl<Page> pages = pagesForKeyAndValue(key, value);
708  
      ret servePagesToBot(pages);
709  
    }
710  
    
711  
    if (eqic(uri, "/bot/keyValuePairsByPopularity")) {
712  
      L<PairS> pairs = map(list(Entry), e -> pair(e.key, e.value));
713  
      LPair<S, Int> pairs2 = multiSetTopPairs(ciMultiSet(map pairToUglyStringForCIComparison(pairs)));
714  
      ret serveJSON(map(pairs2, p -> {
715  
        S key, value = unpair pairFromUglyString(p.a);
716  
        ret litorderedmap(n := p.b, +key, +value);
717  
      }));
718  
    }
719  
    
720  
    if (eqic(uri, "/bot/allKeys"))
721  
      ret serveListToBot(distinctCIFieldValuesOfConcepts(cc, Entry, 'key));
722  
      
723  
    if (eqic(uri, "/bot/allKeysByPopularity"))
724  
      ret serveListToBot(mapMultiSetByPopularity(distinctCIFieldValuesOfConcepts_multiSet(cc, Entry, 'key), (key, n) -> litorderedmap(+n, +key)));
725  
      
726  
    if (eqic(uri, "/bot/dbSize"))
727  
      ret serveJSON(l(conceptsFile()));
728  
      
729  
    if (eqic(uri, "/bot/query"))
730  
      ret serveBotQuery();
731  
732  
    if (eqic(uri, "/bot/createSlice")) {
733  
      Slice slice = createSlice(assertNempty(params.get('name)));
734  
      ret serveJSON(litorderedmap(id := str(slice.globalID), name := slice.name));
735  
    }
736  
    
737  
    if (eqic(uri, "/bot/dumpAllSlices") && authed()) {
738  
      new L<Map> out;
739  
      for (Slice slice) try {
740  
        out.add(litorderedmap(slice := slice.caseID, ms := returnTimeFor(() -> dumpSliceToFile(loadBackgroundSlice(slice)))));
741  
      } catch print e {
742  
        out.add(litorderedmap(slice.caseID, error := exceptionToStringShort(e)));
743  
      }
744  
      ret serveJSON(out);
745  
    }
746  
    
747  
    if (eqic(uri, "/bot/dumpSlice")) {
748  
      File f = dumpSliceToFile(slice);
749  
      ret "OK, saved as: " + f2s(f);
750  
    }
751  
    
752  
    if (eqic(uri, "/bot/diskStats"))
753  
      ret serveJSON(litcimap(
754  
        sizeOnDisk := sizeOnDisk!
755  
      ));
756  
757  
    if (eqic(uri, "/bot/memStats")) {
758  
      Map fg = cloneMap(loadedSlices);
759  
      Map bg = cloneMap(backgroundSlices);
760  
      ret serveJSON(litcimap(
761  
        error := checkDoubleLoads(),
762  
        centralIndexEntries := l(centralIndex),
763  
        centralIndexMade := renderHowLongAgo(centralIndexMade),
764  
        numLoadedForegroundSlices := l(fg),
765  
        numLoadedBackgroundSlices := l(bg),
766  
        loadedForegroundSlicesEstimatedSize := longSum(map estimatedSliceDataSize(keys(fg))),
767  
        loadedBackgroundSlicesEstimatedSize := longSum(map estimatedSliceDataSize(keys(bg))),
768  
        loadedForegroundSlices := sortedIC(keysList(fg)),
769  
        loadedBackgroundSlices := sortedIC(keysList(bg)),
770  
        sessionsWithGoogleUsers := countPred(list(Session), s -> s.user! instanceof GoogleUser),
771  
        userObjects := countConcepts(User),
772  
      ));
773  
    }
774  
    
775  
    if (eqic(uri, "/bot/centralIndexGet")) {
776  
      CentralIndexEntry e = centralIndex.get(q);
777  
      ret serveJSON(e == null ? ll() : map(e.slices, sliceToMap()));
778  
    }
779  
    
780  
    // return primary triple from each slice
781  
    if (eqic(uri, "/bot/centralIndexGrab")) {
782  
      CentralIndexEntry ie = centralIndex.get(q);
783  
      new L<Map> out;
784  
      if (ie != null) for (Slice slice : ie.slices) {
785  
        LoadedSlice ls = loadBackgroundSlice(slice);
786  
        WorksOnSlice wos = new(ls);
787  
        Page page = wos.findPageFromQ(q);
788  
        Iterable<Entry> entries = entriesOnPage(page);
789  
        print("Page for " + q + " in slice " + ls.caseID + ": " + yesNo(page != null) + " - " + l(entries));
790  
        Entry e = first(entries);
791  
        if (e != null)
792  
          out.add(litorderedmap(a := page.q, b := e.key, c := e.value, slice := slice.caseID));
793  
      }
794  
      ret serveJSON(out);
795  
    }
796  
    
797  
    if (eqic(uri, "/bot/updateCentralIndex") && authed()) {
798  
      rst_index.trigger();
799  
      ret "OK";
800  
    }
801  
802  
    if (eqic(uri, "/bot/allGoogleEmails") && authed())
803  
      ret serveJSON(collect googleEmail(list(GoogleUser)));
804  
    
805  
    // end of bot methods
806  
  
807  
    ret subBot_serve404();
808  
  }
809  
  
810  
  O serveBotQuery() {
811  
    S query = params.get('query);
812  
    ret new Query(slice).process(query);
813  
  }
814  
  
815  
  O serveLiteralSearch() {
816  
    S q = params.get('q);
817  
    L<Page> searchResults = literalSearch(q);
818  
    ret serveSearchResults("literal search" , q, searchResultsToShow, searchResults);
819  
  }
820  
  
821  
  L<Page> literalSearch(S q, O... _) {
822  
    int searchResultsToShow = optPar max(_, 100);
823  
    
824  
    // quick search in random order
825  
    //L<Page> searchResults = takeFirst(searchResultsToShow+1, filterIterator(iterator(list(cc, Page)), p -> cic(p.q, q));
826  
    
827  
    // full search, order by length
828  
    ret takeFirst(searchResultsToShow+1, pagesSortedByLength(filter(list(cc, Page), p -> cic(p.q, q))));
829  
  }
830  
  
831  
  O serveScoredSearch() {
832  
    S q = params.get('q);
833  
    L<Page> searchResults = (L<Page>) dm_call('agiBlueSearch, 'search, q, +cc);
834  
    ret serveSearchResults("scored search" , q, searchResultsToShow, searchResults);
835  
  }
836  
  
837  
  O serveLevenSearch() {
838  
    S q = params.get('q);
839  
    L<Page> searchResults = levenSearch(q);
840  
    ret serveSearchResults("leven search with distance 1" , q, searchResultsToShow, searchResults);
841  
  }
842  
  
843  
  L<Page> levenSearch(S q, O... _) {
844  
    int searchResultsToShow = optPar max(_, 100);
845  
    int maxEditDistance = 1;
846  
    
847  
    new Map<Page, Int> map;
848  
    for (Page p : list(cc, Page)) {
849  
      int distance = leven_limitedIC(q, p.q, maxEditDistance+1);
850  
      if (distance <= maxEditDistance) map.put(p, distance);
851  
    }
852  
    ret takeFirst(searchResultsToShow+1, keysSortedByValue(map));
853  
  }
854  
  
855  
  O serveSearchResults(S searchType, S q, int searchResultsToShow, Collection<Page> searchResults) {
856  
    S title = "agi.blue " + searchType + " for " + htmlEncode2(quote(q)) + " (" + (l(searchResults) >= searchResultsToShow ? searchResultsToShow + "+ results" : nResults(l(searchResults))) + ")";
857  
    
858  
    ret hhtml_agiBlue(hhead_title(htmldecode_dropAllTags(title))
859  
      + hbody(hfullcenter(//top() +
860  
        h3(title)
861  
      + p_nemptyLines_showFirst(searchResultsToShow, map(pageToHTMLLink(), searchResults)))));
862  
  }
863  
  
864  
  O serveQueryPage() {
865  
    S query = params.get('query);
866  
    if (query == null) query = loadSnippet(#1024258);
867  
    S title = agiBlueNameHTML() + " | Execute a query script (" + targetBlank("http://code.botcompany.de/1024274", "ALQL") + ")";
868  
    ret hhtml_miniPage(title, h3(title)
 + form(
869  
      htextarea(query, name := 'query, cols := 80, rows := 10, autofocus := true)
870  
      + "<br><br>"
871  
      + hsubmit("Execute"), action := "/bot/query"
872  
    ));
873  
  }
874  
875  
  O hhtml_miniPage(S htmlTitle, O contents) {
876  
    ret hhtml_agiBlue(hhead_title(htmldecode_dropAllTags(htmlTitle))
877  
      + hbody(hfullcenter(contents)));
878  
  }
879  
  
880  
  S sliceHomeURL() {
881  
    ret slice == null ? agiBlueURL() : sliceHomeURL(slice.sliceConcept.globalID);
882  
  }
883  
  
884  
  S sliceHomeURL(Slice slice) { ret sliceHomeURL(slice.globalID); }
885  
886  
  S sliceHomeURL(GlobalID slice) {
887  
    ret agiBlueURL() + hquery(+slice);
888  
  }
889  
  
890  
  O serveCreateSlicePage() {
891  
    S sliceName = trim(params.get('sliceName));
892  
    if (eq(params.get('doIt), "1") && nempty(sliceName)) {
893  
      // TODO: check for existing name
894  
      Slice slice = createSlice(sliceName);
895  
      ret hrefresh(sliceHomeURL(slice.globalID));
896  
    }
897  
    
898  
    S title = agiBlueNameHTML() + " | Create slice";
899  
    ret hhtml_agiBlue(hhead_title(htmldecode_dropAllTags(title))
900  
      + hbody(hfullcenter(
901  
        h3(title)
902  
      + form(
903  
          hhidden(doIt := 1)
904  
        + "Slice name: " + htextinput(+sliceName, autofocus := true)
905  
        + "<br><br>"
906  
        + hsubmit("Create slice"))
907  
      )));    
908  
  }
909  
  
910  
  F1<Page, S> pageToHTMLLink(O... _) {
911  
    optPar int displayLength = main.displayLength;
912  
    ret func(Page p) -> S {
913  
      S name = pageDisplayName(p);
914  
      ret ahref(agiBlue_pageURLWithSlice(p),
915  
        htmlEncode2(shorten(displayLength, name)),
916  
        title := name);
917  
    };
918  
  }
919  
  
920  
  // and google log-in
921  
  S sliceSelector() {
922  
    ret htag table(tr(
923  
      (!showGoogleLogIn ? "" : td(
924  
        googleSignIn_signInButton(agiBlueURL() + "/google-verify", "console.log(data);", ""), style := "padding-right: 10px;")
925  
        + td(nobr(ahref("javascript:signOut()", "Sign out")), style := "padding-right: 10px; padding-bottom: 0.15em"))
926  
    
927  
    + (!showSliceSelector ? "" : hform(td(
928  
        "Select reality slice: "
929  
      + hselect(availableSlices(), session.selectedSlice, name := 'slice, onchange := "this.form.submit()")
930  
      /*+ " " + hsubmit("Go")*/
931  
      + " &nbsp; | " +
932  
      ahref(agiBlueURL("/slices"), nSlices(countConcepts(Slice))) + " | " +
933  
      ahref(agiBlueURL() + "/createSlice", "Create slice...")
934  
    )))));
935  
  }
936  
  
937  
  S sliceAsHTML() {
938  
    if (slice.isMainSlice()) ret htmlEncode2(agiBlueName() + "'s main slice");
939  
    if (slice.sliceConcept == null) ret "Slice ???";
940  
    ret htmlEncode2("Slice " + quote(slice.sliceConcept.name));
941  
  }
942  
  
943  
  Slice sliceConcept() { ret slice.sliceConcept; }
944  
  
945  
  S footer() {
946  
    ret p(small(elapsedMS_sysNow(started) + " ms"));
947  
  }
948  
  
949  
  S verifiedEmail() {
950  
    if (session == null || !(session.user! instanceof GoogleUser)) null;
951  
    ret ((GoogleUser) session.user!).googleEmail;
952  
  }
953  
  
954  
  bool authed() {
955  
    bool ver = eqic(verifiedEmail(), "stefan.reich.maker.of.eye@googlemail.com");
956  
    print("Auth check " + verifiedEmail() + " -> " + ver);
957  
    ret ver;
958  
  }
959  
  
960  
  S googleSignInID() {
961  
    ret eqic(domain(), "botcompany.de") ? botCompanyGoogleSignInID() : agiBlueGoogleSignInID();
962  
  }
963  
964  
  S hhtml_agiBlue(S contents) {
965  
    ret hhtml(hAddToHead_fast(contents, 
966  
      hIncludeGoogleFont("Source Sans Pro")
967  
      //+ [[<meta name="google-site-verification" content="oRvyeTqgSuv-FE_c-2UKM1Vp0oDqx8h9WruHYWqA-NQ" />]]
968  
      + loadJQuery()
969  
      + hmobilefix()
970  
      + googleSignIn_header("", googleSignInID())
971  
      + hstylesheet("body { font-family: Source Sans Pro }")));
972  
  }
973  
  
974  
  O serveSlicesList() {
975  
    S sort = getAny(params, 'sort, 'by);
976  
    L<Slice> slices;
977  
    S shown;
978  
    if (eqic(sort, 'name)) {
979  
      slices = asList(idx_slicesByName.objectIterator());
980  
      shown = "sorted by name";
981  
    } else {
982  
      sort = 'date;
983  
      slices = asList(idx_slicesByModification.objectIterator());
984  
      shown = "last modified first";
985  
    }
986  
      
987  
    S title = agiBlueNameHTML() + " has " + nSlices(slices) /*+ " (" + shown + ")"*/;
988  
    new PreIncLongCounter counter;
989  
    ret hhtml_agiBlue(hhead_title_decode(title)
990  
      + hbody(hfullcenter(
991  
        h1(title)
992  
      + p(joinWithSpacedVBar(
993  
        ahrefIf(neqic(sort, 'name), agiBlueURL() + "/slices" + hquery(sort := 'name), "List by name"),
994  
        ahrefIf(neqic(sort, 'date), agiBlueURL() + "/slices" + hquery(sort := 'date), "List by date"),
995  
        ahref(agiBlueURL() + "/createSlice", "Create slice...")))
996  
997  
      + htmlTable2(map(slices, slice ->
998  
        litorderedmap(
999  
          "Name" := ahref(sliceHomeURL(slice), htmlEncode2(slice.name)),
1000  
          "ID" := ahref(sliceHomeURL(slice), str(slice.globalID)),
1001  
          "Owner" := str(slice.owner!)
1002  
        )),
1003  
        htmlEncode := false)
1004  
      )));
1005  
  }
1006  
1007  
  O serveUsersList() {
1008  
    S sort = getAny(params, 'sort, 'by);
1009  
    L<User> users;
1010  
    S shown;
1011  
    if (eqic(sort, 'name))
1012  
      users = asList(idx_usersByName.objectIterator());
1013  
    else {
1014  
      sort = 'seen;
1015  
      users= asList(idx_usersBySeen.objectIterator());
1016  
    }
1017  
      
1018  
    S title = agiBlueNameHTML() + " has " + nUsers(users);
1019  
    new PreIncLongCounter counter;
1020  
    ret hhtml_agiBlue(hhead_title_decode(title)
1021  
      + hbody(hfullcenter(
1022  
        h1(title)
1023  
      + p(joinWithSpacedVBar(
1024  
        ahrefIf(neqic(sort, 'name), agiBlueURL() + "/users" + hquery(sort := 'name), "List by name"),
1025  
        ahrefIf(neqic(sort, 'seen), agiBlueURL() + "/users" + hquery(sort := 'seen), "List by last seen"),
1026  
        ahref(agiBlueURL() + "/createSlice", "Create slice...")))
1027  
1028  
      + htmlTable2(map(users, user ->
1029  
        litorderedmap(
1030  
          "Name" := ahref(userHomeURL(user), htmlEncode2(str(user))),
1031  
          "Last seen" := renderHowLongAgo(user.lastSeen)
1032  
        )),
1033  
        htmlEncode := false)
1034  
      )));
1035  
  }
1036  
1037  
  S sliceInfoHTML() {
1038  
    User owner = slice.sliceConcept.owner!;
1039  
    ret owner == null ? "" : p("This slice is owned by " + userHTML(owner));
1040  
  }
1041  
1042  
  S userHomeURL(User user) {
1043  
    ret user == null ? null : agiBlueURL() + "/user/" + user.globalID;
1044  
  }
1045  
  
1046  
  S userHTML(User user) {
1047  
    ret user == null ? "nobody" : ahref(userHomeURL(user), htmlEncode2(str(user)));
1048  
  }
1049  
  
1050  
  S top() {
1051  
    ret nempty(get) ? "" : hcomment("cookie: " + takeFirst(4, session.cookie))
1052  
      + hSilentComputatorWithFlag("agi.blue: " + q)
1053  
      + p(ahref(sliceHomeURL(),
1054  
        //hsnippetimg(#1101682, width := 565/5, height := 800/5, title := "Robot by Peerro @ DeviantArt")
1055  
        //hsnippetimg(#1101778, width := 96, height := 96, title := "agi.blue - a database for everything")
1056  
        hsnippetimg(#1101822, width := 314, height := 125, title := "agi.blue - Wikipedia for robots")
1057  
      ))
1058  
      + sliceInfoHTML()
1059  
      + p(small(
1060  
          agiBlueNameHTML_boldWithSize()
1061  
        + (agiBlue_isOriginal() ? "" : " " + targetBlank("http://agi.blue", "[original]"))
1062  
        + " | " + ahref(agiBlueURL("/slices"), nSlices(countConcepts(Slice)))
1063  
        + " | " + targetBlank(progLink(), "source code") + " of this web site (" + nLines(sourceCodeLines) + ") | " + 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")
1064  
        + " | " + targetBlank("http://code.botcompany.de/1024233", "Notes")
1065  
        + " | " + ahref(agiBlueURL() + "/query", "Query")
1066  
      ));
1067  
  }
1068  
1069  
  Slice createSlice(S name) {
1070  
    name = shorten(name, maxSliceNameLength);
1071  
    Slice slice = cnew Slice(+name, owner := session.user);
1072  
    cset(slice, caseID := slice.defaultCaseID());
1073  
    loadSlice(slice).initialSetup(slice.globalID);
1074  
    ret slice;
1075  
  }
1076  
1077  
} // end of Request
1078  
1079  
svoid dbLog(O... params) {
1080  
  logStructure(programFile("db.log"), ll(params));
1081  
}
1082  
1083  
static IF1<Page, Map> pageToMap(O... _) {
1084  
  optPar bool withEntries;
1085  
  
1086  
  bool nameOnly = eqOneOf(optPar nameOnly(_), "1", true);
1087  
  if (nameOnly) ret (IF1<Page, Map>) p -> litmap(q := p.q);
1088  
  
1089  
  ret (IF1<Page, Map>) p -> {
1090  
    L<Entry> entries = findBackRefs(p, Entry);
1091  
    ret litorderedmap(
1092  
      q := p.q,
1093  
      nEntries := l(entries),
1094  
      created := p.created,
1095  
      modified := p._modified,
1096  
      entries := !withEntries ? null : map(entries, entryToMap(false)));
1097  
  };
1098  
}
1099  
1100  
static IF1<Entry, Map> entryToMap(bool withPage) {
1101  
  ret (IF1<Entry, Map>) e -> litorderedmap(
1102  
    created := e.created,
1103  
    i := e.count,
1104  
    key := e.key,
1105  
    value := e.value,
1106  
    q := withPage ? e.page->q : null,
1107  
    signer := getString globalID(e.signer!));
1108  
}
1109  
1110  
static IF1<Slice, Map> sliceToMap() {
1111  
  ret (IF1<Slice, Map>) s -> litorderedmap(
1112  
    created := s.created,
1113  
    globalID := str(s.globalID),
1114  
    name := s.name,
1115  
    caseID := s.caseID);
1116  
}
1117  
1118  
sO servePageToBot(Page page, SS params) {
1119  
  if (page == null) ret serveJSON(null);
1120  
  params = asCIMap(params);
1121  
  Map map = pageToMap(withEntries := valueIs1 withEntries(params)).get(page);
1122  
  ret serveJSON(map);
1123  
}
1124  
1125  
sclass GetEntriesAndPost {
1126  
  Concepts cc;
1127  
  L<Entry> entries;
1128  
  Entry entry;
1129  
  bool newEntry;
1130  
  Signer signer;
1131  
  
1132  
  *(Concepts *cc) {}
1133  
  
1134  
  GetEntriesAndPost go(Page page, SS params) {
1135  
    S key = trim(params.get('key)), value = trim(params.get('value));
1136  
    print("GetEntriesAndPost: " + quote(page.q) + ", " + quote(key) + " := " + quote(value));
1137  
    withDBLock {
1138  
      entries = findBackRefs(page, Entry);
1139  
      if (nempty(key) && nempty(value)) {
1140  
        S ip = subBot_clientIP();
1141  
        entry = firstThat(e -> eqic(e.key, key) && eq_icIf(!allowMultipleCasesInValues, e.value, value) && eq(e.ip, ip), entries);
1142  
        if (entry == null) {
1143  
          print("SAVING");
1144  
          Entry e = cnew(cc, Entry, +page, +key, +value, +ip, count := l(entries) + 1, +signer);
1145  
          if (makeAllKeysPages) pageFromQ(cc, key);
1146  
          if (makeAllValuesPages) pageFromQ(cc, value);
1147  
          page.change(); // bump modification date
1148  
          entry = e;
1149  
          newEntry = true;
1150  
          entries.add(entry);
1151  
          dbLog("New entry", page := page.q, globalID := e.globalID, count := e.count, +key, +value);
1152  
        }
1153  
      }
1154  
    }
1155  
1156  
    sortByFieldInPlace created(entries);
1157  
    numberEntriesInConceptField count(entries);
1158  
    this;
1159  
  }
1160  
}
1161  
1162  
static SS availableSlices() {
1163  
  L<Slice> slices = asList(idx_slicesByName.objectIterator());
1164  
  ret mapToOrderedMap(s -> pair(str(s.globalID), s.name + " [ID: " + s.globalID + "]"), slices);
1165  
}
1166  
1167  
static L<Entry> entriesOnPage(Page p) {
1168  
  ret p == null ? null : sortedByField count(findBackRefs(p, Entry));
1169  
}
1170  
1171  
static L<Page> pagesSortedByLength(L<Page> l) {
1172  
  ret sortedByCalculatedField(l, p -> l(p.q));
1173  
}
1174  
1175  
sbool agiBlue_isOriginal() {
1176  
  ret amProgram(#1023558);
1177  
}
1178  
1179  
sS agiBlueURL(S subUri) { ret agiBlueURL() + prependSlash(subUri); }
1180  
1181  
sS agiBlueURL() {
1182  
  ret agiBlue_isOriginal() ? "https://agi.blue" :  "/" + psI(programID()) + "/raw";
1183  
}
1184  
1185  
sS agiBlueName() {
1186  
  ret agiBlue_isOriginal() ? "agi.blue" : "agi.blue clone " + programID();
1187  
}
1188  
1189  
svoid cleanMeUp {
1190  
  cleanUp(fan);
1191  
}
1192  
1193  
static LoadedSlice loadSlice(Slice slice) {
1194  
  ret loadSlice(slice.caseID, str(slice.globalID));
1195  
}
1196  
1197  
static LoadedSlice loadSlice(S caseID, S globalID) {
1198  
  caseID = unnull(caseID);
1199  
  lock fan.lock;
1200  
  
1201  
  // move slice from background to foreground
1202  
  
1203  
  Concepts cc = backgroundFan.getIfLoaded(caseID);
1204  
  if (cc != null) {
1205  
    LoadedSlice slice = assertNotNull(backgroundSlices.get(caseID));
1206  
    backgroundFan.loaded.remove(caseID);
1207  
    fan.loaded.put(caseID, cc);
1208  
    backgroundSlices.remove(caseID);
1209  
    loadedSlices.put(caseID, slice);
1210  
    ret slice;
1211  
  }
1212  
  
1213  
  fan.get(caseID, globalID);
1214  
  ret loadedSlices.get(caseID);
1215  
}
1216  
1217  
// load background slice
1218  
static LoadedSlice loadBackgroundSlice(Slice slice) {
1219  
  ret loadBackgroundSlice(slice.caseID, str(slice.globalID));
1220  
}
1221  
1222  
static LoadedSlice loadBackgroundSlice(S caseID, S globalID) {
1223  
  caseID = unnull(caseID);
1224  
  lock fan.lock;
1225  
  
1226  
  // check if in foreground
1227  
  
1228  
  if (fan.getIfLoaded(caseID) != null)
1229  
    ret loadedSlices.get(caseID);
1230  
1231  
  backgroundFan.get(caseID, globalID);
1232  
  LoadedSlice slice = assertNotNull(backgroundSlices.get(caseID));
1233  
  slice.lastAccess = sysNow();
1234  
  while (l(backgroundSlices) > maxBackgroundSlices)
1235  
    unloadLeastRecentlyAccessedBackgroundSlice();
1236  
  ret slice;
1237  
}
1238  
1239  
// TODO: sync unloading slice with accessors
1240  
svoid unloadLeastRecentlyAccessedBackgroundSlice() {
1241  
  lock fan.lock;
1242  
  S caseID = lowestByField lastAccess(keys(backgroundSlices));
1243  
  if (caseID != null)
1244  
    backgroundFan.unloadCase(caseID);
1245  
}
1246  
1247  
static Slice sliceConceptForGlobalID(S globalID) {
1248  
  ret sliceConceptForGlobalID(toGlobalIDObj(globalID));
1249  
}
1250  
1251  
static Slice sliceConceptForGlobalID(GlobalID globalID) {
1252  
  ret conceptWhere Slice(+globalID);
1253  
}
1254  
1255  
static Slice sliceConceptForCaseID(S caseID) {
1256  
  ret conceptWhere Slice(+caseID);
1257  
}
1258  
1259  
sS agiBlueNameHTML() {
1260  
  ret ahref(agiBlueURL(), htmlEncode2(agiBlueName()));
1261  
}
1262  
1263  
sS agiBlueNameHTML_boldWithSize() {
1264  
  Long size = sizeOnDisk.peek();
1265  
  ret b(agiBlueNameHTML()) + (size == null ? "" : " " + spanTitle("Size of agi.blue's database on disk", "(" + toM(size) + " MB)"));
1266  
}
1267  
1268  
static Slice sliceForName(S name) {
1269  
  ret conceptWhereCI Slice(+name);
1270  
}
1271  
1272  
sclass Query extends WorksOnSlice {
1273  
  SS vars = ciMap();
1274  
    
1275  
  *(LoadedSlice slice) { super(slice); }
1276  
  
1277  
  O process(S query) {
1278  
    try object processLines(agiBlue_parseQueryScript(query));
1279  
    ret serveJSON("No return statement");
1280  
  }
1281  
    
1282  
  O processLines(L<ALQLLine> lines) {
1283  
    for (ALQLLine line : lines) {
1284  
      if (line cast ALQLSlice) {
1285  
        Slice slice = sliceForName(line.slice);
1286  
        if (slice == null) ret serveJSON("Slice not found: " + line.slice);
1287  
        LoadedSlice oldSlice = Query.this.slice;
1288  
        try {
1289  
          setSlice(loadSlice(slice));
1290  
          try object processLines(line.contents);
1291  
        } finally {
1292  
          setSlice(oldSlice);
1293  
        }
1294  
      } else if (line cast ALQLReturn)
1295  
        ret serveJSON(ll(getOrKeep(vars, line.var)));
1296  
      else if (line cast ALQLTriple) {
1297  
        T3S t = line.triple;
1298  
        t = tripleMap(t, s -> getOrKeep(vars, s));
1299  
        Cl<Page> pages;
1300  
        S var;
1301  
        if (isDollarVar(t.c)) {
1302  
          var = t.c;
1303  
          if (isDollarVar(t.a)) {
1304  
            if (isDollarVar(t.b)) todo(t);
1305  
            Entry e = random(conceptsWhereCI(cc, Entry, key := t.b));
1306  
            if (e == null) ret serveJSON("No results for " + var);
1307  
            pages = pagesForKeyAndValue(t.b, t.c);
1308  
            vars.put(t.a, e.page->q);
1309  
            vars.put(t.c, e.value);
1310  
            continue;
1311  
          } else if (isDollarVar(t.b)) {
1312  
            Page page = findPageFromQ(t.a);
1313  
            Entry e = random(findBackRefs(page, Entry));
1314  
            if (e == null) ret serveJSON("No results for " + var);
1315  
            vars.put(t.b, e.key);
1316  
            vars.put(t.c, e.value);
1317  
            continue;
1318  
          } else {
1319  
            S val = getValue(t.a, t.b);
1320  
            if (val == null) ret serveJSON("No results for " + var);
1321  
            pages = ll(pageFromQ(val));
1322  
          }
1323  
        } else if (isDollarVar(t.b)) {
1324  
          var = t.b;
1325  
          if (isDollarVar(t.c)) todo(t);
1326  
          if (isDollarVar(t.a)) {
1327  
            L<Entry> entries = conceptsWhereCI(cc, Entry, value := t.c);
1328  
            if (empty(entries)) ret serveJSON("No results for " + var);
1329  
            Entry e = random(entries);
1330  
            vars.put(t.a, e.page->q);
1331  
            vars.put(t.b, e.key);
1332  
            continue;
1333  
          } else {
1334  
            Cl<S> keys = keysForPageAndValue(t.a, t.c);
1335  
            if (empty(keys)) ret serveJSON("No results for " + var);
1336  
            pages = map(f<S, Page> pageFromQ, keys);
1337  
          }
1338  
        } else {
1339  
          var = t.a;
1340  
          if (!isDollarVar(t.a)) todo(t);
1341  
          if (isDollarVar(t.b)) todo(t);
1342  
          if (isDollarVar(t.c)) todo(t);
1343  
          pages = pagesForKeyAndValue(t.b, t.c);
1344  
        }
1345  
        if (empty(pages)) ret serveJSON("No results for " + var);
1346  
        vars.put(var, random(pages).q);
1347  
      } else if (line cast ALQLPage) {
1348  
        if (eq(line.matchMethod, 'eqic))
1349  
          findPageFromQ(line.page);
1350  
        else if (eq(line.matchMethod, 'flexMatchDollarVarsIC_first)) {
1351  
          new L<SS> l;
1352  
          for (Page p : list(cc, Page))
1353  
            addIfNotNull(l, flexMatchDollarVarsIC_first(line.page, p.q));
1354  
          if (empty(l)) ret serveJSON("No results for " + curly(line.page));
1355  
          vars.putAll(random(l));
1356  
        } else
1357  
          fail("Unknown match method: " + line.matchMethod);
1358  
      } else
1359  
        fail("Can't interpret: " + line);
1360  
    }
1361  
    
1362  
    null;
1363  
  }
1364  
}
1365  
1366  
static Page pageFromQ(Concepts cc, S q) {
1367  
  ret empty(q) ? null : uniqCI_sync(cc, Page, +q);
1368  
}
1369  
1370  
/*sS globalIDFromCaseID(S caseID) {
1371  
  ret assertGlobalID(takeLast(globalIDLength(), caseID));
1372  
}*/
1373  
1374  
sS agiBlue_pageURLWithSlice(Page p) {
1375  
  ret p == null ? null : agiBlueURL() + hquery(slice := _get(sliceForPage(p), 'globalID), q := p.q);
1376  
}
1377  
1378  
static Slice sliceForPage(Page p) {
1379  
  if (p == null) null;
1380  
  SliceInfo info = conceptWhere(p._concepts, SliceInfo);
1381  
  ret info == null ? null : sliceConceptForGlobalID(info.globalID);
1382  
}
1383  
1384  
static GlobalID mainSliceGlobalID() {
1385  
  ret conceptWhere Slice(caseID := "").globalID;
1386  
}
1387  
1388  
static File sliceDumpFile(Slice slice) {
1389  
  ret programFile("slice-dumps/" + or2(slice.caseID, "main") + ".slice");
1390  
}
1391  
1392  
static File dumpSliceToFile(LoadedSlice slice) {
1393  
  ret withDBLock(slice.cc, func -> File {
1394  
    cset(slice.sliceConcept, sliceDumped := now());
1395  
    File file = sliceDumpFile(slice.sliceConcept);
1396  
    new LS lines;
1397  
    for (Page p : list(slice.cc, Page))
1398  
      lines.add(quote(p.q));
1399  
    for (Entry e : list(slice.cc, Entry))
1400  
      lines.add(sfu(tripleToList(entryToTriple(e))));
1401  
    saveLinesAsTextFile(file, lines);
1402  
    ret file;
1403  
  });
1404  
}
1405  
1406  
static T3S entryToTriple(Entry e) {
1407  
  ret e == null ? null : t3(e.page->q, e.key, e.value);
1408  
}
1409  
1410  
static ConceptsLoadedOnDemand slicesLoadedOnDemand(Map<S, LoadedSlice> loadedSlices) {
1411  
  new ConceptsLoadedOnDemand fan;
1412  
  fan.onCaseLoaded(voidfunc(S caseID, O globalID, Concepts concepts) {
1413  
    LoadedSlice ls = new(caseID, concepts);
1414  
    if (nempty(globalID))
1415  
      ls.initialSetup(toGlobalIDObj((S) globalID));
1416  
    loadedSlices.put(caseID, ls);
1417  
  });
1418  
  fan.onUnloadingCase(voidfunc(S caseID, Concepts concepts) {
1419  
    loadedSlices.remove(caseID);
1420  
  });
1421  
  ret fan;
1422  
}
1423  
1424  
// check if slices are loaded both in foreground and background (BAD)
1425  
sS checkDoubleLoads() {
1426  
  LS l = sharedKeys(loadedSlices, backgroundSlices);
1427  
  ret empty(l) ? null : "ERROR: Slice loaded in background and foreground: " + first(l);
1428  
}
1429  
1430  
// just use size of concepts.structure.gz
1431  
static long estimatedSliceDataSize(Slice slice) {
1432  
  ret estimatedSliceDataSize(slice.caseID);
1433  
}
1434  
1435  
static long estimatedSliceDataSize(S caseID) {
1436  
  ret l(conceptsFile(fan.dbID(caseID)));
1437  
}
1438  
1439  
static CentralIndexEntry centralIndexGet(S s) { ret getOrCreate CentralIndexEntry(centralIndex, s); }
1440  
1441  
static CentralIndexEntry newCentralIndexGet(S s) { ret getOrCreate CentralIndexEntry(newCentralIndex, s); }
1442  
1443  
// executed by rst_index
1444  
svoid makeCentralIndex() {
1445  
  newCentralIndex.clear();
1446  
  pcall {
1447  
    for (Slice slice : conceptsWhere(Slice, indexed := true))
1448  
      addToNewCentralIndex(slice);
1449  
  }
1450  
  centralIndex.putAll(newCentralIndex);
1451  
  removeAllKeysNotIn(centralIndex, newCentralIndex);
1452  
  newCentralIndex.clear();
1453  
  centralIndexMade = now();
1454  
}
1455  
1456  
svoid addToNewCentralIndex(Slice slice) {
1457  
  for (S s : sliceDump_pageNamesIncludingKeys(sliceDumpFile(slice)))
1458  
    newCentralIndexGet(s).slices.add(slice);
1459  
}

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: #1024400
Snippet name: agi.blue source [backup before private slices]
Eternal ID of this version: #1024400/1
Text MD5: a7dd996b3d585ff3854b8103c654bd52
Author: stefan
Category:
Type: JavaX source code (Dynamic Module)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-08-10 12:01:35
Source code size: 50963 bytes / 1459 lines
Pitched / IR pitched: No / No
Views / Downloads: 249 / 235
Referenced in: [show references]