Exemple #1
0
def set_blip_info_full(blip, info):
    doc = blip.GetDocument()
    doc.SetText(info.text + "")  # concat with empy string to make it a string
    if info.annotations:
        set_annotations(doc, simplejson.loads(info.annotations))
    if info.elements:
        set_elements(doc, simplejson.loads(info.elements))
Exemple #2
0
	def __init__(self,sid):
		self.data = Session.gql("WHERE sid = :1", sid).fetch(1)
		if len(self.data):
			self.data = self.data[0]
			self.sid, self.frames = self.data.sid,loads(self.data.frames)
		else:
			self.sid, self.frames, self.data = sid,{},Session(sid=sid,frames="{}")
    def post(self):
        '''
        Handles the incoming post request and performs the relevant action on
        the wave.
        '''
        logging.info("POST: /wave/action/")
        #Fetch the auth values from the url + form values
        incoming_json = cgi.escape(self.request.body)
        self.incoming = simplejson.loads(incoming_json)

        self.wave_id = urllib.unquote(self.incoming.get("waveid", ""))
        self.wavelet_id = urllib.unquote(self.incoming.get("waveletid", ""))
        self.email = urllib.unquote(self.incoming.get("email", ""))
        self.auth_token = self.incoming.get("auth", "")
        self.action = self.incoming.get("action", None)

        logging.info("Request waveid: " + self.wave_id + " waveletid: " + self.wavelet_id + " email: " + self.email + " auth token: " + self.auth_token)

        if self.action == "REPLY":
            return self._replyRequest()
        elif self.action == "READ":
            return self._readRequest()
        elif self.action == "REFRESH":
            return self._refreshRequest()
        else:
            return self._malformedRequest()
 def _loads(self, obj):
     '''
     Loads an object from the gadget state if it is b64/json
     @param obj: the raw string to load
     @return the python object
     '''
     if not obj:
         return None
     return simplejson.loads(base64.b64decode(obj))
Exemple #5
0
def _add_googlecode_message(wavelet, myJson):
	payload = json.loads(myJson)
	for commit in payload['revisions']:
		reply = wavelet.reply()
		reply.append("[googlecode: "+payload['repository_path']+"]\n\n")
		commit['timestamp'] = _format_for_commit(commit['timestamp'])
		commit['id'] = str(commit['revision'])
		reply.append(element.Gadget(ROBOT_URL + "/gadgets/github.xml", 
			{'commit': urllib.quote(json.dumps(commit))}))
Exemple #6
0
def execute(url):
    if url:
        json = fetch(url, headers={
            'X-Requested-With': 'XMLHttpRequest',
        }).content
        try:
            return loads(json)
        except Exception, e:
            raise Exception(json)
Exemple #7
0
def _add_github_message(wavelet, myJson):
	payload = json.loads(urllib.unquote(myJson))
	for commit in payload['commits']:
		reply = wavelet.reply()
		reply.append("[github: "+payload['repository']['url']+"]\n\n")
		commit['timestamp'] = _convert_time(commit['timestamp'])
		commit['image'] = _gravatar_url_from(commit['author']['email'])
		commit['author'] = commit['author']['name']
		reply.append(element.Gadget(ROBOT_URL + "/gadgets/github.xml", 
			{'commit': urllib.quote(json.dumps(commit))}))
    def update_using(self, results):
        features = json.loads(urllib.unquote(results))['features']
      
        for blip_id in features:
            blip = self._wavelet.blips[blip_id]
            feature = features[blip_id]

            if str(blip.version) == str(feature['version']):
                self._update_blip(blip, feature)
            else:
                logging.info('Could not update blip ' + blip.blip_id + ', incoming version (' + feature['version'] + ') not current (' + str(blip.version) + ')')
Exemple #9
0
def resolve_part(value):
    if value.startswith('**'):
        value = value[1:]
    elif value.startswith('*'):
        from invocation import resolve_hash
        return resolve_hash(value[1:])

    value = urllib.unquote(value)

    try:
        return (value, loads(value))
    except:
        return (value, value)
