Пример #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)
Пример #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
    })
Пример #3
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()
Пример #4
0
def acceptedTerms(webin):
    pcn = json.loads(webin.content())
    vprint("acceptedTerms", pcn)
    utopic = pcn["user"]
    email = pcn["email"]
    user = models.loadUserD(utopic, webin.pageStore)
    if user == None:
        return failResponse("noSuchUser")
    rss = None
    if email:
        vcode = models.genId("register")
        user.validation_code = vcode
        user.validated = 0
        user.email = email
        vprint("sending validating email to ", email)
        rss = ses.sendValidationEmail(user, True)
    user.accepted_terms = 1
    user.dynsave(False)
    s = user.newSession()
    stp = s.topic
    sid = misc.pathLast(stp)
    rs = {"sessionId": sid}
    if not rss:
        vprint("emailFailed")
        rs["emailFailed"] = 1
    return okResponse(rs)
Пример #5
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__)
Пример #6
0
def newAlbum(webin):

    cks = webin.checkSessionResponse()
    #f cks: return okResponse("virtual")
    if cks: return cks
    sess = webin.session
    user = sess.user
    cob = json.loads(webin.content())
    vprint("NEW ALBUM COB: ", str(cob))
    im = cob.get("image", None)
    cap = cob.get("caption", 'Untitled')
    if (not im) or (not cap):
        return failResponse("missingArguments")
    # for a very unlikely case
    #ha = album.hasAlbums(im,user)
    #if 0 and ha:
    # return failResponse("hasAlbums")
    newa = album.newAlbum(im, user, cap)
    ntp = newa.topic
    imD = image.loadImageD(im, webin.pageStore)
    if (not getattr(imD, "shared", False)) and (imD.owner != user):
        imD.shared = 1
        imD.dynsave(False)
    #js = newa.compute_json(wrapInStatus=True)
    #snapst.closeStore(webin.pageStore)
    exv = newa.externalize()
    #js = json.dumps(exv)
    return okResponse(exv)
Пример #7
0
def cancelJob(webin, pp):
    namep = pp.name
    owner = namep[0]
    idx = namep[1]
    topic = "/job/" + owner + "/" + idx
    theJob = models.getJob(topic, webin.pageStore)
    vprint("CANCEL ", "[" + topic + "]", theJob, theJob.kind, theJob.status)
    if theJob == None:
        vprint("CANCELED could not find ", topic, " to cancel")
        return failResponse("noSuchJob")

    st = theJob.status
    theJob.status = "canceled"
    saveJob(theJob)
    if st == "done":
        whenCanceled(theJob)
    # there is the bare chance of a race condition: the job is just finishing when the canceled notification is written
    # so check for this
    time.sleep(0.1)
    jb = models.getJob(topic, webin.pageStore)
    if jb.status == "done":
        print "CANCEL very unusual: race condition for ", topic
        whenCanceled(jb)
    #if (k=="retrieve") or (k == "upload"):
    #  whenCanceled(theJob)
    #whenCanceled(theJob)
    theJob.status = "canceled"
    saveJob(theJob)
    return okResponse()
Пример #8
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()
Пример #9
0
def imageDeleteable(webin):
    cob = json.loads(webin.content())
    topic = cob["topic"]
    imageD = image.loadImageD(topic, webin.pageStore)
    if not imageD:
        return failResponse("missing")
    rs = imageD.deleteable()
    return okResponse(int(rs))
Пример #10
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()
Пример #11
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()
Пример #12
0
def emitJob(webin, pp):
    namep = pp.name
    owner = namep[0]
    idx = namep[1]
    theJob = models.getJob("/job/" + owner + "/" + idx, webin.pageStore)
    if getattr(theJob, "pageStore", None):
        del theJob.pageStore
    if not theJob:
        return failResponse("noSuchJob")
    return okResponse(theJob.__dict__)
Пример #13
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()
Пример #14
0
def forgotPassword(webin):
    pcn = json.loads(webin.content())
    #uname = pcn["user"]
    email = pcn["email"]
    u = models.loadUserDbyEmail(email)
    if not u:
        return failResponse("noSuchEmail")
    ses.sendForgotPasswordEmail(u)
    #s = nu.newSession()
    #stp = s.topic
    #sid = stp.split("/")[-1]
    return okResponse()
