changeset 24:ab9a6132529a

redo siteRoot handling. fix some pathing bugs. Ignore-this: 30fa1b320f62623e9b6a683f81d842a5
author drewp@bigasterisk.com
date Mon, 23 May 2016 23:39:24 -0700
parents d6a09e8efa56
children e02fc021ab89
files lookup.py static/links.js template/linklist.jade.mustache
diffstat 3 files changed, 59 insertions(+), 42 deletions(-) [+]
line wrap: on
line diff
--- a/lookup.py	Sun May 22 16:38:54 2016 -0700
+++ b/lookup.py	Mon May 23 23:39:24 2016 -0700
@@ -8,7 +8,7 @@
 and the add-bookmark stuff
 
 """
-import pymongo, bottle, time, urllib, datetime, json, restkit
+import pymongo, bottle, time, urllib, datetime, json, restkit, logging
 from collections import defaultdict
 from urllib2 import urlparse
 from dateutil.tz import tzlocal
@@ -20,31 +20,44 @@
 pageTitle = PageTitle(db)
 links = Links(db)
 renderer = Renderer(search_dirs=['template'], debug=bottle.DEBUG)
+log = logging.getLogger()
 
 siteRoot = 'https://bigasterisk.com/href'
 
 def getLoginBar():
     openidProxy = restkit.Resource("http://bang:9023/")
     return openidProxy.get("_loginBar",
-                 headers={"Cookie" : bottle.request.headers.get('cookie')}).body_string()
+                           headers={
+                               "Cookie" : bottle.request.headers.get('cookie'),
+                               'x-site': 'http://bigasterisk.com/openidProxySite/href',
+                           }).body_string()
 
 def getUser():
     agent = bottle.request.headers.get('x-foaf-agent', None)
     username = db['user'].find_one({'_id':agent})['username'] if agent else None
     return username, agent
+
+def siteRoot():
+    try:
+        return bottle.request.headers['x-site-root'].rstrip('/')
+    except KeyError:
+        log.warn(repr(bottle.request.__dict__))
+        raise
     
 @bottle.route('/static/<path:path>')
 def server_static(path):
     return static_file(path, root='static')
 
-def recentLinks(user, tags=None):
+def recentLinks(user, tags, allowEdit):
     out = {'links':[]}
     t1 = time.time()
     spec = {'user':user}
     if tags:
         spec['extracted.tags'] = {'$all' : tags}
     for doc in db['links'].find(spec, sort=[('t', -1)], limit=50):
-        out['links'].append(links.forDisplay(doc))
+        link = links.forDisplay(doc)
+        link['allowEdit'] = allowEdit
+        out['links'].append(link)
     out['stats'] = {'queryTimeMs' : round((time.time() - t1) * 1000, 2)}
     return out
 
@@ -73,7 +86,7 @@
 @bottle.route('/addLink')
 def addLink():
     out = {
-        'toRoot':  '.',
+        'toRoot': siteRoot(),
         'absRoot': siteRoot,
         'user': getUser()[0],
         'withKnockout':  True,
@@ -134,17 +147,17 @@
     
 @bottle.route('/<user>/')
 def userSlash(user):
-    bottle.redirect("/%s" % urllib.quote(user))
+    bottle.redirect(siteRoot() + "/%s" % urllib.quote(user))
 
 @bottle.route('/<user>.json', method='GET')
 def userAllJson(user):
-    data = recentLinks(user, [])
-    data['toRoot'] = "."
+    data = recentLinks(user, [], allowEdit=getUser()[0] == user)
+    data['toRoot'] = siteRoot()
     return json.dumps(data)
     
 @bottle.route('/<user>', method='GET')
 def userAll(user):
-    return userLinks(user, "", toRoot=".")
+    return userLinks(user, "")
     
    
 @bottle.route('/<user>', method='POST')
@@ -168,18 +181,19 @@
 @bottle.route('/<user>/<tags:re:.*>.json')
 def userLinksJson(user, tags):
     tags = parseTags(tags)
-    data = recentLinks(user, tags)
-    data['toRoot'] = ".."
+    data = recentLinks(user, tags, allowEdit=getUser()[0] == user)
+    data['toRoot'] = siteRoot()
     return json.dumps(data)
 
     
 @bottle.route('/<user>/<tags>')
-def userLinks(user, tags, toRoot=".."):
+def userLinks(user, tags):
     tags = parseTags(tags)
-    data = recentLinks(user, tags)
+    log.info('userLinks user=%r tags=%r', user, tags)
+    data = recentLinks(user, tags, allowEdit=getUser()[0] == user)
     data['loginBar'] = getLoginBar()
     data['desc'] = ("%s's recent links" % user) + (" tagged %s"  % (tags,) if tags else "")
-    data['toRoot'] = toRoot
+    data['toRoot'] = siteRoot()
     data['allTags'] = allTags(user)
     data['user'] = user
     data['showPrivateData'] = (user == getUser()[0])
@@ -196,11 +210,12 @@
 def root():
     data = {
         'loginBar': getLoginBar(),
-        'toRoot': ".",
+        'toRoot': siteRoot(),
         'stats': {'template': 'TEMPLATETIME'},
         'users': [{'user':doc['username']} for doc in db['user'].find()],
         }
     return renderWithTime('index.jade', data)
     
 if __name__ == '__main__':
+    logging.basicConfig(level=logging.INFO)
     bottle.run(server='gunicorn', host='0.0.0.0', port=10002, workers=4)
--- a/static/links.js	Sun May 22 16:38:54 2016 -0700
+++ b/static/links.js	Mon May 23 23:39:24 2016 -0700
@@ -4,14 +4,19 @@
     filterTags: ko.observableArray(tagsFromWindowLocation())
 };
 
+function componentsAfterRoot() {
+    var p = window.location.href;
+    return comps = p.substr(toRoot.length + 1).split("/");
+}
+
 function tagsFromWindowLocation() {
-    var p = window.location.pathname;
-    var comps = p.split("/");
-    if (toRoot == ".") {
+    var comps = componentsAfterRoot();
+    comps.shift();
+    if (!comps.length) {
         return [];
-    } else {
-        return (comps[comps.length-1] || "").replace("%20", "+").split("+");
     }
+    var tags = comps[0].replace("%20", "+").split("+");
+    return tags.filter(function(t) { return t != ""; });
 }
 
 function toggleTag(tag) {
@@ -40,36 +45,31 @@
             
 var linklist = null;
 // unsure how to use toRoot- can it change?
-$.getJSON("/href/templates", function (result) {
+$.getJSON(toRoot + "/templates", function (result) {
     linklist = result.linklist;
 });
 
+function pathFromUserAndTags(tags) {
+    var comps = componentsAfterRoot();
+    var newPath = comps[0];
+    if (tags.length) {
+        newPath += '/' + tags.join('+');
+    }
+    return newPath;
+}
+
 function initUrlSync(model) {
     // tag changes push url history; and url edits freshen the page
 
     ko.computed(function () {
         var tags = model.filterTags();
-        var newPath = window.location.pathname;
-        if (toRoot == ".") {
-            newPath += "/";
-            toRoot = "..";
-        } else {
-            newPath = newPath.replace(
-                    /(.*\/)[^\/]*$/, "$1")
-        }
-        if (tags.length) {
-            newPath += tags.join("+")
-        } else {
-            newPath = newPath.substr(0, newPath.length - 1);
-            toRoot = ".";
-        }
-        
+        var newPath = pathFromUserAndTags(tags);
         changePage(newPath);
     });
 
     function changePage(newPath) {
-        if (window.location.pathname != newPath) {
-            window.history.pushState({}, "", newPath);
+        if (componentsAfterRoot().join('/') != newPath) {
+            window.history.pushState({}, "", toRoot + '/' + newPath);
 
             function updateLinklist(fullPath) {
                 var t0 = +new Date();
@@ -78,7 +78,7 @@
                     return;
                 }
                 $(".linklist").text("Loading...");
-                $.getJSON(fullPath + ".json", function (result) {
+                $.getJSON(toRoot + '/' + fullPath + ".json", function (result) {
                     var t1 = +new Date();
                     var rendered = Mustache.render(linklist, result)
                     var t2 = +new Date();
@@ -101,7 +101,7 @@
     
     elem.change(function () {
         var tags = $(this).val().split(",");
-        model.filterTags(tags);
+        model.filterTags(tags.filter(function(t) { return t != ""; }));
         return false;
     });
 
--- a/template/linklist.jade.mustache	Sun May 22 16:38:54 2016 -0700
+++ b/template/linklist.jade.mustache	Mon May 23 23:39:24 2016 -0700
@@ -25,7 +25,9 @@
       | {{label}}
     {{/shareWith}}
   {{/showPrivateData}}
+  {{#allowEdit}}
   .edit
-    a(href="{{toRoot}}/{{editLink}}") Edit
+      a(href="{{toRoot}}/{{editLink}}") Edit
+  {{/allowEdit}}
     
-{{/links}}
\ No newline at end of file
+{{/links}}