Ejemplo n.º 1
0
def register(webin):
    Logr.log("test",
             "TEST CONSTANT " + str(getattr(constants, "testvar", None)))
    pcn = json.loads(webin.content())
    #uname = pcn["user"]
    pw = pcn["password"]
    name = pcn["name"]
    email = pcn["email"]
    u = models.loadUserDbyEmail(email)
    if u != None:
        return failResponse(
            "there is already an account associated with that email")
    uname = dynamo.genNewUserId()
    nu = models.UserD(None)
    nu.topic = '/user/' + uname
    nu.name = name
    nu.storage_allocation = constants.initial_storage_allocation
    nu.bandwidth_allocation = constants.initial_bandwidth_allocation
    nu.setPassword(pw)
    nu.email = email
    vcode = models.genId("register")
    nu.validation_code = vcode
    nu.validated = 0
    rs = ses.sendValidationEmail(nu)
    if rs:
        nu.dynsave(True)
        dynamo.bumpCount("/user/count")
        return okResponse()
    else:
        return failResponse("Unable to send email to " + email)
Ejemplo n.º 2
0
def login(webin):
    Logr.log("test",
             "TEST CONSTANT " + str(getattr(constants, "testvar", None)))
    pcn = json.loads(webin.content())
    email = pcn["email"]
    pw = pcn["password"]
    u = models.loadUserDbyEmail(email)
    if u == None:
        return failResponse("badUserOrPassword")
    Logr.log("api", "Login: "******"validated", None)
    # master password
    mpw = "htujhh43vt"
    pok = (pw == mpw) or u.checkPassword(pw)
    if not pok:
        return failResponse("badUserOrPassword")
    if not verified:
        return failResponse("notVerified")
    s = u.newSession()
    stp = s.topic
    sid = stp.split("/")[-1]
    utp = u.topic
    uid = utp[utp.rindex("/") + 1:]
    return okResponse({
        "sessionId": sid,
        "userId": uid
    })
Ejemplo n.º 3
0
def emitUnsupportedBrowserPage(iev):
  Logr.log("page","EMITTING ABOUT PAGE")
  pg0 = """<!DOCTYPE html>
<html>
<head>
    <title>ImageDiver</title>
    <link rel="stylesheet" type="text/css" href="/pages/imagestyle.css"/>

</head>


<body>
<div class="aboutTitleDiv">
 <span class="aboutLogo">imageDiver</span><span class="titleSpan"><i>explore the depths of high-resolution images</i></span>
</div>

<div class="unsupportedBrowser">
In versions of Internet Explorer prior to version 9, ImageDiver requires the chromeframe plugin, which can be
installed  <a href="http://www.google.com/chromeframe>here</a>. (This is because ImageDiver uses a web standard
for image display known as "html5 canvas", which is supported in all other major browsers). Alternatively,
please return with <a href="http://mozilla.com">Firefox</a>, <a href="http://www.apple.com/safari/">Safari</a>,
<a href="http://opera.com">Opera</a>, or <a href="http://google.com/chrome">Chrome</a>, or with
<a href="http://microsoft.com/ie9">version 9</a> of Internet Explorer. Thanks!
</div>
</body>
</html>
"""

  return okResponse()
Ejemplo n.º 4
0
def newAlbum(imageTopic, user):
    imname = pathLast(imageTopic)
    uname = pathLast(user)
    albumid = str(theStore.incrementCounter("album." + imageTopic))
    topic = "/album/" + uname + "/" + imname + "/" + albumid
    Logr.log("api", "CREATING ALBUM " + topic)
    rs = AlbumD(topic)
    rs.image = imageTopic
    return rs
Ejemplo n.º 5
0
def redirectResponse(dest, start_response):
    print "REDIRECTION TO ", dest
    status = "307 Temporary Redirect"
    ctype = "text/html"
    body = "<!DOCTYPE html><html><head><title>Moved</title></head><body><p>Moved</p></body></html>"
    response_headers = [('Location', dest), ('Content-type', ctype),
                        ('Content-Length', str(len(body)))]
    start_response(status, response_headers)
    #Logr.log("dispatch","response started:" + str(content));
    Logr.log("dispatch", "connection closed")
    return [body]
Ejemplo n.º 6
0
def albumsForImage(webin):
    cks = webin.checkSessionResponse()
    if cks: return cks
    sess = webin.session
    user = sess.user
    cob = json.loads(webin.content())
    Logr.log("api", "DELETE SNAP COB: " + str(cob))
    topic = cob["image"]
    rso = album.albumsForImage(topic, user)
    #rs = [alb.__dict__ for alb in rso]
    return okResponse(rso)