Exemple #10
0
def resolve_hash(value):
    dest = Invocation.gql("WHERE ihash = :1", value).fetch(1)
    if not len(dest):
        raise ErrorTrace("Unable to resolve function invocation. Invocation hash: %s" % value)
    url = dest[0].url
    json = memcache.get(value)
    if not json:
        rvalue = execute(url)
    else:
        rvalue = loads(json)
    if rvalue.has_key('value'):
        return url, rvalue['value']
    else:
        raise ErrorTrace("Whilst resolving binding value %s" % value, rvalue)
Exemple #11
0
 def post(self):
     waveid = self.request.POST.get("waveid", None)
     body = self.request.POST.get("body", None)
     if waveid and body:
         # self.response.out.write('Received %s' % body)
         try:
             zephyr = simplejson.loads(body)
             if helpers.valid(zephyr):
                 wavelet = self.robot.fetch_wavelet(waveid, "googlewave.com!conv+root")
                 # wavelet.title = TITLE + ' - %s' % zephyr['zclass']
                 formatted = helpers.format(zephyr)
                 wavelet.reply().append_markup(formatted)
                 self.robot.submit(wavelet)
                 self.response.out.write(formatted)
         except Exception, e:
             self.response.out.write(" ...but it failed! (%s)" % e)
Exemple #12
0
def bitly(url):
  if reBitly.match(url) :
    info = 1
    hashUrl = url.replace("http://bity.ly/", "")
    apiUrl = apiBitly % ('info', 'shortUrl', urllib.quote(hashUrl))
  else :
    apiUrl = apiBitly % ('shorten', 'longUrl', urllib.quote(hashUrl))

  json = urllib2.urlopen(apiUrl).read()
  data = simplejson.loads(json)
  if info:
    for k,v in data['results'].iteritems():
      return data['results'][k]['longUrl']
  else:
    for k,v in data['results'].iteritems():
      return data['results'][k]['shortUrl'];
    def _update_account(self):
        '''Update account or create one if it does not exist yet'''

        if not self.receipt_data: return

        if self.receipt_data == FREE_TRIAL:
            if self.account.subscription_type:
                return 'Cannot activate the free trial, a subscription already exists.'

            purchase_date = datetime.datetime.now()
            transaction_id = FREE_TRIAL
            subscription_type = FREE_TRIAL
        else:
            type = model.ApplicationSettings.get('apn-type')
            receipt_url = model.ApplicationSettings.get('apn-receipt-url-%s' %
                                                        type)
            data = simplejson.dumps({'receipt-data': self.receipt_data})
            json = simplejson.loads(urllib2.urlopen(receipt_url, data).read())

            if json['status'] != 0:
                return 'Invalid receipt'

            subscription_type = json['receipt']['product_id']
            transaction_id = json['receipt']['transaction_id']

            query = model.Account.all()
            query.filter('transaction_id =', transaction_id)
            if query.get():
                return 'Cannot use receipt, account already activated with this receipt.'

            if self.account.transaction_id and self.account.transaction_id != transaction_id:
                purchase_date = self.account.expiration_date
            else:
                purchase_date = json['receipt']['purchase_date'].split(" ")[0]
                purchase_date = datetime.datetime.strptime(
                    purchase_date, "%Y-%m-%d")

        if subscription_type in PRODUCT_IDS:
            self._save_history()
            self.account.expiration_date = PRODUCT_IDS[subscription_type](
                purchase_date)
            self.account.subscription_type = subscription_type
            self.account.transaction_id = transaction_id
            self.account.receipt_data = self.receipt_data
            self.account.put()
        else:
            return "Invalid Product ID %s" % subscription_type
Exemple #14
0
 def process_single_packet(self, obj):
     file("./stream.txt","a+").write(str(obj)+"\n")
     for packs in obj:
         pid, pcont = packs
         if (pcont[0] != 'wfe'):
             continue
         innerobj = simplejson.loads(pcont[1])
         file("./streamb.txt","a+").write(str(innerobj)+"\n")
         file("./streamc.txt","a+").write("----------------------------\n")
         file("./streamc.txt","a+").write(self.dump_object(innerobj))
         if isinstance(innerobj["p"]["1"],list):
             for w in innerobj["p"]["1"]:
                 ctitle = w["9"]["1"].encode("ASCII","ignore")
                 content = w["10"][0]["1"].encode("ASCII","ignore")
                 waveid = w["1"].encode("ASCII","ignore")
                 print waveid+" : " + ctitle + " "+content[0:10]
     return
