def construct_wavelet_json_for_http_response(wavelet_data, wave_id, wavelet_id, email, b64Encode=False): ''' Constructs the json that will be sent back through the http request from various elements @param wavelet_data: the dict with the wavelet and wavelet json @param wave_id: the id of the wave @param wavelet_id: the id of the wavelet @param email: the email of the user waiting for the response @param b64Encode=False: set to true if you want the response base64 encoded @return the json to be sent to the webpage ''' #Fetch the required data from the datastore session = sessionTools.get(wave_id, wavelet_id, email) settings = settingsTools.get(session) waveMeta = waveTools.get(wave_id, wavelet_id) if waveMeta: participant_profiles = waveMeta.participant_profiles or {} else: participant_profiles = {} #Construct the outgoing json wavelet_json = { 'wavelet' : wavelet_data.get("json"), 'readblips' : settings.read_blips or [], 'profiles' : participant_profiles, 'isPublic' : sessionTools.isPublic(session), 'rwPermission' : settings.rw_permission } if b64Encode: return base64.b64encode(simplejson.dumps(wavelet_json)) else: return simplejson.dumps(wavelet_json)
def save_blip_info_full(blip_id, content, annotations="", elements=""): saved = SavedBlip() saved.blip_id = blip_id saved.text = db.Text(content) saved.annotations = db.Text(simplejson.dumps(annotations)) saved.elements = db.Text(simplejson.dumps(elements)) saved.put()
def toggle(self, toggle=True): pp = model.ParticipantPreferences.get_by_pk(self.participant) pwp = model.ParticipantWavePreferences.get_by_pk(self.participant, self.wave_id, create=toggle) data = '' if pwp: if toggle: pwp.notify_type = (pwp.notify_type + 1) % model.NOTIFY_TYPE_COUNT pwp.put() status = pwp.notify_type email = pwp.notify_type phones = [ 1 ] # TODO count phones if len(phones) == 0: phone = -1 if pwp.notify_type != model.NOTIFY_NONE: phone = model.NOTIFY_ONCE else: phone = model.NOTIFY_NONE data = simplejson.dumps({ 'status': status, 'email': email, 'phone': phone, 'preferencesWaveId': pp and pp.preferences_wave_id or '' }) else: data = simplejson.dumps({ 'status': 0, 'email': 0, 'phone': 0, 'preferencesWaveId': pp and pp.preferences_wave_id or '' }) self.response.out.write(data);
def unresolve_part(part): if type(part) == str or type(part) == unicode: if not len(part): return '' elif part[0] != '*': return urllib.quote(part, '') else: return urllib.quote(dumps(part), '') else: return urllib.quote(dumps(part))
def construct_message(participant, phone_token, wave_id, wavelet_id, blip_id, title, message): message = (templates.PHONE_MESSAGE % (title, message)) if phone_token: data = { 'device_tokens': [phone_token.replace(' ', '').upper()], 'aps': { 'alert': { 'body': message } }, 'r': '%s:%s:%s:%s' % (participant, wave_id, wavelet_id, blip_id) } else: data = { 'aps': { 'alert': { 'body': message } }, 'r': '%s:%s:%s:%s' % (participant, wave_id, wavelet_id, blip_id) } return simplejson.dumps(data, separators=(',', ':'))
def throw(message, *args, **kwargs): """ <p>Raises an exception with the first argument as the main exception text also giving it a JSON representation of the arguments and kwargs</p> """ try: json = dumps({'args':args, 'kwargs':kwargs}) except Exception, e: raise Exception('%s\nError generating JSON: %s' % (message, e))
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))}))
def _dumps(self, obj): ''' Writes an object to a string so it can be stored in the gadget state @param obj: the object to write to string @return a b64/json string representing the object ''' if not obj: return "" return base64.b64encode(simplejson.dumps(obj))
def features(self): features = {} blips = self._wavelet.blips for blip_id in blips: blip = blips[blip_id] match = self.FEATURE.match(blip.text) if match: features[blip.blip_id] = {'name' : match.group(1), 'version' : str(blip.version), 'content' : blip.text} return json.dumps({'features' : features})
def fetch(self): participant = self.request.get('participant') wave_id = self.request.get('wave_id') wavelet_id = self.request.get('wavelet_id') blip_id = self.request.get('blip_id') wavelet = util.fetch_wavelet(wave_id, wavelet_id, participant) if blip_id in wavelet.blips: blip = wavelet.blips[blip_id] data = { 'blipId': blip.blip_id, 'waveId': blip.wave_id, 'waveletId': blip.wavelet_id, 'creator': blip.creator, 'content': blip.text } logging.debug('RESPONSE: %s' % simplejson.dumps(data)); self.response.out.write(simplejson.dumps(data)) return False else: return 'Blip not found'
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 reset(self): domain = self.participant.split('@')[1] robot = create_robot(run=False, domain=domain) preferences.create_preferences_wave(robot, self.participant) #wavelet = robot.fetch_wavelet(self.wave_id, '%s!root+conv' % domain) #general.participant_init(wavelet, self.participant) #general.participant_wavelet_init(wavelet, self.participant, self.participant) self.response.out.write(simplejson.dumps({ 'status': 0 }))
def fetch(self): participant = self.request.get('participant') wave_id = self.request.get('wave_id') wavelet_id = self.request.get('wavelet_id') blip_id = self.request.get('blip_id') wavelet = util.fetch_wavelet(wave_id, wavelet_id, participant) if blip_id in wavelet.blips: blip = wavelet.blips[blip_id] data = { 'blipId': blip.blip_id, 'waveId': blip.wave_id, 'waveletId': blip.wavelet_id, 'creator': blip.creator, 'content': blip.text } logging.debug('RESPONSE: %s' % simplejson.dumps(data)) self.response.out.write(simplejson.dumps(data)) return False else: return 'Blip not found'
def construct_message(participant, phone_token, wave_id, wavelet_id, blip_id, title, message): message = (templates.PHONE_MESSAGE % (title, message)) if phone_token: data = { 'device_tokens': [ phone_token.replace(' ', '').upper() ], 'aps': { 'alert': { 'body': message } }, 'r': '%s:%s:%s:%s' % (participant, wave_id, wavelet_id, blip_id) } else: data = { 'aps': { 'alert': { 'body': message } }, 'r': '%s:%s:%s:%s' % (participant, wave_id, wavelet_id, blip_id) } return simplejson.dumps(data, separators=(',', ':'))
def online(self, online=True): pwp = model.ParticipantWavePreferences.get_by_pk(self.participant, self.wave_id) if pwp: pwp.last_visited = datetime.datetime.now() pwp.put() if not online: visited(pwp.participant, self.wave_id, pwp) else: deferred.defer(visited, pwp.participant, pwp.wave_id, pwp.last_visited, _queue='visited', _countdown=150) self.response.out.write(simplejson.dumps({ 'status': 0 }))
def invoke(responder, module, fn, *path, **kwargs): from urquell.value import resolve_part ihash = store_invocation(responder.request.url) responder.object['hash'] = u'*%s' % unicode(ihash) responder.object['name'] = '%s/%s' % (module.path(), fn.func_name) call_trace = [resolve_part(str(i)) for i in path] args = [x for u, x in call_trace] responder.object['args'] = [u for u, x in call_trace] responder.object['value'] = fn(*args, **kwargs) json = dumps(responder.object) if responder.object.has_key('value'): memcache.add(ihash, json, 300) return json, responder.object
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 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 constructInitialState(wavelet): ''' Constructs the initial gadget state. This is used purely for migration from the v1 gadget to v2 gadget. So it returns a list of email users in the correct format for the gadget @param wavelet: the wavelet where the gadget will live @return a dictionary containing the key values of the initial state ''' sessions = sessionTools.fetch(wavelet.wave_id, wavelet.wavelet_id) #Form the email list email_list = [] public_session = None for session in sessions: if sessionTools.isPublic(session): public_session = session else: email_list.append(session.email) #Form public settings public = {} isPublic = False isReadOnly = True try: public_settings = settingsTools.get(public_session) rw_permission = public_settings.rw_permission if rw_permission == pt_raw.RW['READ']: isPublic = True isReadOnly = True elif rw_permission == pt_raw.RW['READ_WRITE']: isPublic = True isReadOnly = False except: #Just means public settings could not be found. Defaults will be used pass public.update({'isPublic' : isPublic, 'isReadOnly' : isReadOnly}); output = base64.b64encode(simplejson.dumps({'emailParticipants' : email_list, 'public' : public})) return {'state' : output, 'participantDetailsState' : 'fetch'}
#!python
class PhoneProcess(webapp.RequestHandler): def post(self, *args): self.get() def get(self, *args): self.response.contentType = 'application/json' path = [urllib.unquote(a) for a in self.request.path.split('/')[2:]] req_type = path[0] self.participant = self.request.get('participant') if self.participant: self.participant = self.participant.lower() self.activation = self.request.get('activation') self.receipt_data = self.request.get('receipt_data') self.phone_uid = self.request.get('phone_uid') self.phone_type = self.request.get('phone_type') self.phone_token = self.request.get('phone_token') if self.phone_token: self.phone_token = self.phone_token.replace('+', ' ') logging.debug(LOG, req_type, self.participant, self.activation, self.phone_uid, self.phone_token, self.receipt_data) self.account = None try: if req_type.startswith('_'): return error = getattr(self, req_type)() if error == False: return except Exception, e: logging.exception('Error while processing phone process %s', e) error = str(e) data = None if not error and self.account: query = model.Phone.all() query.filter('account_id =', self.account.account_id) phones = [phone1.phone_uid for phone1 in query] query = model.ParticipantPreferences.all() query.filter('account_id =', self.account.account_id) participants = [pa.participant for pa in query] data = { 'phones': phones, 'participants': participants, 'subscription_type': self.account.subscription_type, 'expiration_date': str(self.account.expiration_date), 'response': "OK" } else: data = { 'response': "ERROR", 'message': error or 'Invalid Google Wave account' } logging.debug('RESPONSE: %s' % simplejson.dumps(data)) self.response.out.write(simplejson.dumps(data))
'message': e.message, 'trace': e.trace } except Exception, e: import traceback self.status = 500 self.object['error'] = { 'message': unicode(e), 'python': { 'call_trace': traceback.format_exc(), }, } self.response.set_status(self.status) if self.request.headers.get('X-Requested-With', '').find('XMLHttpRequest') >= 0 or self.request.GET.has_key('__'): self.response.headers['Content-Type'] = 'text/plain' text = dumps(self.object) if self.request.GET.get('__', None): self.response.out.write("%s(%s);" % (self.request.GET['__'], text)) else: self.response.out.write(text) else: self.context['result'] = self.object self.context['status'] = self.status if self.object.has_key('value'): self.context['value'] = dumps(self.object['value']) self.context['error'] = self.object.get('error', None) self.response.out.write(template.render(self.template, self.context)) class EndPoint(object): """
def _deflate(self, value): return db.Text(simplejson.dumps(value))
def save(self): self.data.frames = dumps(self.frames) db.put(self.data)
def save_blip(blip, delta): del_saved_blip(blip.blipId) saved = SavedBlipDelta() saved.blip_id = blip.blipId saved.delta = simplejson.dumps(delta) saved.put()