Пример #15
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()
Пример #16
0
def tumblrPost(webin):
    vprint("tumblrPost")
    cks = webin.checkSessionResponse()
    if cks: return cks
    cob = json.loads(webin.content())
    vprint("cob", cob)

    sess = webin.session
    user = sess.user
    if tumblrPost1(user, cob):
        return okResponse()
    else:
        return failResponse()
    """
  userD = models.loadUserD(user)
  ttk = getattr(userD,'tumblr_token',None)
  if not ttk:
    return failResponse("noToken")
  tko = json.loads(ttk)
  token = tko["oauth_token"]
  token_secret = tko["oauth_token_secret"]
  vprint("Token",token)
  vprint("Token_secret",token_secret)
  cob=json.loads(webin.content())
  blog=cob["blog"]
  #caption = cob["caption"]
  #description = cob["description"]
  albumt = cob["album"]
  albumsp = albumt.split("/")
  ownr = albumsp[2]
  imname = albumsp[3]
  cropId = cob["crop"]
  snapId = cob["snap"]
  #http://static.imagediver.org/images/4294b0e/van_eyck_arnolfini/snap/12.jpg?album=4294b0e.1
  #http://s3.imagediver.org/topic/album/4294b0e/van_eyck_arnolfini/1/index.html#snap=9
  cropUrl = "http://static.imagediver.org/images/"+ownr+"/"+imname+"/snap/"+str(cropId)+".jpg"
  clickThru = "http://s3.imagediver.org/topic"+albumt+"/index.html#"+str(snapId)
  params = {"type":"photo","state":"draft","link":clickThru,"source":cropUrl}
  vprint("params",params)
  oauth_tumblr.post(token,token_secret,"chrisgoad.tumblr.com",params)
  vprint("post complete")
  """
    return okResponse()
Пример #17
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})
Пример #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)
Пример #19
0
def deleteSnap(webin):
    cks = webin.checkSessionResponse()
    if cks: return cks
    sess = webin.session
    user = sess.user
    cob = json.loads(webin.content())
    vprint("DELETE SNAP COB: " + str(cob))
    topic = cob["topic"]
    if constants.snapsInDynamo:
        snap = snapm.loadSnapD(topic)
    else:
        snap = models.loadSnapD(topic)
    if user != snap.owner:
        return failResponse("notOwner")
    if constants.snapsInDynamo:
        if snap:
            snap.delete()
    else:
        models.deleteSnap(topic, webin.pageStore)
        snaps.closeStore(webin.pageStore)
    return okResponse()
Пример #20
0
def runJob(webin):
    cks = webin.checkSessionResponse()
    if cks: return cks
    session = webin.session
    user = session.user.split("/")[-1]
    qs = webin.queryString
    qsp = urlparse.parse_qs(qs)
    jobId = qsp["id"][0]
    vprint("runJob", jobId)
    #jobId = qs.split("=")[1]
    jobTopic = "/job/" + user + "/" + jobId
    theJob = models.getJob(jobTopic, webin.pageStore)
    theJob.topic = jobTopic
    k = theJob.kind
    vprint("RUNNING JOB ", jobId, "KIND ", k)
    if theJob.status == "canceled":
        vprint("JOB CANCELED BEFORE IT STARTED")
        return okResponse("canceled")
    if k == "upload":
        rs = upload(theJob, webin)
    if k == "retrieve":
        rs = retrieveImage(theJob)
    """ the rest of these cases no longer occur, due to the separate importer """
    if k == "add_image_to_db":
        rs = addImageToDb(theJob)
    #if k=="build_tiling" or k=="resize_image" or k=="to_s3":
    #  rs = None
    elif k == "build_tiling":
        rs = buildTilingInThread(theJob)
    elif k == "resize_image":
        rs = resizeImageInThread(theJob)
    elif k == "to_s3":
        rs = toS3InThread(theJob)
    #jobs.closeStore(webin.pageStore)
    if type(rs) == str:
        vprint("FAIL FROM RUN JOB", rs)
        return failResponse(rs)
        del jobsByTopic[jobTopic]
    return okResponse()
