Example #1
0
def system_api_call(rt_settings, request_id, method, params, user_details,
                    **kwargs):
    if method not in API_METHOD_MAPPING:
        logging.warn('Ignoring unknown api call: %s', method)
        return
    user_details = log_and_parse_user_details(user_details)
    response = SendApiCallCallbackResultTO(error=None, result=None)
    try:
        params = json.loads(params) if params else params
        result = API_METHOD_MAPPING[method](params=params,
                                            user_detail=user_details[0])
        if result is not None:
            is_list = isinstance(result, list)
            if is_list and result:
                _type = type(result[0])
            else:
                _type = type(result)

            if isinstance(result, unicode):
                response.result = result
            else:
                result = serialize_complex_value(result, _type, is_list)
                response.result = json.dumps(result).decode('utf-8')
    except ApiCallException as e:
        response.error = e.message
    except:
        logging.exception('Unhandled API call exception')
        response.error = u'An unknown error has occurred. Please try again later.'
    return serialize_complex_value(response, SendApiCallCallbackResultTO,
                                   False)
Example #2
0
def send_message_for_pharmacy_order(service_user, order_key, order_status, message):
    from solutions.common.bizz.messaging import send_inbox_forwarders_message

    azzert(order_status in SolutionPharmacyOrder.ORDER_STATUSES)

    def txn():
        m = SolutionPharmacyOrder.get(order_key)
        azzert(service_user == m.service_user)
        if m.status == SolutionPharmacyOrder.STATUS_RECEIVED and m.status != order_status:
            m.status = order_status
            m.put()
        return m
    order = db.run_in_transaction(txn)

    sm_data = []
    sm_data.append({u"type": u"solutions.common.pharmacy_orders.update"})

    sln_settings = get_solution_settings(service_user)
    if message:
        if order.solution_inbox_message_key:
            sim_parent, _ = add_solution_inbox_message(
                service_user, order.solution_inbox_message_key, True, None, now(), message, mark_as_unread=False, mark_as_read=True)
            send_inbox_forwarders_message(service_user, sim_parent.service_identity, None, message, {
                'if_name': sim_parent.sender.name,
                'if_email': sim_parent.sender.email
            }, message_key=sim_parent.solution_inbox_message_key, reply_enabled=sim_parent.reply_enabled)
            sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, order.service_identity)
            sm_data.append({u"type": u"solutions.common.messaging.update",
                            u"message": serialize_complex_value(SolutionInboxMessageTO.fromModel(sim_parent, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False)})
        else:
            sln_main_branding = get_solution_main_branding(service_user)
            branding = sln_main_branding.branding_key if sln_main_branding else None

            member = MemberTO()
            member.alert_flags = Message.ALERT_FLAG_VIBRATE
            member.member = order.sender.email
            member.app_id = order.sender.app_id

            messaging.send(parent_key=None,
                           parent_message_key=None,
                           message=message,
                           answers=[],
                           flags=Message.FLAG_ALLOW_DISMISS,
                           members=[member],
                           branding=branding,
                           tag=None,
                           service_identity=order.service_identity)

    elif order.solution_inbox_message_key:
        sim_parent = SolutionInboxMessage.get(order.solution_inbox_message_key)
        if not sim_parent.read:
            sim_parent.read = True
            sim_parent.put()
            deferred.defer(update_user_data_admins, service_user, order.service_identity)
        sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, order.service_identity)
        sm_data.append({u"type": u"solutions.common.messaging.update",
                        u"message": serialize_complex_value(SolutionInboxMessageTO.fromModel(sim_parent, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False)})

    send_message(service_user, sm_data, service_identity=order.service_identity)
    def testSvcIdentityDetailsTOs(self):

        id_default, id_child = self.prepare_svc('*****@*****.**', [u"rogerthat"])

        default_dict = {'phone_number': u'123456123123',
                        'search_use_default': False,
                        'description_use_default': False,
                        'description_branding': u'DESCBR',
                        'description': u'Default name ([email protected])',
                        'created': id_default.creationTimestamp,
                        'qualified_identifier': u'qual1',
                        'phone_number_use_default': False,
                        'phone_call_popup': None,
                        'phone_call_popup_use_default': False,
                        'admin_emails': [],
                        'search_config':{'keywords': None,
                                         'enabled': False,
                                         'locations': []},
                        'menu_branding_use_default': False,
                        'menu_branding': u'MENUBR',
                        'recommend_enabled': id_default.shareEnabled,
                        'identifier': u'+default+',
                        'description_branding_use_default': False,
                        'name': u'Default name',
                        'email_statistics': False,
                        'email_statistics_use_default': False,
                        'app_data': None,
                        'app_ids_use_default':False,
                        'app_ids':[App.APP_ID_ROGERTHAT],
                        'app_names':["Rogerthat"],
                        'can_edit_supported_apps':False,
                        'content_branding_hash': None,
                        'home_branding_hash': u'HOMEBR',
                        'home_branding_use_default': False}

        service_profile = get_service_profile(users.User(u'*****@*****.**'))

#        print serialize_complex_value(ServiceIdentityDetailsTO.fromServiceIdentity(id_default, service_profile), ServiceIdentityDetailsTO, False)
#        print default_dict
        current_dict = serialize_complex_value(ServiceIdentityDetailsTO.fromServiceIdentity(id_default, service_profile), ServiceIdentityDetailsTO, False)
        azzert(current_dict == default_dict)

        child_dict = default_dict.copy()
        child_dict['menu_branding'] = None
        child_dict['name'] = u'child'
        child_dict['qualified_identifier'] = None
        child_dict['identifier'] = u'childid'
        child_dict['description_branding_use_default'] = True
        child_dict['phone_number_use_default'] = True
        child_dict['description'] = u'Child description'
        child_dict['created'] = id_child.creationTimestamp
        child_dict['recommend_enabled'] = False
        child_dict['email_statistics'] = False
        child_dict['home_branding_use_default'] = True

#        print serialize_complex_value(ServiceIdentityDetailsTO.fromServiceIdentity(id_child, service_profile), ServiceIdentityDetailsTO, False)
#        print child_dict
        azzert(serialize_complex_value(ServiceIdentityDetailsTO.fromServiceIdentity(id_child, service_profile), ServiceIdentityDetailsTO, False) == child_dict)
Example #4
0
def delete_sandwich_order(service_user, service_identity, sandwich_id, message):
    from solutions.common.bizz.messaging import send_inbox_forwarders_message

    sln_settings = get_solution_settings(service_user)

    def txn():
        m = SandwichOrder.get_by_order_id(service_user, service_identity, sln_settings.solution, sandwich_id)
        azzert(service_user == m.service_user)
        m.deleted = True
        m.put()
        return m

    xg_on = db.create_transaction_options(xg=True)
    sandwich_order = db.run_in_transaction_options(xg_on, txn)

    sm_data = [{u"type": u"solutions.common.sandwich.orders.deleted", u'sandwich_id': sandwich_id}]

    if message:
        if sandwich_order.solution_inbox_message_key:
            sim_parent, _ = add_solution_inbox_message(service_user, sandwich_order.solution_inbox_message_key, True, None, now(), message, mark_as_unread=False, mark_as_read=True, mark_as_trashed=True)
            send_inbox_forwarders_message(service_user, sim_parent.service_identity, None, message, {
                        'if_name': sim_parent.sender.name,
                        'if_email':sim_parent.sender.email
                    }, message_key=sim_parent.solution_inbox_message_key, reply_enabled=sim_parent.reply_enabled)
            sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, sandwich_order.service_identity)
            sm_data.append({u"type": u"solutions.common.messaging.update",
                         u"message": serialize_complex_value(SolutionInboxMessageTO.fromModel(sim_parent, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False)})

        else:
            branding = get_solution_main_branding(service_user).branding_key
            member = MemberTO()
            member.alert_flags = Message.ALERT_FLAG_VIBRATE
            member.member = sandwich_order.sender.email
            member.app_id = sandwich_order.sender.app_id

            messaging.send(parent_key=None,
                           parent_message_key=None,
                           message=message,
                           answers=[],
                           flags=Message.FLAG_ALLOW_DISMISS,
                           members=[member],
                           branding=branding,
                           tag=None,
                           service_identity=sandwich_order.service_identity)

    elif sandwich_order.solution_inbox_message_key:
        sim_parent = SolutionInboxMessage.get(sandwich_order.solution_inbox_message_key)
        if not sim_parent.trashed and not sim_parent.deleted:
            sim_parent.trashed = True
            sim_parent.put()
            deferred.defer(update_user_data_admins, service_user, sandwich_order.service_identity)
        sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, sandwich_order.service_identity)
        sm_data.append({u"type": u"solutions.common.messaging.update",
                     u"message": serialize_complex_value(SolutionInboxMessageTO.fromModel(sim_parent, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False)})

    send_message(service_user, sm_data, service_identity=sandwich_order.service_identity)
def add_chat_members(api_key, parent_message_key, members=None, reader_members=None, json_rpc_id=None):
    method = 'messaging.add_chat_members'
    if reader_members is None:
        reader_members = []
    if members is None:
        members = []
    params = dict(parent_message_key=parent_message_key,
                  members=serialize_complex_value(members, MemberTO, True, skip_missing=True),
                  reader_members=serialize_complex_value(reader_members, MemberTO, True, skip_missing=True))
    return call_rogerthat(api_key, method, params, json_rpc_id)
    def testSerializeWithMISSING(self):
        RESULT_STR = """{"id":"ef0da970-eaec-11e2-9eeb-af96f4efab6f","result":{"type":"form","value":{"attachments":[],"message":"Beste Test agent 11, \\n\\nselecteer de dag waarvan u de schedule wil bekijken:","flags":0,"alert_flags":0,"branding":"9D104A3966ADA1E11B2508606944E6EFC2E1DF49DC9A041A23CF8C4114CF5F5C","tag":"{\\"_id\\":\\"select_date_get_schedule\\"}","form":{"positive_button":"Verder","positive_confirmation":null,"positive_button_ui_flags":1,"negative_button":"Annuleren","negative_confirmation":null,"negative_button_ui_flags":0,"type":"date_select","widget":{"date":0,"min_date":1373587200,"max_date":1405123200,"minute_interval":30,"mode":"date","unit":null}}}},"error":null}"""
        resp = json.loads(RESULT_STR)

        f = poke_service_callback_response_receiver
        type_ = f.meta[u"kwarg_types"][u"result"]
        result = parse_parameter(u"result", type_, resp["result"])

        d = serialize_complex_value(result, type_, False, skip_missing=True)
        json.dumps(d)  # this crashes if MISSING is in the serialized result

        self.assertRaises(Exception, json.dumps, serialize_complex_value(result, type_, False, skip_missing=False))
 def post(self, app_id, asset_type):
     validate_request_authentication(self, Scopes.APP_EDITOR, {'app_id': app_id})
     scale_x = float(self.request.get('scale_x'))
     file_data = self.request.POST.get('file')
     self.response.headers['Content-Type'] = 'application/json'
     try:
         asset = process_uploaded_assets(unicode(asset_type), file_data, False, [unicode(app_id)], scale_x)
         response_data = serialize_complex_value(AppAssetFullTO.from_model(asset), AppAssetFullTO, False)
     except BusinessException as exception:
         err = ErrorResponse(HttpBadRequestException(exception.message))
         response_data = serialize_complex_value(err, ErrorResponse, False)
         self.response.status = err.status_code
     self.response.write(json.dumps(response_data))
Example #8
0
    def testSerializeWithMISSING(self):
        RESULT_STR = """{"id":"ef0da970-eaec-11e2-9eeb-af96f4efab6f","result":{"type":"form","value":{"attachments":[],"message":"Beste Test agent 11, \\n\\nselecteer de dag waarvan u de schedule wil bekijken:","flags":0,"alert_flags":0,"branding":"9D104A3966ADA1E11B2508606944E6EFC2E1DF49DC9A041A23CF8C4114CF5F5C","tag":"{\\"_id\\":\\"select_date_get_schedule\\"}","form":{"positive_button":"Verder","positive_confirmation":null,"positive_button_ui_flags":1,"negative_button":"Annuleren","negative_confirmation":null,"negative_button_ui_flags":0,"type":"date_select","widget":{"date":0,"min_date":1373587200,"max_date":1405123200,"minute_interval":30,"mode":"date","unit":null}}}},"error":null}"""
        resp = json.loads(RESULT_STR)

        f = poke_service_callback_response_receiver
        type_ = f.meta[u"kwarg_types"][u"result"]
        result = parse_parameter(u"result", type_, resp["result"])

        d = serialize_complex_value(result, type_, False, skip_missing=True)
        json.dumps(d)  # this crashes if MISSING is in the serialized result

        self.assertRaises(
            Exception, json.dumps,
            serialize_complex_value(result, type_, False, skip_missing=False))
Example #9
0
def _validate_start_flow(service_identity_user, parent_message_key, members, check_friends=True,
                         tag=None, allow_reserved_tag=False, flow_params=None):
    if not members:
        raise NoMembersException()

    if parent_message_key and len(members) > 1:
        raise MessageParentKeyCannotBeUsedWithMultipleParents()

    if tag and not allow_reserved_tag and tag.startswith(MC_RESERVED_TAG_PREFIX):
        raise ReservedTagException()

    # Create list with ServiceFriendKeys for the members
    if check_friends:
        fsic_keys = [FriendServiceIdentityConnection.createKey(member, service_identity_user) for member in members]
        fsics = db.get(fsic_keys)  # db.get returns a list of found and None
        non_friends = []
        for (member, fsic) in zip(members, fsics):
            if not fsic or fsic.deleted:
                m = BaseMemberTO()
                human_user, m.app_id = get_app_user_tuple(member)
                m.member = human_user.email()
                non_friends.append(m)

        if non_friends:
            raise NonFriendMembersException(serialize_complex_value(non_friends, BaseMemberTO, True))
    if flow_params:
        try:
            json.loads(flow_params)
        except ValueError:
            raise InvalidFlowParamsException()
    def post(self):
        params = dict(self.request.POST)
        logging.debug("PaymentLoginAppHandler with params %s", params)
        user = self.request.headers.get("X-MCTracker-User", None)
        password = self.request.headers.get("X-MCTracker-Pass", None)
        if not (user and password):
            logging.debug("user not provided")
            self.response.set_status(500)
            return

        if not users.set_json_rpc_user(base64.decodestring(user), base64.decodestring(password)):
            logging.debug("user not set")
            self.response.set_status(500)
            return
        app_user = users.get_current_user()

        state = params["state"]
        login_state = get_login_state(state)
        if app_user != login_state.app_user:
            self.response.set_status(500)
            logging.error("%s tried to finish anothers user login %s", app_user, state)
            return

        token = get_api_module(login_state.provider_id).handle_code(login_state)
        logging.debug('Received token: %s', token)
        if not finish_login_state(state, token):
            logging.debug("user already finished this login")
            self.response.set_status(500)
            return

        args = {"result": "success",
                "payment_provider": serialize_complex_value(
                    get_payment_provider_for_user(app_user, login_state.provider_id), AppPaymentProviderTO, False)}
        r = json.dumps(args)
        self.response.out.write(r)
Example #11
0
def sign_see_document(username, iyo_see_id, sign_result, user_detail):
    # type: (unicode, unicode, SignWidgetResultTO, UserDetailsTO) -> None
    public_key = sign_result.public_key.public_key
    iyo_organization_id = get_iyo_organization_id()
    logging.debug('Getting IYO SEE document %s', iyo_see_id)
    doc = get_see_document(iyo_organization_id, username, iyo_see_id)
    doc_view = IYOSeeDocumentView(username=doc.username,
                                  globalid=doc.globalid,
                                  uniqueid=doc.uniqueid,
                                  **serialize_complex_value(
                                      doc.versions[-1], IYOSeeDocumenVersion,
                                      False))
    doc_view.signature = sign_result.payload_signature
    keystore_label = get_publickey_label(public_key, user_detail)
    if not keystore_label:
        raise Exception(
            'Could not find keystore label for user %s and public key %s' %
            (user_detail, public_key))
    doc_view.keystore_label = keystore_label
    logging.debug('Signing IYO SEE document')
    try:
        _sign_see_document(iyo_organization_id, username, doc_view)
    except HTTPError as e:
        # Already signed, ignore
        if e.response.status_code != httplib.CONFLICT:
            raise e
Example #12
0
def solution_coupon_redeem(service_user, email, method, params, tag,
                           service_identity, user_details):
    data = json.loads(params)
    coupon_id = data.get('coupon_id')
    redeeming_user = users.User(data.get('redeeming_user'))
    response = SendApiCallCallbackResultTO()
    lang = get_solution_settings(service_user).main_language
    service_identity_user = get_and_validate_service_identity_user(
        service_user, service_identity)

    try:
        coupon = redeem_news_coupon(coupon_id, service_identity_user,
                                    redeeming_user)
        with users.set_user(service_user):
            news_item = news.get(coupon.news_id, service_identity)
            response.result = u'%s' % json.dumps(
                serialize_complex_value(news_item, NewsItemTO, False))
    except NewsCouponNotFoundException:
        response.error = t(lang, 'coupon_not_found')
    except NewsCouponAlreadyUsedException:
        response.error = t(lang, 'you_have_already_used_this_coupon')
        user, app_id = get_app_user_tuple(redeeming_user)
        member = BaseMemberTO(user.email(), app_id)
        disable_news_with_coupon(coupon_id, service_identity_user, member)
    except Exception as exception:
        logging.error(exception)
        response.error = t(lang, 'error-occured-unknown')
    return response
def delete_role_member(api_key, role_id, member, service_identity=None, json_rpc_id=None):
    call_rogerthat(api_key=api_key,
                   method="system.delete_role_member",
                   params=dict(role_id=role_id,
                               member=serialize_complex_value(member, BaseMemberTO, False, skip_missing=True),
                               service_identity=service_identity),
                   json_rpc_id=json_rpc_id)
def _export_brandings(export_zip, service_user, brandings):
    # type: (zipfile.ZipFile) -> None
    export_zip.writestr('brandings.json', json.dumps(serialize_complex_value(brandings, BrandingTO, True)))
    to_delete = []
    for branding in brandings:
        logging.info('Exporting branding %s - %s', branding.description, branding.id)
        gcs_filename = get_branding_cloudstorage_path(branding.id, service_user)
        try:
            with cloudstorage.open(gcs_filename, 'r',
                                   retry_params=RetryParams(max_retries=1 if DEBUG else 6)) as gcs_file:
                zip_path = os.path.join('brandings', '%s.zip' % branding.id)
                old_zip_stream = StringIO()
                old_zip_stream.write(gcs_file.read())
                the_zip = zipfile.ZipFile(old_zip_stream, compression=zipfile.ZIP_DEFLATED)
                new_zip_stream = StringIO()
                with zipfile.ZipFile(new_zip_stream, 'w', zipfile.ZIP_DEFLATED) as new_zip:
                    for f in the_zip.filelist:  # type: zipfile.ZipInfo
                        if f.filename == 'branding.html':
                            new_filename = Branding.TYPE_MAPPING[branding.type]
                            new_zip.writestr(new_filename, the_zip.read(f.filename))
                        else:
                            new_zip.writestr(f.filename, the_zip.read(f.filename))
                export_zip.writestr(zip_path, new_zip_stream.getvalue())
        except cloudstorage.NotFoundError:
            logging.error('file %s not found' % gcs_filename)
        except cloudstorage.ServerError as e:
            logging.exception('Error while getting branding from cloudstorage')
            if DEBUG and 'But got status 500' in e.message:
                to_delete.append(Branding.create_key(branding.id))
    if to_delete:
        logging.info('Deleting %s brandings that were not found', len(to_delete))
        db.delete(to_delete)
 def get(self):
     user = users.get_current_user()
     self.response.headers['Content-Type'] = 'text/json'
     app_settings = get_app_settings(App.APP_ID_ROGERTHAT)
     user_profile = get_user_profile(user)
     self.response.out.write(
         json.dumps(serialize_complex_value(SettingsTO.fromDBSettings(app_settings, user_profile, Settings.get()), SettingsTO, False)))
Example #16
0
    def trans():
        sln_cwl.pending = False
        sln_cwl.winners = winners
        sln_cwl.winners_info = json.dumps(
            serialize_complex_value(winners_info, ExtendedUserDetailsTO, True))
        sln_cwl.put()
        deferred.defer(_redeem_city_wide_lottery_visits,
                       service_user,
                       sln_cwl_lottery_key,
                       now(),
                       _transactional=True)

        to_emails = sln_settings.inbox_mail_forwarders
        if to_emails:
            solution_server_settings = get_solution_server_settings()
            subject = 'Winnaars gemeentelijke tombola'
            body = """Beste,
Volgende mensen hebben gewonnen met de tombola: %s


Met vriendelijke groeten,

Het Onze Stad App Team
""" % winner_text

            send_mail(solution_server_settings.shop_export_email, to_emails,
                      subject, body)
def delete_chat_members(api_key, parent_message_key, members=None, soft=False, json_rpc_id=None):
    method = 'messaging.delete_chat_members'
    if members is None:
        members = []
    params = dict(parent_message_key=parent_message_key,
                  members=serialize_complex_value(members, MemberTO, True, skip_missing=True),
                  soft=soft)
    return call_rogerthat(api_key, method, params, json_rpc_id)
Example #18
0
def create_keystore_key(username, data):
    client = get_itsyouonline_client_from_username(username)
    data = serialize_complex_value(data,
                                   IYOKeyStoreKey,
                                   False,
                                   skip_missing=True)
    result = client.api.users.SaveKeyStoreKey(data, convert_to_str(username))
    return IYOKeyStoreKey(**result.json())
Example #19
0
def messaging_poke(rt_settings, id_, email, tag, result_key, context, service_identity, user_details, timestamp):
    handler = POKE_TAG_MAPPING.get(parse_to_human_readable_tag(tag))
    if not handler:
        logging.info('Ignoring poke with tag %s', tag)
        return None
    user_details = log_and_parse_user_details(user_details[0])
    result = handler(email, tag, result_key, context, service_identity, user_details)
    return result and serialize_complex_value(result, PokeCallbackResultTO, False, skip_missing=True)
Example #20
0
def create_see_document(username, doc):
    client = get_itsyouonline_client_from_username(username)
    data = serialize_complex_value(doc,
                                   IYOSeeDocumentView,
                                   False,
                                   skip_missing=True)
    result = client.api.users.CreateSeeObject(data, convert_to_str(username))
    return IYOSeeDocumentView(**result.json())
Example #21
0
def _repair_order_received(service_user, message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key,
                   tag, result_key, flush_id, flush_message_flow_id, service_identity, user_details):
    from solutions.common.bizz.messaging import send_inbox_forwarders_message


    logging.info("_flow_member_result_repair_order: \n %s" % steps)

    remarks = _get_value(steps[0], u'message_remarks')
    if steps[1].answer_id == u"positive":
        picture_url = _get_value(steps[1], u'message_picture')
    else:
        picture_url = None

    sln_settings = get_solution_settings(service_user)

    logging.info("Saving repair order from %s" % user_details[0].email)
    service_identity_user = create_service_identity_user_wo_default(service_user, service_identity)
    o = SolutionRepairOrder(parent=parent_key_unsafe(service_identity_user, sln_settings.solution))
    o.description = remarks
    o.sender = SolutionUser.fromTO(user_details[0])
    o.timestamp = steps[1].received_timestamp
    o.status = SolutionRepairOrder.STATUS_RECEIVED
    o.picture_url = picture_url
    o.user = user_details[0].toAppUser() if user_details else None

    msg = common_translate(sln_settings.main_language, SOLUTION_COMMON, 'if-repair-order-received',
                           remarks=remarks)

    message = create_solution_inbox_message(service_user, service_identity, SolutionInboxMessage.CATEGORY_REPAIR, None, False, user_details, steps[1].received_timestamp, msg, True, [picture_url] if picture_url else [])
    o.solution_inbox_message_key = message.solution_inbox_message_key
    o.put()
    message.category_key = unicode(o.key())
    message.put()

    sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, service_identity)

    sm_data = []
    sm_data.append({u"type": u"solutions.common.repair_orders.update"})
    sm_data.append({u"type": u"solutions.common.messaging.update",
                 u"message": serialize_complex_value(SolutionInboxMessageTO.fromModel(message, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False)})

    send_message(service_user, sm_data, service_identity=service_identity)

    attachments = []
    if picture_url:
        att = AttachmentTO()
        att.content_type = AttachmentTO.CONTENT_TYPE_IMG_JPG
        att.download_url = picture_url
        att.name = common_translate(sln_settings.main_language, SOLUTION_COMMON, u'picture')
        att.size = 0
        attachments = [att]

    app_user = user_details[0].toAppUser()

    send_inbox_forwarders_message(service_user, service_identity, app_user, msg, {
            'if_name': user_details[0].name,
            'if_email':user_details[0].email
        }, message_key=message.solution_inbox_message_key, attachments=attachments, reply_enabled=message.reply_enabled)
Example #22
0
def get_streets(sik, service_identity, email, app_id, params):
    try:
        r = get_api_streets(sik)
        return {"result": json.dumps(serialize_complex_value(r, StreetTO, True)),
                "error": None}
    except:
        logging.exception(u"get_api_streets failed")
        return {"result": None,
                "error": u"get_api_streets failed"}
Example #23
0
def update_see_document(organization_id, username, doc):
    client = get_itsyouonline_client_from_username(username)
    data = serialize_complex_value(doc,
                                   IYOSeeDocumentView,
                                   False,
                                   skip_missing=True)
    result = client.users.UpdateSeeObject(data, doc.uniqueid, organization_id,
                                          convert_to_str(username))
    return IYOSeeDocumentView(**result.json())
 def handle(self, branding_id):
     validate_request_authentication(self, Scopes.BACKEND_EDITOR, {})
     default = self.request.get('is_default') == 'true'
     app_ids = [a for a in self.request.get('app_ids', '').split(',') if a]
     file_data = self.request.POST.get('file')
     branding_type = self.request.POST.get('branding_type')
     try:
         branding = save_default_branding(branding_type, file_data, default, app_ids, branding_id)
         response_data = serialize_complex_value(DefaultBrandingTO.from_model(branding), DefaultBrandingTO, False)
     except AppAssetNotFoundException as exception:
         err = ErrorResponse(HttpNotFoundException(exception.message))
         response_data = serialize_complex_value(err, ErrorResponse, False)
         self.response.status = err.status_code
     except BusinessException as exception:
         err = ErrorResponse(HttpBadRequestException(exception.message))
         response_data = serialize_complex_value(err, ErrorResponse, False)
         self.response.status = err.status_code
     self.response.write(json.dumps(response_data))
Example #25
0
def _send_event_notification(sln_settings, service_user, service_identity,
                             user_details, event, event_guest):
    from solutions.common.bizz.messaging import send_inbox_forwarders_message

    status = translate(sln_settings.main_language, SOLUTION_COMMON,
                       event_guest.status_str)
    status_message = translate(sln_settings.main_language,
                               SOLUTION_COMMON,
                               u'events_status_notification',
                               status=status,
                               event=event.title)

    create_chat = True
    if event_guest.chat_key:
        create_chat = SolutionInboxMessage.get(event_guest.chat_key) is None

    if create_chat:
        event_key = unicode(event.key())
        message = create_solution_inbox_message(
            service_user, service_identity,
            SolutionInboxMessage.CATEGORY_AGENDA, event_key, False,
            user_details, now(), status_message, True)
        event_guest.chat_key = message.solution_inbox_message_key
        event_guest.put()

        app_user = user_details[0].toAppUser()
    else:
        message, _ = add_solution_inbox_message(service_user,
                                                event_guest.chat_key, False,
                                                user_details, now(),
                                                status_message)
        app_user = None

    send_inbox_forwarders_message(
        service_user,
        service_identity,
        app_user,
        status_message, {
            'if_name': user_details[0].name,
            'if_email': user_details[0].email
        },
        message_key=message.solution_inbox_message_key,
        reply_enabled=message.reply_enabled,
        send_reminder=False)

    # show as last message
    sln_i_settings = get_solution_settings_or_identity_settings(
        sln_settings, service_identity)
    message_to = SolutionInboxMessageTO.fromModel(message, sln_settings,
                                                  sln_i_settings, True)
    send_message(service_user,
                 u'solutions.common.messaging.update',
                 service_identity=service_identity,
                 message=serialize_complex_value(message_to,
                                                 SolutionInboxMessageTO,
                                                 False))
Example #26
0
def get_street_numbers(sik, service_identity, email, app_id, params):
    try:
        jsondata = json.loads(params)
        r = get_api_houses(sik, long(jsondata["streetnumber"]))
        return {"result": json.dumps(serialize_complex_value(r, HouseTO, True)),
                "error": None}
    except:
        logging.exception(u"get_street_numbers failed")
        return {"result": None,
                "error": u"get_street_numbers failed"}
 def handle(self, asset_id):
     validate_request_authentication(self, Scopes.BACKEND_EDITOR, {})
     scale_x = float(self.request.get('scale_x'))
     app_ids = [a for a in self.request.get('app_ids', '').split(',') if a]
     default = self.request.get('is_default') == 'true'
     asset_type = unicode(self.request.get('asset_type'))
     file_data = self.request.POST.get('file')
     try:
         asset = process_uploaded_assets(asset_type, file_data, default, app_ids, scale_x, asset_id)
         response_data = serialize_complex_value(AppAssetFullTO.from_model(asset), AppAssetFullTO, False)
     except AppAssetNotFoundException as exception:
         err = ErrorResponse(HttpNotFoundException(exception.message))
         response_data = serialize_complex_value(err, ErrorResponse, False)
         self.response.status = err.status_code
     except BusinessException as exception:
         err = ErrorResponse(HttpBadRequestException(exception.message))
         response_data = serialize_complex_value(err, ErrorResponse, False)
         self.response.status = err.status_code
     self.response.write(json.dumps(response_data))
Example #28
0
def _update_user_data(sik, service_identity, email, app_id, address, notifications, collections):
    settings = RogerthatSettings.create_key(sik).get()
    user_data = dict()
    user_data["trash"] = {}
    user_data["trash"]["address"] = address
    activities = {}
    for collection in collections:
        activities[collection.activity.number] = collection.activity

    user_data["trash"]["collections"] = serialize_complex_value(collections, CollectionTO, True)
    user_data["trash"]["notifications"] = notifications
    user_data["trash"]["notification_types"] = serialize_complex_value(sorted(activities.values(), key=lambda a: a.name), ActivityTO, True)

    try:
        system.put_user_data(settings.api_key, email, app_id, user_data, service_identity)
    except RogerthatApiException, e:
        if e.code != ROGERTHAT_EXCEPTION_CODE_SERVICE_USER_NOT_FOUND:
            raise e
        logging.debug("Ignoring _update_user_data user de-friended")
Example #29
0
def send_inbox_message_update(sln_settings, message, service_identity=None):
    service_user = sln_settings.service_user
    sln_i_settings = get_solution_settings_or_identity_settings(
        sln_settings, service_identity)
    message_to = SolutionInboxMessageTO.fromModel(message, sln_settings,
                                                  sln_i_settings, True)
    data = serialize_complex_value(message_to, SolutionInboxMessageTO, False)
    channel.send_message(service_user,
                         u'solutions.common.messaging.update',
                         message=data,
                         service_identity=service_identity)
    def test_feed_names(self):
        service_profile = create_service_profile(self.user, u'test name')[0]
        service_profile.broadcastTypes.append(self._get_broadcast_type(1234))
        service_profile.put()

        feed_names = [NewsFeedNameTO(u'rogerthat', u'bla_ moehaha')]

        with set_current_user(self.user, skip_create_session=True):
            news_item = self._create_news_item(1234, feed_names=feed_names)
            self.assertEqual(serialize_complex_value(feed_names, NewsFeedNameTO, True), serialize_complex_value(news_item.feed_names, NewsFeedNameTO, True))
            self.assertEqual([u'news'], news_item.tags)
 def to_dict(self, include=None, exclude=None):
     # type: (list[basestring], list[basestring]) -> dict
     result = serialize_complex_value(self, type(self), False, skip_missing=True)
     if include:
         if not isinstance(include, list):
             include = [include]
         return {key: result[key] for key in include if key in result}
     if exclude:
         if not isinstance(exclude, list):
             exclude = [exclude]
         return {key: result[key] for key in set(result.keys()) - set(exclude) if key in result}
     return result
def send_chat_message(api_key, parent_key, message, answers=None, attachments=None, sender=None, priority=None,
                      sticky=False, tag=None, alert_flags=Message.ALERT_FLAG_VIBRATE, json_rpc_id=None):
    method = 'messaging.send_chat_message'
    if not attachments:
        attachments = list()
    if not answers:
        answers = list()
    if not priority:
        priority = 0
    params = dict(
        parent_key=parent_key,
        message=message,
        answers=serialize_complex_value(answers, AnswerTO, True, skip_missing=True),
        attachments=serialize_complex_value(attachments, AttachmentTO, True, skip_missing=True),
        sender=sender,
        priority=priority,
        sticky=sticky,
        tag=tag,
        alert_flags=alert_flags
    )
    return call_rogerthat(api_key, method, params, json_rpc_id)
Example #33
0
def messaging_update(rt_settings, request_id, status, answer_id, received_timestamp, member, message_key, tag,
                     acked_timestamp, parent_message_key, service_identity, user_details, **kwargs):
    if not is_flag_set(Message.STATUS_ACKED, status):
        return None

    user_details = log_and_parse_user_details(user_details)
    f = FMR_TAG_MAPPING.get(parse_to_human_readable_tag(tag))
    if not f:
        return None

    result = f(status, answer_id, received_timestamp, member, message_key, tag, acked_timestamp, parent_message_key,
               service_identity, user_details)
    return result and serialize_complex_value(result, MessageAcknowledgedCallbackResultTO, False, skip_missing=True)
Example #34
0
    def trans():
        sln_settings = get_solution_settings(service_user)
        menu = get_restaurant_menu(service_user, sln_settings.solution)
        category = menu.categories[category_id]
        if not category:
            return create_error(
                common_translate(sln_settings.main_language,
                                 SOLUTION_COMMON,
                                 u'category_not_found',
                                 name=category_name))
        for item in category.items:
            if item.id == item_id:
                break
        else:
            return create_error(
                common_translate(sln_settings.main_language,
                                 SOLUTION_COMMON,
                                 u'item_not_found',
                                 name=item_name))

        if item.image_id:
            delete_file_blob(service_user, item.image_id)

        response = download_image()
        if response.status_code != 200:
            return create_error(
                common_translate(sln_settings.main_language, SOLUTION_COMMON,
                                 u'error-occured-unknown-try-again'))

        item.image_id = create_file_blob(service_user,
                                         response.content).key().id()
        menu.put()
        on_trans_committed(channel.send_message,
                           service_user,
                           'solutions.common.menu.item_image_configured',
                           category=serialize_complex_value(
                               category, MenuCategory, False),
                           item=serialize_complex_value(item, MenuItem, False))
        return None
def broadcast(api_key, broadcast_type, message, answers, flags, branding, tag, service_identity=None,
              alert_flags=Message.ALERT_FLAG_VIBRATE, dismiss_button_ui_flags=0, target_audience=None, attachments=None,
              timeout=0, json_rpc_id=None):
    method = 'messaging.broadcast'
    if not attachments:
        attachments = list()
    params = dict(
        broadcast_type=broadcast_type,
        message=message,
        answers=serialize_complex_value(answers, AnswerTO, True, skip_missing=True),
        flags=flags,
        branding=branding,
        tag=tag,
        service_identity=service_identity,
        alert_flags=alert_flags,
        dismiss_button_ui_flags=dismiss_button_ui_flags,
        target_audience=serialize_complex_value(target_audience, BroadcastTargetAudienceTO, False, skip_missing=True),
        attachments=serialize_complex_value(attachments, AttachmentTO, True, skip_missing=True),
        timeout=timeout
    )
    result = call_rogerthat(api_key, method, params, json_rpc_id)
    return parse_complex_value(BroadcastResultTO, result, False)
Example #36
0
 def write_result(self, result):
     self.response.headers.update({'Content-Type': 'application/json'})
     if result is not None:
         if type(result) == ErrorResponse:
             self.response.set_status(result.status_code)
             result = serialize_complex_value(result, ErrorResponse, False)
         if DEBUG:
             self.response.out.write(
                 json.dumps(result, indent=2, sort_keys=True))
         else:
             self.response.out.write(json.dumps(result))
     else:
         self.response.set_status(httplib.NO_CONTENT)
    def post(self, app_id, branding_type):
        validate_request_authentication(self, Scopes.APP_EDITOR, {'app_id': app_id})
        file_data = self.request.POST.get('file')
        self.response.headers['Content-Type'] = 'application/json'
        if file_data is None:
            err = ErrorResponse(HttpBadRequestException('missing_file'))
            response_data = serialize_complex_value(err, ErrorResponse, False)
            self.response.status = httplib.BAD_REQUEST
        else:
            try:
                branding = save_default_branding(unicode(branding_type), file_data, False, [unicode(app_id)])
                response_data = serialize_complex_value(DefaultBrandingTO.from_model(branding), DefaultBrandingTO,
                                                        False)
            except BusinessException as exception:
                err = ErrorResponse(HttpBadRequestException(exception.message))
                response_data = serialize_complex_value(err, ErrorResponse, False)
                self.response.status = err.status_code
            except HttpException as e:
                response_data = serialize_complex_value(ErrorResponse(e), ErrorResponse, False)
                self.response.status = e.http_code

        self.response.write(json.dumps(response_data))
Example #38
0
def _gather_events_for_customer(customer_key, cap_key, organization_type):
    customer = Customer.get(customer_key)
    if not customer.service_email:
        logging.debug('This customer has no service yet: %s',
                      db.to_dict(customer))
        return
    if cap_key.parent().name() == customer.service_email:
        # do not gather own events
        return
    sln_settings = get_solution_settings(customer.service_user)
    if SolutionModule.AGENDA not in sln_settings.modules:
        return
    if sln_settings.default_calendar is None:
        logging.error(
            'This customer has no default calendar!\n\nSolutionSettings: %s\n\nCustomer: %s',
            db.to_dict(sln_settings),
            db.to_dict(customer),
            _suppress=False)
        return
    sc = SolutionCalendar.get_by_id(
        sln_settings.default_calendar,
        parent_key(customer.service_user, sln_settings.solution))
    if not sc:
        return

    event_items = []
    for event in sc.events:
        event_item = EventItemTO.fromEventItemObject(event)
        event_item.calendar_id = organization_type
        event_items.append(event_item)

    if event_items:
        new_events = serialize_complex_value(event_items, EventItemTO, True)
        gather_events_key = u"%s" % organization_type

        def trans():
            cap = CityAppProfile.get(cap_key)
            stream = cap.gather_events.get(gather_events_key)
            if stream:
                json_list = json.load(stream)
            else:
                json_list = list()
            json_list.extend(new_events)
            with closing(StringIO()) as stream:
                json.dump(json_list, stream)
                cap.gather_events[gather_events_key] = stream
            cap.put()

        db.run_in_transaction(trans)
        sln_settings.put_identity_pending = True
        sln_settings.put()
Example #39
0
def get_customer_locations_for_app(app_id):
    query_string = (u'app_ids:"%s"' % app_id)
    query = search.Query(query_string=query_string,
                         options=search.QueryOptions(returned_fields=[
                             'service', 'name', 'location', 'description'
                         ],
                                                     limit=1000))
    search_result = search.Index(name=SERVICE_LOCATION_INDEX).search(query)

    customers = {
        customer.service_email: customer
        for customer in Customer.list_by_app_id(app_id)
    }

    def map_result(service_search_result):
        customer_location = CustomerLocationTO()
        for field in service_search_result.fields:
            if field.name == 'service':
                customer = customers.get(field.value.split('/')[0])
                if customer:
                    customer_location.has_terminal = customer.has_loyalty
                    customer_location.address = customer.address1
                    customer_location.type = customer.organization_type
                    if customer.address2:
                        customer_location.address += '\n%s' % customer.address2
                    if customer.zip_code or customer.city:
                        customer_location.address += '\n'
                        if customer.zip_code:
                            customer_location.address += customer.zip_code
                        if customer.zip_code and customer.city:
                            customer_location.address += ' '
                        if customer.city:
                            customer_location.address += customer.city
                else:
                    customer_location.type = ServiceProfile.ORGANIZATION_TYPE_PROFIT
                continue
            if field.name == 'name':
                customer_location.name = field.value
                continue
            if field.name == 'location':
                customer_location.lat = field.value.latitude
                customer_location.lon = field.value.longitude
                continue
            if field.name == 'description':
                customer_location.description = field.value
                continue
        return customer_location

    return json.dumps(
        serialize_complex_value([map_result(r) for r in search_result.results],
                                CustomerLocationTO, True))
 def get(self):
     user = users.get_current_user()
     self.response.headers['Content-Type'] = 'text/json'
     mobile_id = self.request.GET['mobile_id']
     mobile = get_mobile_by_id(mobile_id)
     azzert(mobile.user == user)
     settings = MobileSettings.get(mobile)
     app_settings = get_app_settings(App.APP_ID_ROGERTHAT)
     settingsDict = serialize_complex_value(SettingsTO.fromDBSettings(settings, app_settings), SettingsTO, False)
     settingsDict["description"] = mobile.description
     settingsDict["hardwareModel"] = mobile.hardwareModel
     settingsDict["color"] = settings.color
     settingsDict["type"] = mobile.type
     self.response.out.write(json.dumps(settingsDict))
def send(api_key, parent_message_key, message, answers, flags, members, branding, tag,
         alert_flags=Message.ALERT_FLAG_VIBRATE, dismiss_button_ui_flags=0, context=None, attachments=None,
         broadcast_guid=None, step_id=None, json_rpc_id=None):
    if attachments is None:
        attachments = []
    result = call_rogerthat(api_key,
                            method="messaging.send",
                            params=dict(parent_message_key=parent_message_key,
                                        message=message,
                                        answers=serialize_complex_value(answers, AnswerTO, True, skip_missing=True),
                                        flags=flags,
                                        members=serialize_complex_value(members, MemberTO, True, skip_missing=True),
                                        branding=branding,
                                        tag=tag,
                                        alert_flags=alert_flags,
                                        dismiss_button_ui_flags=dismiss_button_ui_flags,
                                        context=context,
                                        attachments=serialize_complex_value(attachments, AttachmentTO, True,
                                                                            skip_missing=True),
                                        broadcast_guid=broadcast_guid,
                                        step_id=step_id),
                            json_rpc_id=json_rpc_id)
    return result
Example #42
0
 def write_result(self, result):
     self.response.headers.update({
         'Content-Type': 'application/json'
     })
     if result is not None:
         if type(result) == ErrorResponse:
             self.response.set_status(result.status_code)
             result = serialize_complex_value(result, ErrorResponse, False)
         if DEBUG:
             self.response.out.write(json.dumps(result, indent=2, sort_keys=True))
         else:
             self.response.out.write(json.dumps(result))
     else:
         self.response.set_status(httplib.NO_CONTENT)
def _save_backend(backend_server, backend_server_to):
    """
    Args:
        backend_server (BackendServer)
        backend_server_to (BackendServerTO)

    Returns:
        BackendServer
    """
    params = serialize_complex_value(backend_server_to, BackendServerTO, False)
    params.pop('id')
    backend_server.populate(**params)
    backend_server.put()
    return backend_server
def start_chat(api_key, members, topic, description, alert_flags=Message.ALERT_FLAG_VIBRATE, service_identity=None,
               tag=None, context=None, reader_members=None, flags=0, metadata=None, avatar=None, background_color=None,
               text_color=None, default_priority=Message.PRIORITY_NORMAL, default_sticky=False, json_rpc_id=None):
    method = 'messaging.start_chat'
    if reader_members is None:
        reader_members = list()
    if metadata is None:
        metadata = list()
    params = dict(members=serialize_complex_value(members, MemberTO, True, skip_missing=True),
                  topic=topic,
                  description=description,
                  alert_flags=alert_flags,
                  service_identity=service_identity,
                  tag=tag,
                  context=context,
                  reader_members=serialize_complex_value(reader_members, MemberTO, True, skip_missing=True),
                  flags=flags,
                  metadata=serialize_complex_value(metadata, KeyValueTO, True, skip_missing=True),
                  avatar=avatar,
                  background_color=background_color,
                  text_color=text_color,
                  default_priority=default_priority,
                  default_sticky=default_sticky)
    return call_rogerthat(api_key, method, params, json_rpc_id)
def send_form(api_key, parent_message_key, member, message, form, flags, alert_flags, branding, tag,
              service_identity=None, context=None, attachments=None, app_id=None, broadcast_guid=None, step_id=None,
              json_rpc_id=None):
    if attachments is None:
        attachments = []
    result = call_rogerthat(api_key,
                            method="messaging.send_form",
                            params=dict(parent_message_key=parent_message_key,
                                        member=member,
                                        message=message,
                                        form=serialize_complex_value(form, FormTO, False, skip_missing=True),
                                        flags=flags,
                                        alert_flags=alert_flags,
                                        branding=branding,
                                        tag=tag,
                                        service_identity=service_identity,
                                        context=context,
                                        attachments=serialize_complex_value(attachments, AttachmentTO, True,
                                                                            skip_missing=True),
                                        app_id=app_id,
                                        broadcast_guid=broadcast_guid,
                                        step_id=step_id),
                            json_rpc_id=json_rpc_id)
    return result
def _trigger_update_friend(target_user, friend_map_or_key, profile_info_or_key):
    profile_info = db.get(profile_info_or_key) if isinstance(profile_info_or_key, db.Key) else profile_info_or_key
    logging.info("Sending out updates for %s (%s)", profile_info.name, profile_info.user.email())

    friendTO = send_update_friend_request(target_user, profile_info.user, UpdateFriendRequestTO.STATUS_MODIFIED,
                                          friend_map_or_key)
    if friendTO:
        if profile_info.isServiceIdentity:
            # Send update request over channel API
            friend_dict = serialize_complex_value(friendTO, FriendTO, False)
            # Preventing "InvalidMessageError: Message must be no longer than 32767 chars"
            del friend_dict['appData']
            del friend_dict['userData']
            channel.send_message(target_user, u'rogerthat.friends.update',
                                 friend=friend_dict)
Example #47
0
def bulk_invite_result(service_user, service_identity, tag, email, result, user_details):
    if not tag:
        logging.exception("Expected tag in bulk_invite_result")
        return

    if tag in (SERVICE_AUTOCONNECT_INVITE_TAG, APP_BROADCAST_TAG):
        return

    try:
        key = db.Key(tag)
    except db.BadKeyError:
        logging.info('Tag is no db.Key: %s. Ignoring...', tag)
        return

    def trans():
        invite = db.get(reconstruct_key(key))
        if not invite:
            logging.error("Invite object not found in datastore")
            return
        save_message = False
        if "accepted" == result:
            invite.status = RestaurantInvite.STATUS_ACCEPTED
            save_message = True
        else:
            invite.status = RestaurantInvite.STATUS_REJECTED
        invite.put()
        return save_message

    save_message = run_in_xg_transaction(trans)
    if save_message:
        now_ = now()
        sln_settings = get_solution_settings(service_user)
        msg = common_translate(sln_settings.main_language, SOLUTION_COMMON, 'if-accepted-invitation',
                               if_name=user_details[0].name,
                               if_email=user_details[0].email)

        message = create_solution_inbox_message(
            service_user, service_identity, SolutionInboxMessage.CATEGORY_BULK_INVITE, None, False, user_details, now_, msg, False)
        app_user = create_app_user_by_email(user_details[0].email, user_details[0].app_id)
        send_inbox_forwarders_message(service_user, service_identity, app_user, msg, {
            'if_name': user_details[0].name,
            'if_email': user_details[0].email
        }, message_key=message.solution_inbox_message_key, reply_enabled=message.reply_enabled, send_reminder=False)

        sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, service_identity)
        send_message(service_user, u"solutions.common.messaging.update",
                     service_identity=service_identity,
                     message=serialize_complex_value(SolutionInboxMessageTO.fromModel(message, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False))
Example #48
0
def common_new_chat_message(parent_message_key, message_key, sender, message, answers, timestamp, tag, service_identity,
                            attachments):
    if tag and tag.startswith(POKE_TAG_INBOX_FORWARDING_REPLY):
        info = json.loads(tag[len(POKE_TAG_INBOX_FORWARDING_REPLY):])
        message_key = info['message_key']
        sim_parent = SolutionInboxMessage.get(reconstruct_key(db.Key(message_key)))

        if sim_parent.awaiting_first_message:
            sim_parent.awaiting_first_message = False
            sim_parent.put()
        else:
            service_user = sim_parent.service_user
            sln_settings = get_solution_settings(service_user)
            sent_by_service = True
            if sim_parent.sender.email == sender.email and sim_parent.sender.app_id == sender.app_id:
                sent_by_service = False

            picture_attachments = []
            video_attachments = []
            for a in attachments:
                if a.content_type.startswith("image"):
                    picture_attachments.append(a.download_url)
                if a.content_type.startswith("video"):
                    video_attachments.append(a.download_url)

            if sent_by_service:
                sim_parent, _ = add_solution_inbox_message(service_user, message_key, sent_by_service, [sender], timestamp, message, picture_attachments, video_attachments, mark_as_unread=False, mark_as_read=True)
            else:
                sim_parent, _ = add_solution_inbox_message(service_user, message_key, sent_by_service, [sender], timestamp, message, picture_attachments, video_attachments)

            sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, service_identity)
            send_message(service_user, u"solutions.common.messaging.update",
                         service_identity=service_identity,
                         message=serialize_complex_value(SolutionInboxMessageTO.fromModel(sim_parent, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False))

            member_sender_user = create_app_user_by_email(sim_parent.sender.email, sim_parent.sender.app_id)
            sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, service_identity)
            members = [MemberTO.from_user(users.User(f)) for f in sln_i_settings.inbox_forwarders]
            if member_sender_user.email() not in sln_i_settings.inbox_forwarders:
                members.append(MemberTO.from_user(member_sender_user))

            users.set_user(service_user)
            try:
                messaging.add_chat_members(sim_parent.message_key, members)
            finally:
                users.clear_user()
    else:
        raise NotImplementedError()