def onAddParticipantsChangedV1(event, wavelet, add_gadget):
    '''
    Deals with the add participants gadget changing, subscribes wave users etc
    @param event: the event that triggered the gadget state change
    @param wavelet: the wavelet the gadget lives in
    @param add_gadget: the add participants gadget retrieved from the wave
    '''

    #Fetch the values from the gadget
    participants_json = add_gadget.get("EMAIL-PARTICIPANTS", None)
    if participants_json:
        participants_json = base64.b64decode(participants_json)
    else:
        participants_json = "[]"
    participants = simplejson.loads(participants_json)
    new_participant = add_gadget.get("ADD-PARTICIPANT", None)

    if new_participant:
        logging.info("Subscribing new e-mail user: "******" not subscribed. E-mail address not valid")
            return

        #Only update if the user is new
        if not new_participant in participants:
            deferred.defer(
                    emailInterface.sendFirstNotificationEmail,
                    sessionCreation.generateNewUser(wavelet.wave_id,
                                                    wavelet.wavelet_id,
                                                    new_participant,
                                                    pt_raw.RW['READ_WRITE']),
                    wavelet.wave_id,
                    wavelet.wavelet_id,
                    new_participant,
                    event.modified_by,
                    wavelet.title)

            participants.append(new_participant)
            wavelet.add_proxying_participant(utils.getProxyForFromEmail(new_participant))

        #Update the gadget
        participants_json = simplejson.dumps(participants)
        add_gadget.update_element({ "ADD-PARTICIPANT": None,
                                    "EMAIL-PARTICIPANTS": base64.b64encode(participants_json)})
    def _update_account(self):
        '''Update account or create one if it does not exist yet'''

        if not self.receipt_data: return

        if self.receipt_data == FREE_TRIAL:
            if self.account.subscription_type:
                return 'Cannot activate the free trial, a subscription already exists.'

            purchase_date = datetime.datetime.now()
            transaction_id = FREE_TRIAL
            subscription_type = FREE_TRIAL
        else:
            type = model.ApplicationSettings.get('apn-type')
            receipt_url = model.ApplicationSettings.get('apn-receipt-url-%s' % type)
            data = simplejson.dumps({ 'receipt-data': self.receipt_data })
            json = simplejson.loads(urllib2.urlopen(receipt_url, data).read())

            if json['status'] != 0:
                return 'Invalid receipt'

            subscription_type = json['receipt']['product_id']
            transaction_id = json['receipt']['transaction_id']

            query = model.Account.all()
            query.filter('transaction_id =', transaction_id)
            if query.get():
                return 'Cannot use receipt, account already activated with this receipt.'

            if self.account.transaction_id and self.account.transaction_id != transaction_id:
                purchase_date = self.account.expiration_date
            else:
                purchase_date = json['receipt']['purchase_date'].split(" ")[0]
                purchase_date = datetime.datetime.strptime(purchase_date, "%Y-%m-%d")

        if subscription_type in PRODUCT_IDS:
            self._save_history()
            self.account.expiration_date = PRODUCT_IDS[subscription_type](purchase_date)
            self.account.subscription_type = subscription_type
            self.account.transaction_id = transaction_id
            self.account.receipt_data = self.receipt_data
            self.account.put()
        else:
            return "Invalid Product ID %s" % subscription_type
def migratev1tov2(sessions):
    '''
    Looks at the provided session and if it is running version 1 migrates it
    to version 2
    @param session: the sessions to potentially migrate
    '''
    for session in sessions:
        if session and session.version == 1:
            settings = Settings(read_blips      = simplejson.loads(session.read_blips or '[]'),
                                unseen_changes  = session.unseenChanges,
                                parent          = session,
                                key_name        = settingsTools.generateKey(session.wave_id,
                                                                            session.wavelet_id,
                                                                            session.email))
            settingsTools.put(settings, session.wave_id, session.wavelet_id, session.email)
            session.version = 2
            session.read_blips = None
            session.unseenChanges = None
            sessionTools.put(session)