Пример #21
0
def tumblrPost1(user, params):
    cob = params
    userD = models.loadUserD(user)
    uid = misc.pathLast(user)
    ttk = getattr(userD, 'tumblr_token', None)
    if not ttk:
        return failResponse("noToken")
    tko = json.loads(ttk)
    token = tko["oauth_token"]
    token_secret = tko["oauth_token_secret"]
    vprint("Token", token)
    vprint("Token_secret", token_secret)
    topic = cob["topic"]
    blog = cob["blog"]
    imageSource = cob["imageSource"]
    linkTo = cob["linkTo"]
    tags = cob["tags"]
    caption = cob["caption"].encode("utf_8", "ignore")
    """
  topicsp = topic.split("/")
  kind = topicsp[1] # snap or album
  ownr = topicsp[2]
  ownerName = None
  if ownr != uid:
    ownru = models.loadUserD("/user/"+ownr)
    ownerName = ownru.name
  imname = topicsp[3]
  albumNum = topicsp[4]
 
  imageTitle = cob["imageTitle"]
  imageAuthor = cob["imageAuthor"]
  imageSource = cob["imageSource"]
  linkTo = cob["linkTo"]
  if kind=="snap":
    snap = cob["snap"]
    #print "snap",snap
    #cropId = snap["cropid"]
    #snapId = misc.pathLast(topic)
  scaption = snap.get("caption",None)
  sdes = snap.get("description",None)
  caption = "Click on the image to see the detail in a zoomable context\n\nDetail"
  tags = []
  
  if imageTitle:
    caption += " from *"+imageTitle+"*"
    if imageTitle.find(",") < 0:
      tags.append(imageTitle)
  if imageAuthor:
    caption += ", "+imageAuthor
    if imageAuthor.find(",") < 0:
      tags.append(imageAuthor)
  caption += "\n\n"
  if scaption:
    caption += scaption
  if sdes:
    if scaption:
      caption +=  "\n\n"
    caption += sdes.decode("utf8","ignore")
  if ownerName:
    caption += "\n\n From  "+ownerName+" at [Imagediver](http://imagediver.org)"
  #http://static.imagediver.org/images/4294b0e/van_eyck_arnolfini/snap/12.jpg?album=4294b0e.1
  #http://s3.imagediver.org/topic/album/4294b0e/van_eyck_arnolfini/1/index.html#snap=9
  cropUrl = "http://static.imagediver.org/images/"+ownr+"/"+imname+"/snap/"+str(cropId)+".jpg"
  clickThru = "http://s3.imagediver.org/topic/album/"+ownr+"/"+imname+"/"+albumNum+"/index.html#snap="+str(snapId)
  """
    params = {
        "type": "photo",
        "format": "markdown",
        "state": "draft",
        "link": linkTo,
        "source": imageSource
    }
    if caption:
        params["caption"] = caption
    if len(tags) > 0:
        params["tags"] = ",".join(tags)
    #params = {"type":"text","state":"draft","body":"Second TEST post"}
    #print "DESC",sdes
    #vprint("CAPTION",caption)
    #print "params",params

    try:
        oauth_tumblr.post(token, token_secret, blog, params)
    except Exception as ex:
        vprint("FAILED TO POST", ex)
        return False
    vprint("post complete")
    return True