Example #49
0
 def get(self, app_id):
     template = JINJA_ENVIRONMENT.get_template('app_translations.html')
     js_template = JINJA_ENVIRONMENT.get_template('app_translations_part.html').render()
     app = App.get(App.create_key(app_id))
     if not app:
         self.response.out.write('app %s does not exist' % app_id)
         return
     app_translations_key = AppTranslations.create_key(app_id)
     translations = AppTranslations.get_or_insert(app_translations_key.name(), parent=app_translations_key.parent())
     parameters = {
         'templates': json.dumps({'app_translations_part': js_template}),
         'translations': json.dumps(
             zlib.decompress(translations.translations) if translations.translations else None),
         'app': json.dumps(serialize_complex_value(AppTO.fromModel(app), AppTO, False))
     }
     self.response.out.write(template.render(parameters))
Example #50
0
 def post(self):
     app_id = self.request.POST.get("app_id", None)
     self.response.headers['Content-Type'] = 'text/json'
     if app_id:
         app = get_app_by_id(app_id)
         if app:
             app_dict = serialize_complex_value(AppTO.fromModel(app, True), AppTO, False)
             # append service_role_names to app_dict
             for acs in app_dict['auto_connected_services']:
                 service_user = get_service_user_from_service_identity_user(users.User(acs['service_identity_email']))
                 acs['service_role_names'] = [r.name for r in get_service_roles_by_ids(service_user,
                                                                                       acs['service_roles'])]
             logging.debug("Returning %s", app_dict)
             self.response.out.write(json.dumps(dict(success=True, errormsg=None, app=app_dict)))
             return
     self.response.out.write(json.dumps(dict(success=False, errormsg=u"Could not find app")))