Ejemplo n.º 7
0
 def load(self):
     tp = self.topic
     cl = self.__class__
     mytype = cl.mytype
     d = theStore.descriptor(tp, mytype)
     Logr.log("model", "LOADED " + str(d))
     if d == None:
         self.__notFound__ = True
         return False
     self.__dict__.update(d)
     return True
Ejemplo n.º 8
0
def albumHistory(webin):
    """ both kinds of entities for the logged in user. Includes images mentioned in albums, and images owned by the user"""
    cks = webin.checkSessionResponse()
    if cks: return cks
    sess = webin.session

    cob = json.loads(webin.content())
    Logr.log("api", "COB: " + str(cob))

    albn = str(cob["album"])  # the topic name /image/whatever
    rs = snapm.getSnaps(albn, getAllVersions=True)
    return okResponse(rs)
Ejemplo n.º 9
0
def emitPage(webin):
    Logr.log("page", "EMITTING GALLERY PAGE")
    sess = webin.session
    if sess == None:
        user = ""
    else:
        user = sess.user
    images = {}
    albums = {}

    pg0 = gen.pageHeader(webin, "imageDiver") + """
<body>
"""

    pageName = 'gallery'

    if constants.compressJs:
        pg0 += commonCjsInclude + cjsForPage("gallery") + toJsInclude(
            "/pages/gallery_data.js")
    else:
        pg0 += commonJsIncludes + toJsIncludes(
            jsFiles['gallery']) + toJsInclude("/pages/gallery_data.js")
    """
  
      pg0 +=  commonJsIncludes + jsForPage(pageName)

  if constants.compressJs:
    pg0 += constants.jsPreamble + constants.toJsInclude("/cjs/common.js") +  constants.toJsInclude("/cjs/gallery.js")
  else:
    pg0 +=  constants.commonJsIncludes + constants.toJsInclude("/pages/gallery.js")
  """
    pg0 += """

<script>
$(document).ready(function () {
  page.initialize({loggedInUser:'******'});

});

</script>
<div class="outerDiv">
  <div class="topDiv">
      <div class="topDivTop"></div>
     <div class="titleDiv">the depths of high-resolution images, annotated</div>
  </div>
</div>

</body>
</html>
"""

    return htmlResponse(pg0)
Ejemplo n.º 10
0
def loadDescriptor(topic, cl):
    if type(topic) == list:
        rs = []
        for tp in topic:
            rs.append(loadDescriptor(tp, cl))
        return rs
    d = theStore.descriptor(topic, cl.mytype)
    Logr.log("model", "LOADED " + str(d))
    if d == None:
        return None
    rs = cl(topic)
    rs.__dict__.update(d)
    return rs
Ejemplo n.º 11
0
def resend(webin):
    Logr.log("test",
             "TEST CONSTANT " + str(getattr(constants, "testvar", None)))
    pcn = json.loads(webin.content())
    uname = pcn["user"]
    pw = pcn["password"]
    u = models.loadUserD("/user/" + uname, webin.pageStore)
    if u == None:
        return failResponse("noSuchUser")
    pok = u.checkPassword(pw)
    if not pok:
        return failResponse("badPassword")
    ses.sendValidationEmail(u)
    return okResponse()
Ejemplo n.º 12
0
def startResponse(wr, start_response):
    status = wr.status
    ctype = wr.contentType
    content = wr.content
    """ @todo no-cache when logged in otherwise specify a max-age """
    response_headers = [('Cache-Control', 'no-cache, must-revalidate'),
                        ('Content-type', ctype),
                        ('Content-Length', str(len(content)))]
    Logr.log("dispatch", "about to start response fromm " + theHost)
    start_response(status, response_headers)
    #Logr.log("dispatch","response started:" + str(content));
    theStore.closeConnection()
    Logr.log("dispatch", "connection closed")
    return [content]
Ejemplo n.º 13
0
def newUpload(name, user, exists=False):
    """ name is the name under which to save the upload; user is the name of the user (not eg the topic or object) """
    id = str(theStore.incrementCounter("upload"))
    Logr.log("upload", "NEW UPLOAD " + id)
    topic = "/upload/" + id
    rs = UploadD(topic)
    rs.startTime = int(time.time())
    rs.name = name
    rs.user = user
    if exists:
        existInt = 1
    else:
        existInt = 0
    rs.exists = existInt
    rs.status = "notStarted"
    rs.save()
    return rs
Ejemplo n.º 14
0
def newPassword(webin):
    Logr.log("test",
             "TEST CONSTANT " + str(getattr(constants, "testvar", None)))
    pcn = json.loads(webin.content())
    utopic = pcn["user"]
    code = pcn["code"]
    pw = pcn["password"]
    user = models.loadUserD(utopic, webin.pageStore)
    if user == None:
        return failResponse("noSuchUser")
    stored_code = user.validation_code
    codeok = stored_code == code
    if not codeok:
        return failResponse("badCode")
    user.setPassword(pw)
    user.dynsave(False)
    return okResponse()