Пример #22
0
def addSnap(webin):
    """
  Handles the api/addSnap request; this is used for editing snaps too
  """
    if testingAddSnap:
        print "TESTINGADDSNAP"
        return failResponse("testing")
    print "ADD SNAPPPPP"
    cks = webin.checkSessionResponse()
    if cks: return cks
    sess = webin.session
    user = sess.user
    uname = models.pathLast(user)
    #  Logr.activeTags = ["dispatch","api"]
    #vprint(str(napi.__dict__))
    cob = json.loads(webin.content())
    vprint("COB: " + str(cob))
    album = cob["album"]
    albumIdx = pathLast(album)
    albumD = model.album.loadAlbumD(album, webin.pageStore)
    if user != albumD.owner:
        return failResponse("notOwner")
    topic = cob.get("topic", None)
    coverage = cob["coverage"]  # unscaled
    im = str(cob["image"])
    """
  imsplit = im.split("/")
  imuname = imsplit[2]
  imname = imsplit[3]
  imd = image.loadImageD(im,webin.pageStore)
  imdir = imd.imDir()
  imdim = imd.dimensions
  imwd = imdim["x"]
  imht = imdim["y"]
  scoverage = misc.scaleRectDict(coverage,1.0/imwd);
  """
    snap = snapm.SnapD(None)
    """
  if newCrop:
    cropid = dyn.bumpCount(cropcnti)
  else:
    cropid = cob["cropid"]
  vprint ("im",im,"imuname",imuname,"cropcnti",cropcnti,"cropid",cropid)
  #return okResponse("testing");

  cropid_s = str(cropid)
  """
    cropid = cob.get("cropid", None)
    caption = cob.get("caption", "")
    description = cob.get("description", "")
    ordinal = cob.get("ordinal", -1)
    #if newCrop:
    #  crect = image.dictToRect(coverage)

    #if not caption:caption=""
    #if not description:description=""
    # d={"topic":tp,"notSaved""type":"/type/snapD","image":im,"caption":caption,"description":description,"coverage":coverage}
    snap.image = im
    snap.album = album
    snap.owner = user
    snap.coverage = coverage
    snap.caption = caption
    snap.description = description
    snap.cropid = cropid
    snap.shares_coverage = 0
    snap.ordinal = ordinal
    snap.topic = topic
    rs = albumD.addSnap(snap, webin.pageStore)
    return okResponse(rs.__dict__)

    if in_snaps:
        snap.in_snaps = 1
    if newCrop:
        snap.published = 0
    if topic:
        snap.topic = topic
    if newSnap:
        #snapid = models.newSnap(album,snap)
        snapid = albumD.newSnap(snap)
    else:
        albumD.updateSnap(snap)
    if not snap.topic:
        snap.topic = "/snap/" + uname + "/" + imname + "/" + str(
            albumIdx) + "/" + str(snapid)

    vprint("saved snap :" + str(snap.__dict__))
    #dst.insert(d) # this does an update, if the topic and type exist

    # convert -size 25053x4354 -depth 16 -extract 2000x2000+10000+0 -resize 200x200 Panorama1924.TIF /var/www/neo.com/images/P00.jpg
    if newCrop:
        tl = image.Tiling(imd, 256, 1)
        tl.createTiles([], kind="r", parent=None, recursive=False)
        albumD.genSnapImages(imd, tl, snap)

        #snappath = imdir+"snap/"+str(cropid)+".jpg"
        #thumbpath = imdir+"snapthumb/"+str(cropid)+".jpg"
        #cropsize = imd.cropImage(crect,snappath,targetArea=200000) # the actual crop image will not be blown up, so may be less than the nominal (and returned) cropsize
        #thumbsize = imd.cropImage(crect,thumbpath,targetArea=25000) # the actual crop image will not be blown up, so may be less than the nominal (and returned) cropsize

        #tl.createTiles([])
        #cropsize = tl.cropFromTiles(snappath,crect,targetArea=200000) # the actual crop image will not be blown up, so may be less than the nominal (and returned) cropsize
        #thumbsize = tl.cropFromTiles(thumbpath,crect,targetArea=25000) # the actual crop image will not be blown up, so may be less than the nominal (and returned) cropsize
        #cropsize = imd.cropFromTile(tl,crect,snappath,targetArea=200000) # the actual crop image will not be blown up, so may be less than the nominal (and returned) cropsize
        #thumbsize = imd.cropFromTile(tl,crect,thumbpath,targetArea=25000) # the actual crop image will not be blown up, so may be less than the nominal (and returned) cropsize
        """
    this scheme, with iterative reduction, gave inferior results
    thumbsize = cropsize.scaleToArea(25000)
    imdir = imd.imDir()
    src = imdir + snappath+".jpg"
    dst = imdir + "snapthumb/"+str(cropid)+".jpg"
    image.resizeImage(src,dst,thumbsize)
    """

        #cmd = "convert -quiet -size {imwd}x{imht} -depth 8 -extract {cx}x{cy}+{x}+{y} -resize {szx}x{szy} {imFile} {cropFile}"
        #cmdf = cmd.format(imwd=imwd,imht=imht,cx=cx,cy=cy,x=x,y=y,szx=szx,szy=szy,imFile=imFile,cropFile=cropFile)

    #              " -resize "+ex+"x"+ey+" "+(tim.filename)+" "+(tl.directory)+(this.id)+";
    #import subprocess
    #subprocess.Popen(cmd)
    cap = getattr(albumD, "caption", None)
    " snaps from the snaps album are published immediately "
    #if cap==".snaps.":
    snap.publish()
    snap.publishInAlbum()
    #snaps.closeStore(webin.pageStore)
    return okResponse(snap.__dict__)
Пример #23
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)