def start_local_flow(api_key, xml, members, service_identity=None, tag=None, parent_message_key=None, context=None,
                     force_language=None, download_attachments_upfront=False, push_message=None, flow=None,
                     flow_params=None, json_rpc_id=None):
    return call_rogerthat(api_key,
                          method="messaging.start_local_flow",
                          params=dict(xml=xml,
                                      members=serialize_complex_value(members, MemberTO, True, skip_missing=True),
                                      service_identity=service_identity,
                                      tag=tag,
                                      parent_message_key=parent_message_key,
                                      context=context,
                                      force_language=force_language,
                                      download_attachments_upfront=download_attachments_upfront,
                                      push_message=push_message,
                                      flow=flow,
                                      flow_params=flow_params),
                          json_rpc_id=json_rpc_id)
 def _handle_request(self, kwargs, write_result=True):
     """
     Proxies requests incoming on /api/plugins/rcc/proxy/rogerthat/{backend_id} to the appropriate rogerthat server
     This uses the url set on the BackendServer model with the id from the url
     Args:
         kwargs (dict): url parameters
         write_result (boolean): Whether or not to return the result instead of writing it
     """
     try:
         backend_server = get_backend_server(kwargs['backend_id'])
         url = '%s/%s' % (backend_server.proxy_url, urllib.quote(kwargs['route']))
         return _do_proxy(url, self.request, self.response, write_result=write_result)
     except HttpException as e:
         body = serialize_complex_value(ErrorResponse(e), ErrorResponse, False)
         self.response.set_status(httplib.NOT_FOUND)
         self.response.headers['Content-Type'] = 'application/json-rpc'
         self.response.out.write(json.dumps(body))