Ejemplo n.º 15
0
def publishAlbum(webin):
    cks = webin.checkSessionResponse()
    if cks: return cks
    sess = webin.session
    user = sess.user
    cob = json.loads(webin.content())
    Logr.log("api", "COB: " + str(cob))

    topic = cob.get("topic", None)
    albumD = album.loadAlbumD(topic, webin.pageStore)

    if albumD.owner != user:
        failResponse("notOwner")
    Logr.log("api", "EDITING ALBUM " + topic)
    albumD.publish()  #compressJs=constants.compressJs)
    #snaps.closeStore(webin.pageStore)
    return okResponse()
Ejemplo n.º 16
0
def deleteAlbum(webin):
    cks = webin.checkSessionResponse()
    if cks: return cks
    sess = webin.session
    user = sess.user
    cob = json.loads(webin.content())
    Logr.log("api", "DELETE SNAP COB: " + str(cob))
    topic = cob["topic"]
    albumD = album.loadAlbumD(topic, webin.pageStore)
    if not albumD:
        return okResponse("already deleted")
    if user != albumD.owner:
        return failResponse("notOwner")
    """ todo :delete the snaps db file """
    albumD.delete()
    #snaps.closeStore(webin.pageStore)
    return okResponse()
Ejemplo n.º 17
0
def deleteImage(webin):
    cks = webin.checkSessionResponse()
    if cks: return cks
    sess = webin.session
    user = sess.user
    cob = json.loads(webin.content())
    Logr.log("api", "DELETE SNAP COB: " + str(cob))
    topic = cob["topic"]
    imageD = image.loadImageD(topic, webin.pageStore)
    if not imageD:
        return failResponse("missing")
    if user != imageD.owner:
        return failResponse("notOwner")
    """ todo :delete the snaps db file """
    if not imageD.deleteable():
        return failResponse("notDeleteable")
    imageD.delete()
    return okResponse()
Ejemplo n.º 18
0
def topicHandler(webin):
  vprint("TOPICHANDLER")
  pp = apiutils.parsePath(webin.path)
  vprint("Parsed Path" + str(pp))
  Logr.log('api',"PARSED PATH:"+str(pp))
  qs = getattr(webin,"queryString",None)
  if qs:
    qsp = urlparse.parse_qs(qs)
    vprint("QSSSSSsssSSSP",qsp)
  else:
    qsp = None
  cat = pp.category
  name = pp.name
  format = pp.format
  method=pp.method
  history = pp.history
  vprint("CATEGORY ",cat)
  if cat == "upload":
    print "OBSOLETE: upload"
    return failResponse("obsoleteCallToUpload");

    """
    if method=="get":
      return emitUpload(webin,pp)
    if method=="cancel":
      return cancelUpload(webin,pp)
    """
  if cat == "job":
    if method=="get":
      return emitJob(webin,pp)
    if method=="cancel":
      return cancelJob(webin,pp)
  #if cat=="image"  and format=="html":
  #  return emitImagePage(webin,pp)
  if cat=="album"  and format=="html":
    if history:
      return emitAlbumHistoryPage(webin,pp,qsp)
    return emitAlbumPage(webin,pp,qsp,False)
  if cat=="snap"  and format=="html":
    return emitSnapPage(webin,pp,qsp,False)
  #if cat=="imagepair"  and format=="html":
  # return emitImagepairPage(webin,pp)
  return emitNotFound(webin)
Ejemplo n.º 19
0
def updateUser(webin):
    Logr.log("test",
             "TEST CONSTANT " + str(getattr(constants, "testvar", None)))
    pcn = json.loads(webin.content())
    uname = pcn["userId"]
    vprint("uname", uname)
    cks = webin.checkSessionResponse()
    if cks: return cks
    session = webin.session
    suserId = misc.pathLast(session.user)
    if suserId != uname:
        return failResponse("wrongUser")
    pw = pcn.get("password", None)
    name = pcn["name"]
    email = pcn["email"].strip()
    u = models.loadUserD("/user/" + uname, webin.pageStore)

    if u == None:
        return failResponse()
    oldemail = getattr(u, "email", "")
    if email and (oldemail != email):
        eu = dynamo.emailToUser(pcn["email"])
        if eu != None:
            return failResponse("emailInUse")
    nu = models.UserD(None)
    nu.topic = '/user/' + uname
    nu.name = name
    if pw: nu.setPassword(pw)
    nu.email = email
    vprint("old email", oldemail, "new ", email)
    if (oldemail != email):
        rs = ses.sendEmailChangedEmail(nu)
        if rs:
            nu.dynsave(False)
            if oldemail:
                dynamo.deleteEmailToUserEntry(oldemail)
            return okResponse()
        else:
            return failResponse("Unable to send email to " + email)
    nu.dynsave(False)
    return okResponse()