Exemple #18
0
def unbuttify_blip(blip):
    saved = get_saved_blip(blip.blipId)

    if saved is None:
        logging.warning("user requested unbuttification of non-butted blip")
        return

    delta = simplejson.loads(saved.delta + "")
    if delta is not None:
        delta.reverse()
    doc = blip.GetDocument()
    txt = doc.GetText()

    for old, new in delta:
        s = re.search(re.escape(new), txt)

        if s is not None:
            r = document.Range(s.start(0), s.end(0))
            doc.SetTextInRange(r, old)
def getAuthenticationValuesFromRequest(requestHandler):
    '''
    Fetches the wave id, wavelet id, email and auth token from the request
    handler using whichever means are possible. If they cannot be found
    returns an empty string for each
    @param requestHandler: the request object to extract the values from
    @return a dict containing {wave_id, wavelet_id, email, auth}
    '''
    
    #Load the json if it is available
    try:
        json = simplejson.loads(cgi.escape(requestHandler.request.body))
    except:
        json = {}

    #Take either the values from the url or from the json
    return {
    "wave_id"   : requestHandler.request.get("waveid", urllib.unquote(json.get("waveid", ""))),
    "wavelet_id": requestHandler.request.get("waveletid", urllib.unquote(json.get("waveletid", ""))),
    "email"     : requestHandler.request.get("email", urllib.unquote(json.get("email", ""))),
    "auth"      : requestHandler.request.get("auth", urllib.unquote(json.get("auth", "")))
    }
Exemple #20
0
 def process_stream(self, sid, f):
     """process an incoming stream referenced from SID; calls back f(data)"""
     zx = "".join([chr(random.randint(97,122)) for i in xrange(0, 11)])
     import httplib
     connection = httplib.HTTPSConnection("wave.google.com")
     # connection.set_debuglevel(1)
     connection.request("GET", "/wave/wfe/channel?VER=6&RID=rpc&SID="+sid+
                        "&CI=0&AID=0&TYPE=xmlhttp&zx="+zx+"&t=1", None, 
                        {'Cookie': self.cookie, 
                         'User-Agent' : "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/4.0.249.11 Safari/525.13",
                         # "transfer-encoding" : "chunked"
                         }
                        )
     http_response = connection.getresponse() 
     while (True):
         l = self.process_readline(http_response).strip() # first line is always packet length
         print "new packet length: "+str(l)
         plen = int(l)
         cpacket = ""
         while (len(cpacket) < plen):
             cpacket += self.process_readline(http_response)
             #print "BReading: "+cpacket+" - size: "+str(len(cpacket))
         #print "finished BR"
         while (True):
             # print http_response.fp.tell()
             try:
                 cobj = simplejson.loads(cpacket)
                 break # packet is finished, and readable
             except:
                 # there is probably more to it
                 cline = self.process_readline(http_response).strip()
                 # print "+reading: "+str(cline)
                 cpacket += cline
                 continue
         self.process_single_packet(cobj)
     # print http_data
     exit()
     connection.close()
Exemple #21
0
 def read(self, wid):
     """reads the wave content from wire"""
     self.wiredata = self.refresh_wire(wid)
     if self.wiredata == "":
         return False
     self.wireobj = simplejson.loads(self.wiredata)
     if self.wireobj == False:
         return False
     self.wireobj = self.json_postprocess(self.wireobj)
     logging.info(str(self.wireobj))
     # read all blip information here
     cwn = ""
     i = -1
     while cwn != "googlewave.com!conv+root":
         i += 1
         bliplist = self.wireobj[1][i][1][2]
         wavelet_meta = self.wavelet_parse(self.wireobj[1][i][1][1])
         cwn = wavelet_meta["wavelet"]
     self.rootwavelet = wavelet_meta
     for blipraw in bliplist:
         blip = self.blip_parse(blipraw)
         cid = blip["id"]
         self.blips[cid] = blip
     return True
Exemple #22
0
def _read_config():
    config_file = open(os.path.abspath(os.path.dirname(__file__) + '/../config.json'), 'r')
    contents = config_file.read()
    config_file.close()
    return json.loads(contents)
Exemple #23
0
 def _inflate(self, value):
     if value is None:
         return {}
     if isinstance(value, unicode) or isinstance(value, str):
         return simplejson.loads(str(value))
     return value
Exemple #24
0
 def parse_response(self, r):
     """returns a native python object from the JSON mess spit by wave"""
     data = ("".join(r.split("\n")[1:])).replace(",]","]")
     obj = simplejson.loads(data)
     return obj