Example #53
0
def send_signup_update_messages(sln_settings, *messages):
    service_identity = ServiceIdentity.DEFAULT
    sln_i_settings = get_solution_settings_or_identity_settings(
        sln_settings, service_identity)

    sm_data = [{u'type': u'solutions.common.customer.signup.update'}]
    for message in messages:
        message_to = SolutionInboxMessageTO.fromModel(message, sln_settings,
                                                      sln_i_settings, True)
        sm_data.append({
            u'type':
            u'solutions.common.messaging.update',
            u'message':
            serialize_complex_value(message_to, SolutionInboxMessageTO, False)
        })

    channel.send_message(sln_settings.service_user,
                         sm_data,
                         service_identity=service_identity)
def update_chat(api_key, parent_message_key, topic=None, description=None, flags=None, metadata=None, avatar=None,
                background_color=None, text_color=None, json_rpc_id=None):
    method = 'messaging.update_chat'
    params = {'parent_message_key': parent_message_key}
    if topic:
        params['topic'] = topic
    if description:
        params['description'] = description
    if flags:
        params['flags'] = flags
    if metadata:
        params['metadata'] = serialize_complex_value(metadata, KeyValueTO, True, skip_missing=True)
    if avatar:
        params['avatar'] = avatar
    if background_color:
        params['background_color'] = background_color
    if text_color:
        params['text_color'] = text_color

    return call_rogerthat(api_key, method, params, json_rpc_id)