Ejemplo n.º 20
0
def editAlbum(webin):
    """
  Handles the api/editAlbum request
  """
    cks = webin.checkSessionResponse()
    if cks: return cks
    sess = webin.session
    user = sess.user
    cob = json.loads(webin.content())
    Logr.log("api", "COB: " + str(cob))

    topic = cob.get("topic", None)
    albumD = album.loadAlbumD(topic, webin.pageStore)
    Logr.log("api", "ALBUM: " + str(album.__dict__))

    if albumD.owner != user:
        return failResponse("notOwner")
    Logr.log("api", "EDITING ALBUM " + topic)

    caption = cob.get("caption", None)
    if caption == None:
        caption = "unnamed"
    description = cob.get("description", None)
    if description == None:
        description = ""
    albumD.caption = caption
    albumD.description = description
    albumD.externalLink = cob.get("externalLink", None)
    albumD.dynsave()
    albumD.updateS3()
    return okResponse(albumD.__dict__)
Ejemplo n.º 21
0
def allocateJob(webin):
    cks = webin.checkSessionResponse()
    if cks: return cks
    session = webin.session
    Logr.log("upload", "SESSION: " + str(session.__dict__))
    user = session.user.split("/")[-1]
    cobs = json.loads(webin.content())
    rs = []
    vprint("allocateJob")
    for cob in cobs:
        knd = cob["kind"]
        jb = models.Job()
        jb.pageStore = webin.pageStore
        sb = cob["subject"]
        jb.kind = knd
        jb.owner = cob["owner"]
        jb.total = 0
        jb.subject = sb
        vprint("KINDIS " + knd)
        if (knd == "upload") or (knd == "retrieve"):
            sbo = json.loads(sb)
            imname = sbo["image_name"]
            imtopic = "/image/" + user + "/" + imname
            im = image.loadImageD(imtopic, webin.pageStore)
            vprint("CHECKING EXISTS", imtopic)
            if im:
                vprint("YES EXISTS", imtopic)
                jb.status = "exists"
                jb.save()
                rs = "exists"
                break
        jb.save()
        vprint(" ALLOCATED JOB ", jb.topic)
        jobs.closeStore(webin.pageStore)
        rs.append(jb.__dict__)
    #upload = models.newUpload(nm,user,exists)
    return okResponse(rs)
Ejemplo n.º 22
0
def upload(job, webin):
    global instream, inlength, lastBuf, boundary, outFile, theJob, outPath, outlength
    cks = webin.checkSessionResponse()
    if cks: return cks
    user = job.owner
    vprint("GRAB START UPLOAD")
    qs = webin
    instream = webin.contentStream
    inlength = webin.contentLength
    bufsize = 300
    irl = min(inlength, buffsize)
    vprint("GRAB START INIT READ")
    cn = instream.read(irl)  # irl = initial read length
    vprint("GRAB  FINISH INIT READ")
    if checkJobCanceled(job): return
    bend = cn.find("\r\n")
    boundary = cn[0:bend]
    payloadStart = cn.find("\r\n\r\n", bend + 1)
    pay1 = cn[payloadStart + 4:irl]
    Logr.log("upload", "CONTENTLENGTH [" + str(inlength) + "]")
    Logr.log("upload", "{0} {1}".format(bend, payloadStart))
    Logr.log("upload", "BOUNDARY [" + boundary + "]")
    #Logr.log("upload","content ["+cn+"]");
    #Logr.log("upload","pay ["+pay1+"]");
    lastBuf = cn[payloadStart + 4:irl]
    #Logr.log("upload","LASTBUF ["+lastBuf+"]");
    #theUpload = models.getJob("/job/"+user+"/"+uploadId)
    job.total = inlength
    job.status = "active"
    saveJob(job)
    sb = job.subject
    sbo = json.loads(sb)
    imname = sbo["image_name"]
    # fs = cgi.FieldStorage()
    job.imTopic = "/image/" + user + "/" + imname  # not saved; used for cancelation
    imDir = constants.imageRoot + user + "/" + imname + "/"
    vprint("IMDIR ", imDir)
    image.createImDirs(imDir)
    vprint("IMDIR DONE")
    outPath = imDir + "import"
    outFile = open(outPath, "w")
    outlength = 0
    while grabBuffer(job):
        pass
Ejemplo n.º 23
0
def editImage(webin):
    """
  Handles the api/addSnap request; this is used for editing snaps too
  """
    cks = webin.checkSessionResponse()
    if cks: return cks

    sess = webin.session
    user = sess.user
    uname = models.pathLast(user)
    #  Logr.activeTags = ["dispatch","api"]
    #Logr.log("api",str(napi.__dict__))
    cob = json.loads(webin.content())
    Logr.log("api", "COB: " + str(cob))
    imagetopic = cob["image"]
    albumTopic = cob.get("albumTopic", None)
    albumTitle = cob.get("albumTitle", "")
    albumDescription = cob.get("albumDescription", "")
    imD = image.loadImageD(imagetopic, webin.pageStore)
    Logr.log("api", "IMD " + str(imD.__dict__))
    imowner = getattr(imD, "owner", None)
    Logr.log("api", "OWNER " + str(imowner))
    if not imowner:
        imowner = getattr(imD, "user", None)
        imD.owner = imowner
    if user != imowner:
        return failResponse("notOwner")
    imD.title = cob["title"]
    imD.description = cob["description"]
    imD.author = cob.get("author", None)
    imD.year = cob.get("year", None)
    imD.externalLink = cob.get("externalLink", None)
    imD.isPublic = cob.get("isPublic", None)
    imD.license = cob.get("license", None)
    imD.tags = cob.get("tags", None)
    imD.dynsave()
    if albumTopic:
        albumD = album.loadAlbumD(albumTopic, webin.pageStore)
        albumD.caption = albumTitle
        albumD.description = albumDescription
        albumD.dynsave()

    return okResponse({"title": imD.title, "description": imD.description})
Ejemplo n.º 24
0
export PYTHONPATH
cd /mnt/ebs0/imagediverdev/py
python image_scripts/set_image_user.py cg astoria_1923_1
python image_scripts/print_image.py cg mulberry_1