Example #55
0
def flow_member_result(rt_settings, request_id, message_flow_run_id, member,
                       steps, end_id, end_message_flow_id, parent_message_key,
                       tag, result_key, flush_id, flush_message_flow_id,
                       service_identity, user_details, flow_params, **kwargs):
    user_details = log_and_parse_user_details(user_details)
    steps = parse_complex_value(object_factory("step_type", FLOW_STEP_MAPPING),
                                steps, True)

    f = FMR_TAG_MAPPING.get(parse_to_human_readable_tag(tag))
    if not f:
        logging.info('[tff] Ignoring flow_member_result with tag %s', tag)
        return None

    result = f(message_flow_run_id, member, steps, end_id, end_message_flow_id,
               parent_message_key, tag, result_key, flush_id,
               flush_message_flow_id, service_identity, user_details,
               flow_params)

    return result and serialize_complex_value(
        result, FlowMemberResultCallbackResultTO, False, skip_missing=True)
Example #56
0
def reply_sandwich_order(service_user, service_identity, sandwich_id, message=unicode):
    from solutions.common.bizz.messaging import send_inbox_forwarders_message

    sln_settings = get_solution_settings(service_user)
    sandwich_order = SandwichOrder.get_by_order_id(service_user, service_identity, sln_settings.solution, sandwich_id)
    azzert(service_user == sandwich_order.service_user)
    sandwich_order.status = SandwichOrder.STATUS_REPLIED
    sandwich_order.put()

    sm_data = []
    sm_data.append({u"type": u"solutions.common.sandwich.orders.update"})

    if sandwich_order.solution_inbox_message_key:
        sim_parent, _ = add_solution_inbox_message(service_user, sandwich_order.solution_inbox_message_key, True, None, now(), message, mark_as_unread=False, mark_as_read=True)
        send_inbox_forwarders_message(service_user, sim_parent.service_identity, None, message, {
                    'if_name': sim_parent.sender.name,
                    'if_email':sim_parent.sender.email
                }, message_key=sim_parent.solution_inbox_message_key, reply_enabled=sim_parent.reply_enabled)
        sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, sandwich_order.service_identity)
        sm_data.append({u"type": u"solutions.common.messaging.update",
                     u"message": serialize_complex_value(SolutionInboxMessageTO.fromModel(sim_parent, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False)})
    else:
        sln_main_branding = get_solution_main_branding(service_user)
        branding = sln_main_branding.branding_key if sln_main_branding else None

        member = MemberTO()
        member.alert_flags = Message.ALERT_FLAG_VIBRATE
        member.member = sandwich_order.sender.email
        member.app_id = sandwich_order.sender.app_id

        messaging.send(parent_key=None,
                       parent_message_key=None,
                       message=message,
                       answers=[],
                       flags=Message.FLAG_ALLOW_DISMISS,
                       members=[member],
                       branding=branding,
                       tag=None,
                       service_identity=sandwich_order.service_identity)

    send_message(service_user, sm_data, service_identity=sandwich_order.service_identity)
Example #57
0
def flow_member_result(rt_settings, request_id, message_flow_run_id, member, steps, end_id, end_message_flow_id,
                       parent_message_key, tag, result_key, flush_id, flush_message_flow_id, service_identity,
                       user_details, flow_params, timestamp, **kwargs):
    user_details = log_and_parse_user_details(user_details)
    steps = parse_complex_value(object_factory("step_type", FLOW_STEP_MAPPING), steps, True)

    f = FMR_TAG_MAPPING.get(parse_to_human_readable_tag(tag))
    should_process_flush = f and not flush_id.startswith('flush_monitoring')

    result = None
    try:
        if should_process_flush:
            logging.info('Processing flow_member_result with tag %s and flush_id %s', tag, flush_id)
            result = f(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag,
                       result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params)
            return result and serialize_complex_value(result, FlowMemberResultCallbackResultTO, False,
                                                      skip_missing=True)
        else:
            logging.info('[tff] Ignoring flow_member_result with tag %s and flush_id %s', tag, flush_id)
    finally:
        deferred.defer(save_flow_statistics, parent_message_key, steps, end_id, tag, flush_id, flush_message_flow_id,
                       user_details[0], timestamp, result)
def get_permissions(permission_type, data):
    base_organization = _get_base_organization(data, permission_type)
    permissions = []
    for role in SCOPE_ROLES[permission_type]:
        organization = '%s.%s' % (base_organization, role)
        users = get_organization_users(organization, permission_type)
        invited_users = get_organization_invited_users(organization)
        permissions.extend([PermissionTO(invite.identifier, role, invite.created) for invite in invited_users])
        permissions.extend([PermissionTO(username, role) for username in users])

    if permission_type == PermissionType.BACKEND:
        edit_scopes = Scopes.BACKEND_ADMIN
    elif permission_type == PermissionType.APP:
        edit_scopes = Scopes.APP_ADMIN
    elif permission_type == PermissionType.DEVELOPER_ACCOUNT:
        edit_scopes = Scopes.DEV_ACC_ADMIN
    elif permission_type == PermissionType.APP_PERM:
        edit_scopes = Scopes.APPS_ADMIN
    else:
        raise ValueError('Unknown permission type: %s' % permission_type)
    edit_permission = has_at_least_one_scope(edit_scopes, serialize_complex_value(data, PermissionRequestDataTO, False))
    return edit_permission, permissions
Example #59
0
    def test_mix_type_property(self):
        class MyLittleTO(object):
            name = unicode_property('name')
            age = long_property('age')

            def __str__(self):
                return u"%s is %s years old" % (self.name, self.age)

            def __eq__(self, other):
                return self.name == other.name and self.age == other.age

        class MyPetTO(object):
            person = typed_property('person', (unicode, MyLittleTO))
            crew = typed_property('crew', (unicode, MyLittleTO), True)

        felix = MyPetTO()
        felix.person = u"nice"
        felix.crew = [u"bart", u"donatello"]

        ceaser = MyPetTO()
        ceaser.person = MyLittleTO()
        ceaser.person.name = u"ceaser"
        ceaser.person.age = 35
        ceaser.crew = [u"bart", MyLittleTO()]
        ceaser.crew[1].name = u"donatello"
        ceaser.crew[1].age = 34

        for person in ceaser.crew:
            print person

        serialized = serialize_complex_value(ceaser, MyPetTO, False)
        print serialized
        ceaser2 = parse_complex_value(MyPetTO, serialized, False)
        self.assertEquals(ceaser.person.name, ceaser2.person.name)
        self.assertEquals(ceaser.person.age, ceaser2.person.age)
        self.assertEquals(ceaser.crew[0], ceaser2.crew[0])
        self.assertEquals(ceaser.crew[1], ceaser2.crew[1])
Example #60
0
def solution_event_guests(service_user, email, method, params, tag,
                          service_identity, user_details):
    sln_settings = get_solution_settings(service_user)
    app_user = create_app_user_by_email(email, user_details[0].app_id)

    jsondata = json.loads(params)
    event_id = long(jsondata['eventId'])
    include_details = int(jsondata['includeDetails'])

    event = get_event_by_id(service_user, sln_settings.solution, event_id)
    r = SendApiCallCallbackResultTO()
    if event:
        your_status = None
        eg = db.get(EventGuest.createKey(app_user, event.key()))
        if eg:
            your_status = eg.status

        guests = []
        if include_details == 1:
            for guest in event.guests:
                guests.append(EventGuestTO.fromEventGuest(guest))

        r.result = json.dumps(
            dict(
                event_id=event_id,
                include_details=include_details,
                guests_count_going=event.guests_count(EventGuest.STATUS_GOING),
                guests_count_maybe=event.guests_count(EventGuest.STATUS_MAYBE),
                guests_count_not_going=event.guests_count(
                    EventGuest.STATUS_NOT_GOING),
                guests=serialize_complex_value(guests, EventGuestTO, True),
                your_status=your_status)).decode('utf8')
        r.error = None
    else:
        r.result = None
        r.error = u"Event not found"
    return r