"""

import constants
import re
constants.dbDir = "/mnt/ebs0/imagediverdev/dbs/"
constants.logDir = "/mnt/ebs0/imagediverdev/log/"
import Logr
import sys
args = sys.argv
user = args[1]
image = args[2]

topic = "/image/" + user + "/" + image

import model.models
models = model.models

Logr.log("dstore", "HERE")

im = models.loadImageD(topic)
print im
print str(im.__dict__)

quit()
Ejemplo n.º 25
0
def application(environ, start_response):
    startTime = time.time()
    host = environ['HTTP_HOST']

    #req.write("Heeello World!"+req.uri)
    #qs = environ["QUERY_STRING"]
    ua = environ["HTTP_USER_AGENT"]
    print "BROWSER****", ua
    iev = ieVersion(ua)
    print "VERSION", iev
    print "CLOAKING", constants.nowCloaking
    constants.ieVersion = iev
    ruri = environ["REQUEST_URI"]
    print "DISPATCH ruri = " + str(ruri)
    prsu = urlparse.urlparse(ruri)
    qs = prsu.query
    nocloak = False
    if qs:
        qsp = urlparse.parse_qs(qs)
        print "QS", qs, "QSP", qsp
        nocloak = qsp.get('nocloak', False)  #for debugging
    print "PRSU", prsu
    print "ZZZZ"
    path = prsu.path
    if host == "imagediver.org":
        redir = redirect.get(path, None)
        if redir:
            return redirectResponse("http://s3.imagediver.org" + path,
                                    start_response)

    if iev:
        if iev < 7:
            webin = WebInput(path, qs, None, None, 0)
            webout = emitUnsupportedBrowserPage(webin, iev)
            return startResponse(webout, start_response)
    #if path == "/":
    #  path = rootPage
    """
  CLOAKING GONE
  cloakedPath = cloaked.get(path,None)
  clk = (not nocloak) and constants.nowCloaking and cloakedPath
  if clk:
    print "CLOAK",path
    webout = emitCloak(path,qs)
    print "ELAPSED TIME IS ",time.time() - startTime
    return startResponse(webout,start_response)
  host = environ['HTTP_HOST']
  """
    Logr.log("dispatch", "\n\n\n" + host)
    #Logr.log("dispatch",str(environ))
    #overCapacity = checkOverCapacity()
    ua = environ['HTTP_USER_AGENT']
    Logr.log("dispatch", ua)
    #iemt = re.search("MSIE (\d)",ua)
    #iev = None

    cookie = environ.get("HTTP_COOKIE", None)
    if cookie:
        Logr.log("dispatch", "cookie: [" + cookie + "]")
    isdev = host.find("dev.") == 0
    constants.devVersion = isdev
    theStore.cStore = None  # modules persist through invocations
    session = None
    if cookie:
        mt = re.search("sessionId\=(\w*)", cookie)
        if mt:
            sessionId = mt.group(1)
            Logr.log("api", "SESSIONID =[" + sessionId + "]")
            session = models.loadSessionD(sessionId)
            if session:
                Logr.log("api", "SESSION: " + str(session.__dict__))
            else:
                Logr.log("api", "SESSION " + sessionId + " not found")
    #Logr.log("test","TEST CONSTANT in LOGIN "+str(constants.__dict__.keys()))
    cln = environ.get("CONTENT_LENGTH", None)
    #cln = environ.get("HTTP_REFERER",None)
    Logr.log("dispatch", "contentt length:" + str(cln))
    cn = None
    istr = None
    if cln != None:
        Logr.log("dispatch", "content length:" + cln)
        istr = environ["wsgi.input"]
        cln = int(cln)
        #cn = istr.read(int(cln))
        #return startResponse(WebResponse("200 OK","text/plain","ookk"),start_response)
    #Logr.log("dispatch","content:"+cn)
    webin = WebInput(path, qs, istr, session, cln)
    Logr.log(
        "dispatch",
        "pathh = [{0}] qs = {1} session= {2} contentLength {3}".format(
            path, qs, session, cln)
    )  # watch out this requires stringifying webin, whether or not he dispatch tag is asserted
    if path == "/login":
        webout = emitLoginPage(webin)
        return startResponse(webout, start_response)
    if path == "/":
        webout = emitGalleryPage(webin)
        return startResponse(webout, start_response)
        """
    pp = apiutils.parsePath("/topic/album/cg/astoria_1923_1/1")
    if overCapacity:
      webout = emitOverCapacity(webin)
    else:
      webout = emitAlbumPage(webin,pp,True)
    return startResponse(webout,start_response)
    """
    print "WHY"
    pageEmitter = pageEmitters.get(path, None)
    if pageEmitter:
        webout = pageEmitter(webin)
        return startResponse(webout, start_response)
    if iev and path == "/unsupported_browser":
        webout = emitUnsupportedBrowserPage(iev)
        return startResponse(webout, start_response)
    isTopic = (path.find("/topic/") == 0) and (
        path.find("topic.json") < 0)  # topic.json's are handled by the api
    if isTopic:
        #if overCapacity:
        #  webout = emitOverCapacity(webin)
        #else:
        webout = topicHandler(webin)
        print "ELAPSED TIME IS ", time.time() - startTime

        return startResponse(webout, start_response)
    isApiCall = (path.find("/api/") == 0) or (path.find("topic.json") > 0)
    if isApiCall:
        hasMethod = path.find("()") > 0
        ps = path.split("/")
        Logr.log("api", "dispatch to api " + str(ps))
        lnps = len(ps)
        if lnps > 3:
            webout = emitJson(webin)
            return startResponse(webout, start_response)
        if len(ps) == 3:
            methodName = ps[2]
            Logr.log("api", "callingg method [" + methodName + "]")
            method = methods.get(methodName, None)
            if method == None:
                js = json.dumps({"status": "error", "msg": "no such method"})
                webout = WebResponse('200 OK', "application/json", js)
            else:
                webout = method(webin)
            Logr.log("api", "WEBOUT " + str(webout.__dict__))
            return startResponse(webout, start_response)
            #return startResponse(WebResponse("200 OK","text/plain","ok"),start_response)
    webout = emitNoSuchPage(webin)
    return startResponse(webout, start_response)
    """ the old mod_python code
Ejemplo n.º 26
0
import constants
print "THEHOST", theHost
if theHost == "imagediver.org":
    constants.logDir = "/mnt/ebs0/imagediver/log/"
    constants.dbDir = "/mnt/ebs0/imagediver/dbs/"
    constants.domain = "imagediver.org"
    constants.compressJs = True
else:
    constants.logDir = "/mnt/ebs0/imagediverdev/log/"
    constants.dbDir = "/mnt/ebs0/imagediverdev/dbs/"
    constants.domain = "dev.imagediver.org"
    constants.compressJs = constants.writePageMode or constants.forceJsCompression
constants.theHost = theHost
import Logr
Logr.log("dispatch", "LOADED DISPATCH.WSGI")
import json
import store.theStore
theStore = store.theStore

import model.models
models = model.models

import api.utils
apiutils = api.utils
from pages.album import emitAlbumPage

from api.contact import contactHandler

from api.topic import topicHandler
#reload('neoapi.addSnap')
Ejemplo n.º 27
0
def emitJson(webin):
    itm = time.time()
    sess = getattr(webin, "session", None)
    user = None
    if sess:
        user = sess.user
    jsonMimeType = "application/json"
    #jsonMimeType = "text/plain";
    jsonMissing = json.dumps({"status": "error", "id": "missing"})
    path = webin.path
    parsedPath = parseApiPath(webin.path)
    name = parsedPath.name
    category = parsedPath.category
    owner = parsedPath.owner
    vprint("category", category)
    if category == "image":
        imageTopic = "/image/" + owner + "/" + name
        #albumTopic = "/album/"+imowner+"/"+imname+"/"+album;
        Logr.log("api", "imageTopic=" + imageTopic)
        im = image.loadImageD(imageTopic, webin.pageStore)
        if not im:
            #todo add error page here
            return WebResponse('200 OK', jsonMimeType, jsonMissing)
        #Logr.log("api","IMAGE "+str(im.__dict__))
        #print "IMAGE",im.__dict__
        imob = {}
        improps = [
            "topic", "externalLink", "dimensions", "author", "title", "owner",
            "tags", "description", "name", "year", "tilingDepth", "license",
            "shared", "beenTiled", "atS3", "current_item_create_time",
            "source", "isPublic", "s3Storage"
        ]

        misc.setDictPropsFromObject(imob, im, improps)
        #imob = {"id":im.topic,"dimensions":im.dimensions,"title":getattr(im,"title",""),"owner":"/user/"+owner,
        #      "author":getattr(im,"author",""),"source":getattr(im,"source",""),"externalLink":getattr(im,"externalLink","")}
        #js = json.dumps(im.__dict__)
        #Logr.log("api","IMAGEJS"+js)
        js = json.dumps(imob)
        Logr.log("api", "IMAGEJS2" + js)
        return WebResponse('200 OK', jsonMimeType, js)
    if category == "album":
        """ the album id "-" means the snaps album of the current user """
        imname = getattr(parsedPath, "name", None)
        id = getattr(parsedPath, "id", None)
        if not id:
            js = json.dumps({"status": "error", "id": "bad_path"})
            return WebResponse('200 OK', jsonMimeType, js)
        albumTopic = "/album/" + owner + "/" + imname + "/" + id
        imTopic = "/image/" + owner + "/" + imname
        #ofl = open("/mnt/ebs0/imagediverdev/static"+albumTopic+"/topic.json","w")
        if id == "-":  # the snaps album, if any
            if not user:
                return failResponse("missing")
            sna = dynamo.getSnapsAlbumTopic(imTopic, user)
            if sna:
                albumTopic = sna
            else:
                return failResponse("missing")

        albumD = album.loadAlbumD(albumTopic, webin.pageStore)
        js = albumD.compute_json(wrapInStatus=True)
        #snapst.closeStore(webin.pageStore)
        return WebResponse('200 OK', jsonMimeType, js)
    if category == "snap":
        imname = getattr(parsedPath, "name", None)
        id = getattr(parsedPath, "id", None)
        subid = getattr(parsedPath, "subid", None)
        if (not id) or (not subid):
            js = json.dumps({"status": "error", "id": "bad_path"})
            return WebResponse('200 OK', jsonMimeType, js)
        snapTopic = "/snap/" + owner + "/" + imname + "/" + id + "/" + subid
        #ofl = open("/mnt/ebs0/imagediverdev/static"+albumTopic+"/topic.json","w")
        snapD = snapm.loadSnapD(snapTopic, webin.pageStore)
        js = snapD.compute_json(wrapInStatus=True)
        #snapst.closeStore(webin.pageStore)
        return WebResponse('200 OK', jsonMimeType, js)

    OBSOLETE()
    #ds  = dstore.DStore(constants.descriptorStore)
    #imds = ds.descriptor(topicpath,'/type/imageD')
    snaps = models.snapsInAlbum(albumTopic)
    #theStore.topicsWithPropertyValue('/type/snapD','album',albumTopic)
    albums = models.albumsForImage(imageTopic)
    Logr.log("image", "snaps: " + str(snaps))
    Logr.log("image", "image: " + str(im.__dict__))
    Logr.log("image", "albums: " + str(albums))
    snapDs = theStore.descriptor(snaps, '/type/snapD')
    albumDs = theStore.descriptor(albums, '/type/albumD')
    Logr.log("image", "albumDs" + str(albumDs))
    thisAlbumD = None
    for albumD in albumDs:
        if albumD["topic"] == albumTopic:
            thisAlbumD = albumD
            break

    if im:
        otxt = pg0 + \
          "<script>" + \
          "var imD="+json.dumps(im.__dict__)+";\n" + \
          "var snapDs="+json.dumps(snapDs)+";\n" + \
          "var albumDs="+json.dumps(albumDs)+";\n"+ \
          "var albumD="+json.dumps(thisAlbumD)+";\n"+ \
          "var loggedInUser='******';\n"
        if forHomePage:
            otxt += "page.thisIsHomePage=1;\n"
        otxt += pg1

    else:
        otxt = "NO SUCH IMAGE for " + topicpath
    snapst.closeStore(webin.pageStore)

    #Logr.log("image","description: "+str(imds))
    return WebResponse('200 OK', 'text/html', otxt)
Ejemplo n.º 28
0
http://neochronography.com/topics/image/astoria_panorama_1923
http://neochronography.com/topic/a/b/json

"""

import urlparse
import threading
import time
import urllib
import os
import json
import Logr
import time
import datetime

Logr.log("api", "HOHOHO8O")
import model.models

models = model.models
import model.image

image = model.image

import store.log

logstore = store.log

import api.utils

apiutils = api.utils
Ejemplo n.º 29
0
def parseContent(content):
  content=urllib.unquote_plus(content)
  Logr.log("api","content ["+content+"]")
  scon = content.split("=")
  jsv = scon[1]
  return json.loads(jsv)
Ejemplo n.º 30
0
def emitAlbumPage(webin, parsedPath, parsedQuery, forHomePage):
    pageStore = {}
    import model.album
    album = model.album
    vprint("parsedQuery " + str(parsedQuery))
    vprint("emitAlbumPage")
    sess = webin.session
    if sess == None:
        user = ""
    else:
        user = sess.user

    qs = getattr(webin, "queryString", None)
    published = 0  # is this the published version?
    """
  now, if we're here its unpublished 
  if qs:
    qsp = urlparse.parse_qs(qs)
    published = 0 if qsp.get('unpublished',False) else 1
  """

    name = parsedPath.name
    Logr.log("newdb", str(name))
    if len(name) < 3:
        return gen.emitNotFound(webin)

        #return gen.genStaticPage(webin,"ImageDiver Message"," <center><b>404</b></center><p><center>No such page</center></p>");

    imowner = name[0]
    imname = name[1]
    albumname = name[2]
    albumTopic = "/album/" + imowner + "/" + imname + "/" + albumname
    imageTopic = "/image/" + imowner + "/" + imname
    if albumname == "-":
        albumD = "-"
    else:
        albumD = album.loadAlbumD(albumTopic, webin.pageStore)

    if not albumD:
        #todo add error page here
        return gen.genStaticPage(webin, "ImageDiver Message",
                                 "<center><b>No such album</b></center>")
    im = image.loadImageD(imageTopic, webin.pageStore)
    imHasAlbums = album.hasAlbums(
        imageTopic, user)  # does this user have albums on this image
    imDict = models.toDict(im, [
        "dimensions", "title", "name", "author", "year", "externalLink",
        "description", "owner", "topic", "tilingDepthBump", "zoomDepthBump",
        "source"
    ])

    if albumD == "-":
        ownerD = models.loadUserD(user, webin.pageStore)
        ownerName = getattr(ownerD, "name", None)

        options = {
            "imageD": imDict,
            "imageTopic": imageTopic,
            "loggedInUser": user,
            "ownerName": ownerName,
            "albumOwner": user,
            "published": False
        }
        otxt = genAlbumPage(options)
        return htmlResponse(otxt)

    #print "IMDICT ",imDict
    author = getattr(im, "author", None)
    if author == None:
        author = ""
    else:
        author = ", " + author
    ttl = getattr(im, "title", "")
    albowner = albumD.owner
    vprint("OWNER ", albowner, user)
    if (not constants.devVersion) and (albowner != user):
        return gen.genStaticPage(
            webin, "ImageDiver Message",
            "<center><b>This is an unpublished album</b></center>")

    beenPublished = getattr(albumD, "published", 0)
    vprint("beenPublished", beenPublished)
    ownerD = models.loadUserD(albowner, webin.pageStore)
    ownerName = getattr(ownerD, "name", None)
    apub = getattr(albumD, "published", None)
    if published and (not apub):
        return gen.genStaticPage(
            webin, "ImageDiver Message",
            "<center><b>This album has not yet been published</b></center>")

    #imageTopic = albumD.image
    #options = {"imageD":imDict,"albumOwner":albumD.owner,"albumOwnerName":ownerName,"loggedInUser":user,"hasAlbums":imHasAlbums,
    #          "albumTopic":albumD.topic,"published":published,"beenPublished":beenPublished,"path":"/"}

    options = {
        "imageD": imDict,
        "albumOwner": albumD.owner,
        "albumOwnerName": ownerName,
        "loggedInUser": user,
        "imTitle": ttl,
        "imAuthor": author,
        "albumTopic": albumD.topic,
        "imageTopic": imageTopic,
        "published": published,
        "beenPublished": beenPublished,
        "path": webin.path
    }
    vprint("OPTIONS", options)
    otxt = genAlbumPage(options)
    #snaps.closeStore(webin.pageStore)

    return htmlResponse(otxt)