def migrate_anonymous_account(anonymous_account, new_app_user):
    anonymous_mobile = get_mobile_by_account(anonymous_account)
    bizz_check(anonymous_mobile, 'No mobile found for this anonymous account: %s' % anonymous_account)

    anonymous_user = anonymous_mobile.user
    anonymous_friend_map, new_friend_map, anonymous_user_profile = db.get([get_friends_map_key_by_user(anonymous_user),
                                                                           get_friends_map_key_by_user(new_app_user),
                                                                           get_user_profile_key(anonymous_user)])
    bizz_check(anonymous_user_profile, 'No UserProfile found for %s', anonymous_user.email())

    if anonymous_friend_map:
        for friend_detail in anonymous_friend_map.friendDetails:
            if new_friend_map is None or friend_detail.email not in new_friend_map.friendDetails:
                logging.debug('Connecting %s to %s (%s)', new_app_user.email(), friend_detail.name, friend_detail.email)
                friend_user = users.User(friend_detail.email)
                user_data_str = None
                if friend_detail.hasUserData:
                    friend_user = add_slash_default(friend_user)
                    user_data_key = UserData.createKey(anonymous_user, friend_user)
                    user_data_str = json.dumps(db.get(user_data_key).userData.to_json_dict())

                makeFriends(new_app_user, friend_user, friend_user, None, notify_invitee=False, notify_invitor=False,
                            origin=ORIGIN_USER_INVITE, user_data=user_data_str)

    deferred.defer(archiveUserDataAfterDisconnect, anonymous_user, anonymous_friend_map, anonymous_user_profile, False)
示例#2
0
def re_index_question(question_key):
    question_index = search.Index(name=QUESTION_INDEX)

    # cleanup any previous index entry
    try:
        question_index.delete([str(question_key)])
    except ValueError:
        pass  # no index found for this customer yet

    # re-add index
    question = Question.get(question_key)
    bizz_check(question)

    fields = [search.AtomField(name='question_key', value=str(question_key)),
              search.TextField(name='question_language', value=question.language),
              search.TextField(name='question_title', value=question.title),
              search.TextField(name='question_description', value=question.description),
              search.TextField(name='question_tags', value=" ".join(question.modules)),
              ]

    for qr in question.replies(False):
        question_reply_id = qr.id
        fields.extend([search.TextField(name='question_reply_description_%s' % question_reply_id, value=qr.description),
                       ])

    question_index.put(search.Document(doc_id=str(question_key), fields=fields))
def _send_broadcast_to_test_persons(broadcast):
    testers_to_find = list(broadcast.test_persons)
    si_mapped_to_testers = dict()
    for si in ServiceIdentity.all().ancestor(parent_key(broadcast.service_user)).run():
        keys = [FriendServiceIdentityConnection.createKey(u, si.user) for u in testers_to_find]
        for fsic in db.get(keys):
            if fsic and not fsic.deleted:
                if not si in si_mapped_to_testers:
                    si_mapped_to_testers[si] = list()
                si_mapped_to_testers[si].append(fsic.friend)
                testers_to_find.remove(fsic.friend)
            if not testers_to_find:
                break
        if not testers_to_find:
            break
    bizz_check(not testers_to_find,
               u"Could not find a connected service identity for %s" % [x.email() for x in testers_to_find])
    mfd = MessageFlowDesign.get(broadcast.message_flow)

    # Make sure all end modules are connected with a flush
    new_xml = _check_flow_end_modules(mfd)
    if new_xml:
        mfd = CustomMessageFlowDesign()
        mfd.xml = new_xml

    for si, testers in si_mapped_to_testers.iteritems():
        deferred.defer(start_flow, si.user, message_parent_key=None, flow=mfd, members=testers,
                       check_friends=False, result_callback=False,
                       tag=json.dumps({Broadcast.TAG_MC_BROADCAST: unicode(broadcast.key()),
                                       '%s.tag' % MC_RESERVED_TAG_PREFIX: broadcast.tag}),
                       _transactional=db.is_in_transaction(), broadcast_type=broadcast.type_)
    def trans():
        service_profile = get_service_profile(service_user, False)
        bizz_check(broadcast_type not in service_profile.broadcastTypes,
                   u"Duplicate broadcast type: %s" % broadcast_type)

        service_profile.broadcastTypes.append(broadcast_type)
        set_broadcast_types(service_user, service_profile.broadcastTypes)
示例#5
0
    def trans():
        job = db.get(job_key)

        bizz_check(job, "Job with key %s not found!" % job_key)
        if phase is not None:
            bizz_check(job.phase == phase,
                       "Expected job %s to be in phase %s, but the phase was %s" % (job_key, phase, job.phase))
        return job
def _validate_app_broadcast(service_identity_user, app_ids, message):
    si = get_service_identity(service_identity_user)
    azzert(si)
    for app_id in app_ids:
        azzert(app_id in si.appIds)

    bizz_check(message and message.strip(), 'Message should not be empty')
    return si
 def trans():
     service_profile = get_service_profile(service_user, False)
     user_profile = get_user_profile(test_user, False)
     bizz_check(user_profile, u"No user found with e-mail '%s'" % test_user.email())
     bizz_check(not test_user in service_profile.broadcastTestPersons,
                u"Duplicate test person: %s" % test_user.email())
     service_profile.broadcastTestPersons.append(test_user)
     service_profile.put()
     return user_profile
 def trans():
     broadcast = Broadcast.get(broadcast_key)
     bizz_check(broadcast, u"Broadcast not found")
     azzert(broadcast.service_user == service_user)
     broadcast.scheduled_at = timestamp
     deferred.defer(send_broadcast, service_user, broadcast_key,
                    _transactional=True, _countdown=timestamp - now(), _queue=SCHEDULED_QUEUE)
     broadcast.put()
     return broadcast
def _validate_broadcast_types(all_translations):
    # Translated broadcast types should not contain duplicates
    if ServiceTranslation.BROADCAST_TYPE in all_translations:
        broadcast_types = dict()
        for translations in all_translations[ServiceTranslation.BROADCAST_TYPE].itervalues():
            if translations:
                for lang, translation in translations.iteritems():
                    if lang in broadcast_types:
                        bizz_check(translation not in broadcast_types[lang],
                                   "Duplicate translated broadcast types are not allowed.\n(%s: %s)" % (lang, translation))
                    else:
                        broadcast_types[lang] = list()
                    broadcast_types[lang].append(translation)
 def trans():
     look_and_feel = None
     user_profile = get_user_profile(user, False)
     bizz_check(user_profile, 'User %s does not exist' % user.email())
     for role_id in role_ids:
         user_profile.grant_role(service_identity_user, role_id)
     if not user_profile.look_and_feel_id:
         look_n_feel = get_look_and_feel_for_user(user_profile)
         if look_n_feel:
             user_profile.look_and_feel_id = look_n_feel.id
             look_and_feel = look_n_feel
     user_profile.put()
     return look_and_feel
示例#11
0
    def post(self):
        settings_yaml = self.request.get("settings", "")

        try:
            settings = populate_model_by_yaml(get_server_settings(), settings_yaml)
            # validate jabberEndPoints
            for jabber_endpoint in settings.jabberEndPoints:
                parts = jabber_endpoint.split(":")
                bizz_check(len(parts) == 2, 'Invalid jabber endpoint: %s' % jabber_endpoint)
                ip = [int(p) for p in parts[0].split('.')]
                bizz_check(len(ip) == 4, 'Invalid jabber endpoint IP: %s' % ip)

            # validate srvEndPoints
            for srv_record in settings.srvEndPoints:
                parts = srv_record.split(":")
                bizz_check(len(parts) == 3, 'Invalid SRV record: %s' % srv_record)
                ip = [int(p) for p in parts[0].split('.')]
                bizz_check(len(ip) == 4, "Invalid IP '%s' in SRV record: %s" % (ip, srv_record))

            # sort srvEndPoints by priority
            settings.srvEndPoints = sorted(settings.srvEndPoints, key=lambda x: x.split(':')[2])

            if settings.dkimPrivateKey:
                # dkimPrivateKey dos2unix
                settings.dkimPrivateKey = settings.dkimPrivateKey.replace("\r", "")

            settings.put()

            result = "Settings saved successfully!"
        except Exception, e:
            if not isinstance(e, BusinessException):
                logging.exception('Error happened while updating setting')
            result = 'ERROR: %s' % e.message
示例#12
0
def populate_model_by_yaml(model, stream):
    d = yaml.load(stream)
    bizz_check(d, "Empty yaml")
    missing_properties = [propname for propname in model.properties() if propname not in d]
    if missing_properties:
        from rogerthat.rpc.service import BusinessException
        raise BusinessException("Missing properties: %s" % ", ".join(missing_properties))

    for propname, propobject in model.properties().iteritems():
        value = d[propname]
        if value is not None and isinstance(propobject, db.StringProperty):
            value = str(value)
        setattr(model, propname, value)
    return model
示例#13
0
def schedule_broadcast(service_user, broadcast_key, timestamp):

    bizz_check(timestamp > now(), u"Cannot schedule broadcasts in the past.")

    def trans():
        broadcast = Broadcast.get(broadcast_key)
        bizz_check(broadcast, u"Broadcast not found")
        azzert(broadcast.service_user == service_user)
        broadcast.scheduled_at = timestamp
        deferred.defer(send_broadcast, service_user, broadcast_key,
                       _transactional=True, _countdown=timestamp - now(), _queue=SCHEDULED_QUEUE)
        broadcast.put()
        return broadcast

    return db.run_in_transaction(trans)
def test_send_app_broadcast(service_identity_user, app_ids, message, identifier, tester):
    si = _validate_app_broadcast(service_identity_user, app_ids, message)
    tag = _get_tag(identifier)
    app_users = []
    user_profile_keys = []
    for app_id in app_ids:
        app_user = create_app_user_by_email(tester, app_id)
        user_profile_key = get_profile_key(app_user)
        app_users.append(app_user)
        user_profile_keys.append(user_profile_key)
    user_profiles = db.get(user_profile_keys)
    for user_profile, app_user in zip(user_profiles, app_users):
        bizz_check(user_profile and isinstance(user_profile, UserProfile), 'User %s not found' % app_user.email())

    for user_profile in user_profiles:
        _send_app_broadcast_to_user(user_profile, si.user, message, tag, is_test=True)
    return tag
示例#15
0
 def trans():
     service_profile = get_service_profile(service_user, False)
     mfd = MessageFlowDesign.get(message_flow_id)
     bizz_check(mfd, u"Selected message flow design not found")
     bizz_check(broadcast_type in service_profile.broadcastTypes, u"Unknown broadcast type: %s" % broadcast_type)
     azzert(service_profile.broadcastTestPersons)
     broadcast = Broadcast.create(service_user)
     broadcast.name = name
     broadcast.tag = tag
     broadcast.type_ = broadcast_type
     broadcast.creation_time = now()
     broadcast.message_flow = str(mfd.key())
     broadcast.test_persons = service_profile.broadcastTestPersons
     broadcast.test_persons_statuses = [Broadcast.TEST_PERSON_STATUS_UNDECIDED] * len(broadcast.test_persons)
     broadcast.put()
     _send_broadcast_to_test_persons(broadcast)
     return broadcast
示例#16
0
def userScanned(request):
    from rogerthat.rpc import users
    app_id = users.get_current_app_id()
    app_user = create_app_user(users.User(request.email), request.app_id)
    service_identity_user = add_slash_default(users.User(request.service_email))

    if app_id == request.app_id:
        should_make_friends = True
    else:
        si = get_service_identity(service_identity_user)
        bizz_check(si, "ServiceIdentity %s not found" % service_identity_user)
        should_make_friends = request.app_id in si.appIds

    if should_make_friends:
        try_or_defer(makeFriends, app_user, service_identity_user, original_invitee=None, servicetag=None, origin=None,
                     notify_invitee=False, notify_invitor=False, user_data=None)

    return UserScannedResponseTO()
示例#17
0
def list_friends(service_identity=None, cursor=None, app_id=None, batch_count=100):
    from rogerthat.bizz.service import get_and_validate_service_identity_user, valididate_app_id_for_service_identity_user
    from rogerthat.dal.service import get_users_connected_to_service_identity

    bizz_check(batch_count <= 1000, "Cannot batch more than 1000 friends at once.")

    service_identity_user = get_and_validate_service_identity_user(users.get_current_user(), service_identity)
    if app_id:
        valididate_app_id_for_service_identity_user(service_identity_user, app_id)
    if cursor:
        try:
            cursor = decrypt(service_identity_user, cursor)
        except:
            from rogerthat.bizz.exceptions import InvalidCursorException
            raise InvalidCursorException()
    fsics, cursor = get_users_connected_to_service_identity(service_identity_user, cursor, batch_count, app_id)
    # prevent extra roundtrip by trying to detect whether there are more results to fetch
    if len(fsics) < batch_count and cursor:
        extra_fsics, _ = get_users_connected_to_service_identity(service_identity_user, cursor, 1, app_id)
        if len(extra_fsics) == 0:
            cursor = None
    result = FriendListResultTO()
    result.cursor = unicode(encrypt(service_identity_user, cursor)) if cursor else None
    result.friends = list()

    user_profiles = get_profile_infos([fsic.friend for fsic in fsics], expected_types=[UserProfile] * len(fsics))
    app_names = {}
    for user_profile, fsic in zip(user_profiles, fsics):
        svc_friend = ServiceFriendTO()
        human_user, svc_friend.app_id = get_app_user_tuple(fsic.friend)
        svc_friend.avatar = u"%s/unauthenticated/mobi/cached/avatar/%s" % (get_server_settings().baseUrl, fsic.friend_avatarId)
        svc_friend.email = human_user.email()
        svc_friend.language = user_profile.language
        svc_friend.name = fsic.friend_name
        if svc_friend.app_id not in app_names:
            app = get_app_by_id(svc_friend.app_id)
            app_names[svc_friend.app_id] = app.name

        svc_friend.app_name = app_names[svc_friend.app_id]
        result.friends.append(svc_friend)
    return result
def remove_regio_manager(manager_email):
    logging.info('Removing regional manager %s', manager_email)
    bizz_check(
        manager_email != STORE_MANAGER,
        'Deleting the <Customer shop> regional manager is not allowed.')
    task_list = ShopTask.group_by_assignees([manager_email])
    task_count = len(task_list[manager_email])
    bizz_check(
        task_count == 0,
        'There are still %s tasks assigned to this regional manager' %
        task_count)

    def trans():
        manager_key = RegioManager.create_key(manager_email)
        manager = RegioManager.get(manager_key)
        if not manager.team_id:
            raise BusinessException(
                'Cannot delete regional manager that has no team.')
        team = manager.team
        if not team.support_manager:
            raise BusinessException(
                'Cannot delete regional manager: Team \'%s\' has no support manager'
                % team.name)
        if team.support_manager == manager_email:
            raise BusinessException(
                'You cannot delete the support manager of a team.'
                ' Assign this role to a different regional manager first.')
        team.regio_managers.remove(manager_email)
        db.delete(
            [manager_key,
             RegioManagerStatistic.create_key(manager_email)])
        team.put()
        return team

    team = run_in_transaction(trans, xg=True)
    deferred.defer(_unassign_prospects, manager_email)
    deferred.defer(_change_charges_manager, manager_email,
                   team.support_manager)
    deferred.defer(_change_orders_manager, manager_email, team.support_manager)
    deferred.defer(_change_customers_manager, manager_email)
示例#19
0
def save_menu_name(service_user, name):
    name = name.strip()
    bizz_check(name, "Name can not be empty")

    def trans():
        sln_settings = get_solution_settings(service_user)
        sln_settings.updates_pending = True

        menu = get_restaurant_menu(service_user, sln_settings.solution)
        menu.name = name

        put_and_invalidate_cache(sln_settings, menu)

        return sln_settings

    xg_on = db.create_transaction_options(xg=True)
    sln_settings = db.run_in_transaction_options(xg_on, trans)

    channel.send_message(sln_settings.service_user,
                         'solutions.common.menu.name_updated',
                         name=name)
    broadcast_updates_pending(sln_settings)
示例#20
0
def migrate_and_create_user_profile(executor_user, from_service_user, to_user):
    from shop.models import Customer
    bizz_check(from_service_user.email() != to_user.email(), 'FROM and TO should not be equal')

    from_profile = _get_profile_not_cached(from_service_user)
    bizz_check(from_profile, 'ServiceProfile %s not found' % from_service_user)
    bizz_check(isinstance(from_profile, ServiceProfile),
               'Profile %s is not of expected type ServiceProfile, but of type %s' % (from_service_user, from_profile.kind()))

    service_email = u"*****@*****.**" % uuid.uuid4()

    to_profile = _get_profile_not_cached(to_user)
    if to_profile:
        bizz_check(isinstance(to_profile, UserProfile),
                   'Profile %s is not of expected type UserProfile, but of type %s' % (to_user, to_profile.kind()))
        if service_email not in to_profile.owningServiceEmails:
            to_profile.owningServiceEmails.append(service_email)
    else:
        to_profile = create_user_profile(to_user, to_user.email(), from_profile.defaultLanguage)
        to_profile.isCreatedForService = True
        to_profile.owningServiceEmails = [service_email]
        update_password_hash(to_profile, from_profile.passwordHash, now())

    si = get_default_service_identity_not_cached(from_service_user)
    si.qualifiedIdentifier = to_user.email()
    settings = get_solution_settings(from_service_user)
    settings.qualified_identifier = to_user.email()
    settings.login = to_user
    put_and_invalidate_cache(to_profile, si, settings)

    customer = Customer.all().filter('service_email', from_service_user.email()).get()
    if customer:
        def trans(customer_key):
            customer = db.get(customer_key)
            customer.user_email = to_user.email()
            customer.put()
        db.run_in_transaction(trans, customer.key())

        if SolutionModule.CITY_APP in settings.modules:
            for app_id in customer.app_ids:
                invalidate_service_user_for_city(app_id)
    else:
        logging.debug('There was no customer')

    return migrate(executor_user, from_service_user, users.User(service_email))
示例#21
0
 def trans():
     broadcast = Broadcast.get(broadcast_key)
     bizz_check(broadcast, u"Broadcast not found")
     azzert(broadcast.service_user == service_user)
     service_profile = get_service_profile(service_user, False)
     mfd = MessageFlowDesign.get(broadcast.message_flow)
     bizz_check(mfd, u"Broadcast message flow not found")
     bizz_check(broadcast.type_ in service_profile.broadcastTypes, u"Unknown broadcast type: %s" % broadcast.type_)
     tag = broadcast.tag or broadcast.name
     broadcast_guid = schedule_service_broadcast(service_user, broadcast.message_flow, broadcast.type_, tag)
     stats = BroadcastStatistic(key=BroadcastStatistic.create_key(broadcast_guid, service_user),
                                timestamp=now(),
                                tag=tag)
     broadcast.broadcast_guid = broadcast_guid
     broadcast.sent_time = now()
     db.put([broadcast, stats])
     on_trans_committed(send_message, service_user, "rogerthat.broadcast.changes")
     return broadcast
示例#22
0
def _validate_job(from_service_user, to_service_user):
    # FROM != TO
    bizz_check(from_service_user.email() != to_service_user.email(),
               'FROM and TO should not be equal')

    # FROM should exist and be a ServiceProfile
    from_service_profile = _get_profile_not_cached(from_service_user)
    bizz_check(from_service_profile,
               'ServiceProfile %s not found' % from_service_user)
    bizz_check(isinstance(from_service_profile, ServiceProfile),
               'Profile %s is not of expected type ServiceProfile, but of type %s' % (from_service_user,
                                                                                      from_service_profile.kind()))

    # TO should not exist
    to_profile = _get_profile_not_cached(to_service_user)
    if to_profile:
        raise BusinessException('%s %s already exists' % (to_profile.kind(), to_service_user))

    # FROM should not be an auto_connected_service in an App
    for app in App.all():
        if from_service_user.email() in app.admin_services:
            raise BusinessException('FROM should not be an app admin service (found in app %s)' % app.app_id)

        for acs in app.auto_connected_services:
            acs_si_user = users.User(acs.service_identity_email)
            if get_service_user_from_service_identity_user(acs_si_user).email() == from_service_user.email():
                raise BusinessException('FROM should not be an AutoConnectedService (found %s in app %s)'
                                        % (acs_si_user, app.app_id))

    # Validate that there are no running jobs for <from_service> or <to_service>
    def get_base_query():
        return MigrateServiceJob.all().filter('phase !=', MigrateServiceJob.PHASE_DONE)

    for service_user in (from_service_user, to_service_user):
        for prop in ('from_service_user', 'to_service_user'):
            job = get_base_query().filter(prop, service_user).get()
            if job:
                raise BusinessException('There already is a MigrateServiceJob with %s=%s\n%s'
                                        % (prop, service_user, db.to_dict(job)))

    return from_service_profile
示例#23
0
def rest_loyalty_scanned(user_email_hash, merchant_email, app_id):
    try:
        bizz_check(user_email_hash is not MISSING,
                   'user_email_hash is required')
        bizz_check(merchant_email is not MISSING, 'merchant_email is required')
        bizz_check(app_id is not MISSING, 'app_id is required')

        user_code = user_code_by_hash(binascii.unhexlify(user_email_hash))
        profile_pointer = ProfilePointer.get(user_code)
        if not profile_pointer:
            logging.debug('No ProfilePointer found with user_code %s',
                          user_code)
            raise BusinessException('User not found')
        app_user = profile_pointer.user

        bizz_check(get_app_by_id(app_id), 'App not found')
        bizz_check(app_id == get_app_id_from_app_user(profile_pointer.user),
                   'Invalid user email hash')

        merchant_found = False
        for customer in Customer.list_by_user_email(merchant_email):
            merchant_found = True
            service_user = users.User(customer.service_email)
            logging.info('Received loyalty scan of %s by %s (%s)', app_user,
                         service_user, customer.user_email)
            makeFriends(service_user,
                        app_user,
                        None,
                        None,
                        ORIGIN_USER_INVITE,
                        notify_invitee=False,
                        notify_invitor=False,
                        allow_unsupported_apps=True)

        bizz_check(merchant_found, 'Merchant not found')
    except BusinessException as e:
        return ReturnStatusTO.create(False, e.message)
    else:
        return RETURNSTATUS_TO_SUCCESS
示例#24
0
    def post(self):
        success = False
        app_id = self.request.POST.get("app_id_hidden", None)
        name = self.request.POST.get("name", None)
        app_type = self.request.POST.get("app_type", None)
        fb_app_id = self.request.POST.get("fb_app_id", None)
        ios_app_id = self.request.POST.get("ios_app_id", None)
        android_app_id = self.request.POST.get("android_app_id", None)
        dashboard_email_address = self.request.POST.get("dashboard_email_address", None)
        contact_email_address = self.request.POST.get("contact_email_address", None)
        user_regex = self.request.POST.get("user_regex", None)
        qr_templates_count = int(self.request.POST.get("qr_templates_count", 0))
        default_qr_template_index = int(self.request.POST.get("default_qr_template_index", 0))
        has_core_branding = self.request.POST.get("has_core_branding", None)
        auto_connected_services_string = self.request.POST.get("auto_connected_services", "[]")
        logging.debug("auto_connected_services = %s", auto_connected_services_string)
        auto_connected_services = parse_complex_value(AutoConnectedService,
                                                      json.loads(auto_connected_services_string),
                                                      True)
        admin_services = json.loads(self.request.POST.get('admin_services', '[]'))
        qr_templates_to_delete = json.loads(self.request.POST.get("qr_templates_to_delete", "[]"))
        beacon_regions = json.loads(self.request.POST.get("beacon_regions", "[]"))
        beacon_major_str = self.request.POST.get("beacon_major", 0)
        beacon_major = int(beacon_major_str) if beacon_major_str else 0
        demo = bool(self.request.POST.get("demo", ''))
        beta = bool(self.request.POST.get("beta", ''))
        mdp_client_id = self.request.POST.get('mdp_client_id', None)
        mdp_client_secret = self.request.POST.get('mdp_client_secret', None)

        try:
            has_core_branding = None if not has_core_branding else int(has_core_branding)
        except Exception:
            has_core_branding = None

        try:
            app_type = None if not app_type else int(app_type)
        except Exception:
            app_type = None

        try:
            fb_app_id = None if not fb_app_id else int(fb_app_id)
        except Exception:
            fb_app_id = None

        if not app_id:
            result = "BUG!!! Failed to update app (app_id was empty)!"
        if not name:
            result = "Failed to update app (name was empty)!"
        elif app_type is None:
            result = "Failed to update app (app_type was empty)!"
        elif not ios_app_id:
            result = "Failed to update app (ios_app_id was empty)!"
        elif not android_app_id:
            result = "Failed to update app (android_app_id was empty)!"
        elif not dashboard_email_address:
            result = "Failed to update app (dashboard_email_address was empty)!"
        else:
            app = get_app_by_id(app_id)
            if app:
                try:
                    if user_regex:
                        validate_user_regex(user_regex)

                    to_be_put = [app]
                    app.name = name
                    app.type = app_type

                    if has_core_branding:
                        zip_stream = self.request.POST.get('core_branding').file
                        zip_stream.seek(0)
                        try:
                            zip_ = ZipFile(zip_stream)
                        except BadZipfile, e:
                            raise BrandingValidationException(e.message)

                        branding = store_branding_zip(None, zip_, u"Core branding of %s" % app_id)
                        app.core_branding_hash = branding.hash

                    for qr_template_key_name in qr_templates_to_delete:
                        app.qrtemplate_keys.remove(qr_template_key_name)

                    for i in xrange(qr_templates_count):
                        description = self.request.POST.get("qr_template_description_%s" % i)
                        key_name = create_qr_template_key_name(app_id, description)
                        if self.request.POST.get('qr_template_new_%s' % i) == "1":
                            file_ = self.request.POST.get('qr_template_%s' % i)
                            color = self.request.POST.get("qr_template_color_%s" % i)
                            file_ = file_.file.getvalue() if isinstance(file_, FieldStorage) else None
                            store_template(None, file_, description, color, key_name)
                            if default_qr_template_index == i:
                                app.qrtemplate_keys.insert(0, key_name)
                            else:
                                app.qrtemplate_keys.append(key_name)
                        else:
                            if default_qr_template_index == i:
                                app.qrtemplate_keys.remove(key_name)
                                app.qrtemplate_keys.insert(0, key_name)

                    app.facebook_app_id = fb_app_id
                    app.ios_app_id = ios_app_id
                    app.android_app_id = android_app_id
                    app.dashboard_email_address = dashboard_email_address
                    app.contact_email_address = contact_email_address
                    app.user_regex = user_regex
                    app.demo = demo
                    app.beta = beta
                    app.mdp_client_id = mdp_client_id or None
                    app.mdp_client_secret = mdp_client_secret or None

                    old_auto_connected_services = {acs.service_identity_email for acs in app.auto_connected_services}

                    app.auto_connected_services = AutoConnectedServices()
                    for acs in auto_connected_services:
                        service_identity_user = add_slash_default(users.User(acs.service_identity_email))
                        si = get_service_identity(service_identity_user)
                        bizz_check(si, "ServiceIdentity %s not found" % service_identity_user)
                        if app_id not in si.appIds:
                            si.appIds.append(app_id)
                            to_be_put.append(si)

                        acs.service_identity_email = service_identity_user.email()
                        app.auto_connected_services.add(acs)

                    admin_profiles = db.get([get_profile_key(u) for u in map(users.User, admin_services)])
                    non_existing = list()
                    for admin_email, admin_profile in zip(admin_services, admin_profiles):
                        if not admin_profile:
                            non_existing.append(admin_email)
                    bizz_check(not non_existing, "Non existing services specified: %s" % non_existing)
                    app.admin_services = admin_services

                    old_beacon_regions = list(app.beacon_regions(keys_only=True))
                    new_beacon_regions = list()

                    should_update_beacon_regions = False

                    for beacon_region in beacon_regions:
                        uuid = beacon_region.get("uuid")
                        major = beacon_region.get("major")
                        minor = beacon_region.get("minor")
                        br_key = BeaconRegion.create_key(app.key(), uuid, major, minor)
                        new_beacon_regions.append(br_key)
                        if br_key not in old_beacon_regions:
                            should_update_beacon_regions = True
                            br = BeaconRegion(key=br_key)
                            br.uuid = uuid.lower()
                            br.major = major
                            br.minor = minor
                            br.creation_time = now()
                            to_be_put.append(br)

                    to_be_deleted = []
                    for beacon_region_key in old_beacon_regions:
                        if beacon_region_key not in new_beacon_regions:
                            should_update_beacon_regions = True
                            to_be_deleted.append(beacon_region_key)

                    app.beacon_major = beacon_major
                    app.beacon_last_minor = app.beacon_last_minor if app.beacon_last_minor else 0

                    put_and_invalidate_cache(*to_be_put)
                    if to_be_deleted:
                        db.delete(db.get(to_be_deleted))

                    for acs in app.auto_connected_services:
                        if acs.service_identity_email not in old_auto_connected_services:
                            logging.info("There is a new auto-connected service: %s", acs.service_identity_email)
                            run_job(get_user_profile_keys_by_app_id, [app_id],
                                    hookup_with_default_services.run_for_auto_connected_service, [acs, None])

                    if should_update_beacon_regions:
                        schedule_update_beacon_regions_for_all_users(app_id)

                    result = "Updated app!"
                    success = True
                except BusinessException, e:
                    logging.info("BusinessException: %s", e, exc_info=1)
                    result = e.message
                except Exception, e:
                    logging.exception(str(e), exc_info=1)
                    result = "Unknown error has occurred."
示例#25
0
def migrate(executor_user,
            from_user,
            to_user,
            service_email,
            customer_id=None):
    logging.info('Migrating %s to %s for customer %s', from_user.email(),
                 to_user.email(), customer_id)

    bizz_check(from_user.email() != to_user.email(),
               'FROM and TO should not be equal')

    def trans():
        from_profile = _get_profile_not_cached(from_user)
        if from_profile:
            bizz_check(
                isinstance(from_profile, UserProfile),
                'Profile %s is not of expected type UserProfile, but of type %s'
                % (from_user, from_profile.kind()))
        else:
            logging.warn('UserProfile for %s not found! Weird...',
                         from_user.email())

        to_put = set()
        to_profile = _get_profile_not_cached(to_user)
        if to_profile:
            bizz_check(
                isinstance(to_profile, UserProfile),
                'Profile %s is not of expected type UserProfile, but of type %s'
                % (to_user, to_profile.kind()))

            if service_email not in to_profile.owningServiceEmails:
                to_profile.owningServiceEmails.append(service_email)
            to_put.add(to_profile)
        else:
            if from_profile:
                language = from_profile.language
                password_hash = from_profile.passwordHash
            else:
                service_profile = get_service_profile(
                    users.User(service_email))
                language = service_profile.defaultLanguage
                password_hash = service_profile.passwordHash
            to_profile = create_user_profile(to_user, to_user.email(),
                                             language)
            to_profile.isCreatedForService = True
            to_profile.owningServiceEmails = [service_email]
            update_password_hash(to_profile, password_hash, now())

        if from_profile:
            if service_email in from_profile.owningServiceEmails:
                from_profile.owningServiceEmails.remove(service_email)
                to_put.add(from_profile)

            if not from_profile.owningServiceEmails:

                @db.non_transactional
                def has_mobiles():
                    return bool(
                        list(get_user_active_mobiles(from_profile.user)))

                if has_mobiles():
                    from_profile.isCreatedForService = False
                    to_put.add(from_profile)
                else:
                    delete_account(from_user)

        si = get_default_service_identity_not_cached(users.User(service_email))
        si.qualifiedIdentifier = to_user.email()
        to_put.add(si)
        sln_settings = get_solution_settings(users.User(service_email))
        sln_settings.login = to_user
        sln_settings.qualified_identifier = to_user.email()
        to_put.add(sln_settings)

        if customer_id is not None:
            customer = Customer.get_by_id(customer_id)
            customer.user_email = to_user.email()
            to_put.add(customer)

        put_and_invalidate_cache(*to_put)

    allow_transaction_propagation(run_in_xg_transaction, trans)

    channel.send_message(from_user, u'rogerthat.system.dologout')
    def post(self):
        from rogerthat.pages.shortner import get_short_url_by_code
        from rogerthat.service.api import friends as service_api_friends

        version = self.request.get("version", None)
        install_id = self.request.get("install_id", None)
        registration_time = self.request.get("registration_time", None)
        device_id = self.request.get("device_id", None)
        registration_id = self.request.get("registration_id", None)
        qr_url = self.request.get("qr_url", None)
        signature = self.request.get("signature", None)
        language = self.request.get("language", None)
        country = self.request.get("country", None)
        app_id = self.request.get("app_id", App.APP_ID_ROGERTHAT)
        use_xmpp_kick_channel = self.request.get('use_xmpp_kick', 'true') == 'true'
        GCM_registration_id = self.request.get('GCM_registration_id', '')

        if '-' in language:
            language = get_iso_lang(language.lower())
        elif language and country:
            language = '%s_%s' % (language, country)

        server_settings = get_server_settings()

        calculated_signature = sha256_hex(version + " " + install_id + " " + registration_time + " " + device_id + " " + \
                                       registration_id + " " + qr_url + base64.b64decode(server_settings.registrationMainSignature.encode("utf8")))

        try:
            if signature.upper() != calculated_signature.upper():
                logging.error("Invalid request signature.")
                self.response.set_status(500)
                return

            app = _verify_app_id(app_id)
            azzert(app is not None, "app_id is not found")
            bizz_check(install_id and qr_url, u"Could not validate QR code")

            installation = Installation.get_by_key_name(install_id)
            if not installation:
                platform = self.request.get("platform", None)
                if platform == "android":
                    mobile_type = Mobile.TYPE_ANDROID_HTTP
                elif platform == "iphone":
                    if use_xmpp_kick_channel:
                        mobile_type = Mobile.TYPE_IPHONE_HTTP_XMPP_KICK
                    else:
                        mobile_type = Mobile.TYPE_IPHONE_HTTP_APNS_KICK
                elif platform == "windows_phone":
                    mobile_type = Mobile.TYPE_WINDOWS_PHONE
                else:
                    logging.error("Unknown platform: %s" % platform)
                    self.response.set_status(500)
                    return

                now_ = now()
                installation = Installation(key_name=install_id, version=version, platform=mobile_type, timestamp=now_, app_id=app_id)
                installation_log = InstallationLog(parent=installation, timestamp=now_,
                                              description="Installed with language %s" % language)
                installation_log_app_id = InstallationLog(parent=installation, timestamp=now_,
                                                  description="Installed with app_id: %s" % app_id)
                put_and_invalidate_cache(installation, installation_log, installation_log_app_id)

            InstallationLog(parent=installation, timestamp=now(),
                            description="Creating qr based profile & validating registration request. Language: %s, QR url: %s" % (language, qr_url)).put()

            m = re.match('(.*)/(M|S)/(.*)', qr_url)
            bizz_check(m, u"Could not validate QR code")
            entry_point = m.group(2)
            code = m.group(3)

            bizz_check(entry_point == "S", u"Could not validate QR code")

            su = get_short_url_by_code(code)
            bizz_check(su, u"Could not validate QR code")

            logging.debug("register_via_qr qr_url: %s", qr_url)
            logging.debug("register_via_qr su.full: %s", su.full)

            match = re.match("^/q/s/(.+)/(\\d+)$", su.full)
            bizz_check(match, u"Could not validate QR code")

            user_code = match.group(1)
            service_profile = get_service_profile_via_user_code(user_code)
            bizz_check(service_profile, u"Could not validate QR code")

            service_user = service_profile.user

            sid = int(match.group(2))
            service_interaction_def = get_service_interaction_def(service_user, int(sid))
            service_identity_user = create_service_identity_user(service_user, service_interaction_def.service_identity)
            service_identity = get_identity_from_service_identity_user(service_identity_user)
            svc_profile = get_service_profile(service_user)

            logging.debug("register_via_qr service_identity_user: %s", service_identity_user)

            human_user = users.User(u"*****@*****.**" % uuid.uuid4().get_hex())
            app_user = create_app_user(human_user, app_id)
            from rogerthat.bizz.profile import _create_new_avatar
            avatar, _ = _create_new_avatar(app_user, add_trial_overlay=False)
            user_profile = UserProfile(parent=parent_key(app_user), key_name=app_user.email())
            user_profile.name = None
            user_profile.language = language
            user_profile.avatarId = avatar.key().id()
            user_profile.app_id = get_app_id_from_app_user(app_user)
            user_details = [UserDetailsTO.fromUserProfile(user_profile)]
            r = service_api_friends.register(None, None, svc_profile,
                                             service_identity=service_identity,
                                             user_details=user_details,
                                             origin=REGISTRATION_ORIGIN_QR,
                                             PERFORM_CALLBACK_SYNCHRONOUS=True)

            logging.debug("register_via_qr with id: %s", r)
            bizz_check(r == ACCEPT_ID or r == ACCEPT_AND_CONNECT_ID, u"Service denied your install")

            installation.service_identity_user = service_identity_user
            installation.service_callback_result = r
            installation.qr_url = su.full[4:]
            installation.put()

            # Create registration entry.
            self.response.headers['Content-Type'] = 'text/json'
            registration = Registration(parent=parent_key(app_user), key_name=registration_id)
            registration.timestamp = int(registration_time)
            registration.device_id = device_id
            registration.pin = -1
            registration.timesleft = -1
            registration.installation = installation
            registration.language = language
            registration.put()
            account, registration.mobile, age_and_gender_set = register_mobile(human_user, app_id=app_id,
                                                                               use_xmpp_kick_channel=use_xmpp_kick_channel,
                                                                               GCM_registration_id=GCM_registration_id,
                                                                               language=registration.language)
            installation_log = InstallationLog(parent=installation, timestamp=now(), profile=get_user_profile(app_user), \
                                               description="Profile created & registration request validated.", \
                                               registration=registration, mobile=registration.mobile)
            db.put([registration, installation_log])
            self.response.out.write(json.dumps(dict(account=account.to_dict(), email=human_user.email(), age_and_gender_set=age_and_gender_set)))
        except BusinessException, be:
            logging.debug("BusinessException during via QR handler %s", be)
            self.response.set_status(500)
            return
示例#27
0
    def trans():
        from_profile = _get_profile_not_cached(from_user)
        if from_profile:
            bizz_check(
                isinstance(from_profile, UserProfile),
                'Profile %s is not of expected type UserProfile, but of type %s'
                % (from_user, from_profile.kind()))
        else:
            logging.warn('UserProfile for %s not found! Weird...',
                         from_user.email())

        to_put = set()
        to_profile = _get_profile_not_cached(to_user)
        if to_profile:
            bizz_check(
                isinstance(to_profile, UserProfile),
                'Profile %s is not of expected type UserProfile, but of type %s'
                % (to_user, to_profile.kind()))

            if service_email not in to_profile.owningServiceEmails:
                to_profile.owningServiceEmails.append(service_email)
            to_put.add(to_profile)
        else:
            if from_profile:
                language = from_profile.language
                password_hash = from_profile.passwordHash
            else:
                service_profile = get_service_profile(
                    users.User(service_email))
                language = service_profile.defaultLanguage
                password_hash = service_profile.passwordHash
            to_profile = create_user_profile(to_user, to_user.email(),
                                             language)
            to_profile.isCreatedForService = True
            to_profile.owningServiceEmails = [service_email]
            update_password_hash(to_profile, password_hash, now())

        if from_profile:
            if service_email in from_profile.owningServiceEmails:
                from_profile.owningServiceEmails.remove(service_email)
                to_put.add(from_profile)

            if not from_profile.owningServiceEmails:

                @db.non_transactional
                def has_mobiles():
                    return bool(
                        list(get_user_active_mobiles(from_profile.user)))

                if has_mobiles():
                    from_profile.isCreatedForService = False
                    to_put.add(from_profile)
                else:
                    delete_account(from_user)

        si = get_default_service_identity_not_cached(users.User(service_email))
        si.qualifiedIdentifier = to_user.email()
        to_put.add(si)
        sln_settings = get_solution_settings(users.User(service_email))
        sln_settings.login = to_user
        sln_settings.qualified_identifier = to_user.email()
        to_put.add(sln_settings)

        if customer_id is not None:
            customer = Customer.get_by_id(customer_id)
            customer.user_email = to_user.email()
            to_put.add(customer)

        put_and_invalidate_cache(*to_put)
 def trans_update_app_id():
     si = get_service_identity(service_identity_user)
     bizz_check(si, "ServiceIdentity %s not found" % service_identity_user)
     if user_app_id not in si.appIds:
         si.appIds.append(user_app_id)
         put_and_invalidate_cache(si)
示例#29
0
    def post(self):
        success = False
        app_id = self.request.POST.get("app_id", None)
        name = self.request.POST.get("name", None)
        app_type = self.request.POST.get("app_type", None)
        fb_app_id = self.request.POST.get("fb_app_id", None)
        ios_app_id = self.request.POST.get("ios_app_id", None)
        android_app_id = self.request.POST.get("android_app_id", None)
        dashboard_email_address = self.request.POST.get('dashboard_email_address', None)
        contact_email_address = self.request.POST.get("contact_email_address", None)
        user_regex = self.request.POST.get("user_regex", None)
        qr_templates_count = int(self.request.POST.get("qr_templates_count", 0))
        default_qr_template_index = int(self.request.POST.get("default_qr_template_index", 0))
        auto_connected_services_string = self.request.POST.get("auto_connected_services", "[]")
        logging.debug("auto_connected_services = %s", auto_connected_services_string)
        beacon_major_str = self.request.POST.get("beacon_major", 0)
        beacon_major = int(beacon_major_str) if beacon_major_str else 0
        demo = bool(self.request.POST.get("demo", ''))
        beta = bool(self.request.POST.get("beta", ''))
        mdp_client_id = self.request.POST.get('mdp_client_id', None)
        mdp_client_secret = self.request.POST.get('mdp_client_secret', None)
        orderable_apps = self.request.get_all('orderable_apps')
        auto_connected_services = parse_complex_value(AutoConnectedService,
                                                      json.loads(auto_connected_services_string),
                                                      True)
        admin_services = json.loads(self.request.POST.get('admin_services', '[]'))
        beacon_regions = json.loads(self.request.POST.get("beacon_regions", "[]"))

        try:
            app_type = None if not app_type else int(app_type)
        except Exception:
            app_type = None

        try:
            fb_app_id = None if not fb_app_id else int(fb_app_id)
        except Exception:
            fb_app_id = None

        if not app_id:
            result = "Failed to create new app (app_id was empty)!"
        elif [c for c in app_id if c not in '-abcdefghijklmnopqrstuvwxyz0123456789']:
            result = "App ids should only contain (-, lower case alphabet characters and numbers)"
        elif not name:
            result = "Failed to create new app (name was empty)!"
        elif app_type is None:
            result = "Failed to create new app (app_type was empty)!"
        elif not ios_app_id:
            result = "Failed to create new app (ios_app_id was empty)!"
        elif not android_app_id:
            result = "Failed to create new app (android_app_id was empty)!"
        elif not dashboard_email_address:
            result = "Failed to create new app (dashboard_email_address was empty)!"
        else:
            try:
                if user_regex:
                    validate_user_regex(user_regex)

                zip_stream = self.request.POST.get('core_branding').file
                zip_stream.seek(0)
                try:
                    zip_ = ZipFile(zip_stream)
                except BadZipfile, e:
                    raise BrandingValidationException(e.message)

                branding = store_branding_zip(None, zip_, u"Core branding of %s" % app_id)

                app = App(key=App.create_key(app_id))
                to_be_put = []
                app.qrtemplate_keys = []
                for i in xrange(qr_templates_count):
                    file_ = self.request.POST.get('qr_template_%s' % i)
                    description = self.request.POST.get("qr_template_description_%s" % i)
                    color = self.request.POST.get("qr_template_color_%s" % i)
                    file_ = file_.file.getvalue() if isinstance(file_, FieldStorage) else None
                    key_name = create_qr_template_key_name(app_id, description)
                    store_template(None, file_, description, color, key_name)
                    if default_qr_template_index == i:
                        app.qrtemplate_keys.insert(0, key_name)
                    else:
                        app.qrtemplate_keys.append(key_name)

                app.name = name
                app.type = app_type
                app.core_branding_hash = branding.hash
                app.facebook_app_id = fb_app_id
                app.ios_app_id = ios_app_id
                app.android_app_id = android_app_id
                app.dashboard_email_address = dashboard_email_address
                app.contact_email_address = contact_email_address
                app.user_regex = user_regex
                app.creation_time = now()
                app.is_default = get_default_app_key() is None
                app.demo = demo
                app.beta = beta
                app.mdp_client_id = mdp_client_id or None
                app.mdp_client_secret = mdp_client_secret or None

                app.auto_connected_services = AutoConnectedServices()
                for acs in auto_connected_services:
                    service_identity_user = add_slash_default(users.User(acs.service_identity_email))
                    si = get_service_identity(service_identity_user)
                    bizz_check(si, "ServiceIdentity %s not found" % service_identity_user)
                    if app_id not in si.appIds:
                        si.appIds.append(app_id)
                        to_be_put.append(si)

                    acs.service_identity_email = service_identity_user.email()
                    app.auto_connected_services.add(acs)

                admin_profiles = db.get([get_profile_key(u) for u in map(users.User, admin_services)])
                non_existing = list()
                for admin_email, admin_profile in zip(admin_services, admin_profiles):
                    if not admin_profile:
                        non_existing.append(admin_email)
                bizz_check(not non_existing, "Non existing services specified: %s" % non_existing)
                app.admin_services = admin_services
                app.beacon_major = beacon_major
                app.beacon_last_minor = 0
                put_and_invalidate_cache(*to_be_put)

                to_be_put = []
                for beacon_region in beacon_regions:
                    uuid = beacon_region.get("uuid")
                    major = beacon_region.get("major")
                    minor = beacon_region.get("minor")
                    br = BeaconRegion(key=BeaconRegion.create_key(app.key(), uuid, major, minor))
                    br.uuid = uuid.lower()
                    br.major = major
                    br.minor = minor
                    br.creation_time = now()
                    to_be_put.append(br)

                app.orderable_app_ids = list(orderable_apps)
                apps = db.get(map(App.create_key, app.orderable_app_ids))
                for a in apps:
                    a.orderable_app_ids.append(app_id)
                    to_be_put.append(a)
                to_be_put.append(app)
                put_and_invalidate_cache(*to_be_put)

                for acs in app.auto_connected_services:
                    logging.info("There is a new auto-connected service: %s", acs.service_identity_email)
                    run_job(get_user_profile_keys_by_app_id, [app_id],
                            hookup_with_default_services.run_for_auto_connected_service, [acs, None])

                result = "Created new app!"
                success = True
            except BusinessException, e:
                logging.info("BusinessException: %s", e, exc_info=1)
                result = e.message
示例#30
0
def _create_message_flow_run_xml_doc(service_identity_user, message_flow_design, message_flow_run_record, members,
                                     force_language):
    service_user = get_service_user_from_service_identity_user(service_identity_user)

    if not message_flow_design.xml:
        # Must regenerate xml
        subflowdict = get_message_flow_design_context(message_flow_design)
        translator = get_translator(service_user, ServiceTranslation.MFLOW_TYPES)
        definition_doc = parseString(message_flow_design_to_xml(
            service_user, message_flow_design, translator, subflowdict)[0].encode('utf-8'))
        message_flow_design.xml = definition_doc.toxml('utf-8')
        message_flow_design.put()
        logging.warning("Message flow design with empty xml property discovered!!!\nkey = %s" %
                        message_flow_design.key())
    else:
        definition_doc = parseString(message_flow_design.xml.encode('utf-8'))

    run = MessageFlowRunSub(launchTimestamp=message_flow_run_record.creationtime)
    si = get_service_identity(service_identity_user)
    run.set_serviceName(si.name)
    run.set_serviceDisplayEmail(si.qualifiedIdentifier or si.user.email())
    run.set_serviceEmail(si.user.email())
    run.set_flowParams(message_flow_run_record.flow_params)
    if si.serviceData:
        run.set_serviceData(json.dumps(si.serviceData.to_json_dict()))
    else:
        run.set_serviceData(si.appData)
    fallback_language = force_language or get_service_profile(service_user).defaultLanguage

    mf_languages = list()
    if definition_doc.documentElement.localName == 'messageFlowDefinitionSet':
        for definition_element in definition_doc.documentElement.childNodes:
            if definition_element.localName == 'definition':
                mf_languages.append(definition_element.getAttribute('language'))
    elif definition_doc.documentElement.localName == 'definition':
        mf_languages.append(fallback_language)
    else:
        azzert(False, "Unexpected tag name: %s" % definition_doc.documentElement.localName)

    # if force_language supplied, check if it's in mf_languages
    if force_language:
        bizz_check(force_language in mf_languages, "Can not run in %s." % get_full_language_string(force_language))

    userprofiles = get_profile_infos(members, expected_types=[UserProfile] * len(members))
    user_datas = db.get([UserData.createKey(member, service_identity_user) for member in members])
    for i, p in enumerate(userprofiles):
        member_run_language = force_language or (p.language if p.language in mf_languages else fallback_language)
        human_user, app_id = get_app_user_tuple(p.user)

        if user_datas[i]:
            if user_datas[i].userData:
                user_data = json.dumps(user_datas[i].userData.to_json_dict())
            else:
                user_data = user_datas[i].data
        else:
            user_data = None
        run.add_memberRun(MemberRunSub(status="SUBMITTED", email=human_user.email(), name=p.name,
                                       language=member_run_language, appId=app_id, avatarUrl=p.avatarUrl, userData=user_data))

    xml = StringIO()
    xml.write("""<?xml version="1.0" encoding="utf-8"?>\n""")
    run.export(xml, 0, namespaceprefix_='', namespacedef_='xmlns="https://rogerth.at/api/1/MessageFlow.xsd"',
               name_='messageFlowRun')
    xml.reset()
    xml_doc = parse(xml)
    for member_run_child_node in xml_doc.documentElement.childNodes:
        if member_run_child_node.localName == "memberRun":
            break
    else:
        azzert(False, "No child nodes of type 'memberRun' found for xml:\n%s" % xml)

    # put memberRun in xml
    if definition_doc.documentElement.localName == 'messageFlowDefinitionSet':
        for definition_element in definition_doc.documentElement.childNodes:
            if definition_element.localName == 'definition':
                xml_doc.documentElement.insertBefore(definition_element, member_run_child_node)
    elif definition_doc.documentElement.localName == 'definition':
        xml_doc.documentElement.insertBefore(definition_doc.documentElement, member_run_child_node)
    else:
        azzert(False, "Unexpected tag name: %s" % definition_doc.documentElement.localName)

    return xml_doc
示例#31
0
def _replace_subscription_order(order_key, products,
                                paying_subscription_product_codes):
    customer, old_order = db.get([order_key.parent(), order_key])

    if not is_signup_enabled(customer.app_id):
        logging.debug(
            'FREE_SUBSCRIPTIONS - Signup is not enabled for customer %s with app %s',
            customer.name, customer.app_id)
        return

    if customer.service_disabled_at != 0:
        logging.debug('FREE_SUBSCRIPTIONS - Customer %s is disabled',
                      customer.name)
        return

    if old_order.status == Order.STATUS_SIGNED:
        order_items = list(OrderItem.all().ancestor(old_order))
        ordered_product_codes = {i.product_code for i in order_items}
        if not ordered_product_codes.intersection(
                paying_subscription_product_codes):
            logging.debug(
                'FREE_SUBSCRIPTIONS - Customer %s already had a FREE subscription: %s',
                customer.name, list(ordered_product_codes))
            return

        logging.debug(
            'FREE_SUBSCRIPTIONS - Creating new FREE order for customer %s',
            customer.name)
        new_order_items = []
        for old_order_item in OrderItem.list_by_order(order_key):
            product = products[old_order_item.product_code]
            if product.is_subscription_extension:
                new_order_items.append(OrderItemTO.create(old_order_item))
        if new_order_items:
            logging.debug(
                'FREE_SUBSCRIPTIONS - Adding %s old order items: %s',
                len(new_order_items),
                serialize_complex_value(new_order_items, OrderItemTO, True))

        free_item = OrderItemTO()
        free_item.comment = products[
            Product.PRODUCT_FREE_SUBSCRIPTION].default_comment(
                customer.language)

        next_charge_date_time = datetime.datetime.utcfromtimestamp(
            old_order.next_charge_date)
        language = 'nl' if customer.language == 'nl' else 'en'
        next_charge_date = format_date(next_charge_date_time, locale=language)
        if language == 'nl':
            free_item.comment += u'\n\nEr zijn geen abonnementskosten meer! Uw abonnement is omgezet naar een gratis abonnement.'
            if new_order_items:
                free_item.comment += u'\n\nUw uitbreiding voor extra stad/steden is mee overgezet naar het nieuwe abonnement en zal, zoals bij het oude abonnement, op %s aangerekend worden.' % next_charge_date
        else:
            free_item.comment = u'There are no more subscription costs! Your subscription is changed to a free subscription'
            if new_order_items:
                free_item.comment += u'\n\nThe extension for extra cities is also transferred to the new subscription and will be charged at %s, just like you old subscription.' % next_charge_date

        free_item.count = 1
        free_item.id = None
        free_item.number = 0
        free_item.price = 0
        free_item.product = Product.PRODUCT_FREE_SUBSCRIPTION
        free_item.service_visible_in = None
        new_order_items.append(free_item)

        new_order = create_order(customer,
                                 old_order.contact_id,
                                 new_order_items,
                                 replace=True,
                                 regio_manager_user=old_order.manager)
        new_order.next_charge_date = old_order.next_charge_date
        new_order.put()
    else:
        bizz_check(
            customer.subscription_order_number != old_order.order_number,
            'Something is seriously wrong with customer %s (%s)!' %
            (customer.id, customer.name))
        new_order = Order.get_by_order_number(
            customer.id, customer.subscription_order_number)

    if new_order.status == Order.STATUS_UNSIGNED and new_order.total_amount > 0:
        logging.debug('FREE_SUBSCRIPTIONS - Signing order %s for customer %s',
                      new_order.order_number, customer.name)
        sign_order(customer.id,
                   new_order.order_number,
                   signature=u'',
                   no_charge=True)
def finish_registration(mobile_account, mobileInfo, accounts, invitor_code, invitor_secret, ipaddress):
    from rogerthat.service.api import friends as service_api_friends
    m = get_mobile_by_account(mobile_account)
    mobile_key = m.key()
    ms_key = MobileSettings.get(m).key()
    profile_key = get_user_profile_key(m.user)

    def trans():
        mobile, ms, my_profile = db.get((mobile_key, ms_key, profile_key))

        mobile.status = mobile.status | Mobile.STATUS_REGISTERED
        mobile.type = mobileInfo.app_type
        mobile.simCountry = mobileInfo.sim_country if mobileInfo.sim_country != MISSING else None
        mobile.simCountryCode = mobileInfo.sim_country_code if mobileInfo.sim_country_code != MISSING else None
        mobile.simCarrierCode = mobileInfo.sim_carrier_code if mobileInfo.sim_carrier_code != MISSING else None
        mobile.simCarrierName = mobileInfo.sim_carrier_name if mobileInfo.sim_carrier_name != MISSING else None
        mobile.netCountry = mobileInfo.net_country if mobileInfo.net_country != MISSING else None
        mobile.netCountryCode = mobileInfo.net_country_code if mobileInfo.net_country_code != MISSING else None
        mobile.netCarrierCode = mobileInfo.net_carrier_code if mobileInfo.net_carrier_code != MISSING else None
        mobile.netCarrierName = mobileInfo.net_carrier_name if mobileInfo.net_carrier_name != MISSING else None
        mobile.hardwareModel = mobileInfo.device_model_name
        mobile.osVersion = mobileInfo.device_os_version if mobileInfo.device_os_version != MISSING else None
        mobile.localeLanguage = mobileInfo.locale_language if mobileInfo.locale_language and mobileInfo.locale_language != MISSING else DEFAULT_LANGUAGE
        mobile.localeCountry = mobileInfo.locale_country
        mobile.timezone = mobileInfo.timezone if mobileInfo.timezone != MISSING else None
        mobile.timezoneDeltaGMT = mobileInfo.timezone_delta_gmt if mobileInfo.timezone_delta_gmt != MISSING else None

        if mobileInfo.app_major_version != MISSING and mobileInfo.app_minor_version != MISSING:
            ms.majorVersion = mobileInfo.app_major_version
            ms.minorVersion = mobileInfo.app_minor_version

        # This is the official place where we set the profile language
        my_profile.language = mobile.localeLanguage
        my_profile.country = mobile.netCountry or mobile.simCountry or mobile.localeCountry
        my_profile.timezone = mobile.timezone
        my_profile.timezoneDeltaGMT = mobile.timezoneDeltaGMT

        my_profile.mobiles = MobileDetails()
        my_profile.mobiles.addNew(mobile.account, mobile.type, mobile.pushId, mobile.app_id)

        mobile.put()
        ms.put()
        my_profile.put()

        deferred.defer(_finishup_mobile_registration, mobile, accounts, invitor_code, invitor_secret, ipaddress,
                       ms_key, _transactional=True)

        return mobile, my_profile

    xg_on = db.create_transaction_options(xg=True)
    mobile, my_profile = db.run_in_transaction_options(xg_on, trans)
    channel.send_message(mobile.user, u'com.mobicage.registration.finished')
    typestr = "Unknown type"
    try:
        typestr = Mobile.typeAsString(mobile.type)
    except ValueError:
        pass

    server_settings = get_server_settings()
    registration = get_registration_by_mobile(mobile)
    if registration:
        InstallationLog(parent=registration.installation, timestamp=now(), registration=registration,
                        mobile=mobile, profile=my_profile, description="Registration successful.").put()

        if registration.installation and registration.installation.qr_url:
            service_user = get_service_user_from_service_identity_user(registration.installation.service_identity_user)
            service_identity = get_identity_from_service_identity_user(registration.installation.service_identity_user)
            svc_profile = get_service_profile(service_user)
            user_details = [UserDetailsTO.fromUserProfile(my_profile)]

            if registration.installation.service_callback_result == ACCEPT_AND_CONNECT_ID:
                service_identity_user = create_service_identity_user(service_user, service_identity)
                si = get_service_identity(service_identity_user)
                bizz_check(si, "ServiceIdentity %s not found" % service_identity_user)
                xmpp.send_message(server_settings.xmppInfoMembers,
                                  "User %s registered %s (%s) with account:\n%s\nFor service %s %s" % (
                                  mobile.user, mobile.hardwareModel, typestr, mobile.account, si.name,
                                  service_identity_user), message_type=xmpp.MESSAGE_TYPE_CHAT)
                app_id = get_app_id_from_app_user(mobile.user)
                if app_id not in si.appIds:
                    si.appIds.append(app_id)
                    put_and_invalidate_cache(si)
                try_or_defer(makeFriends, mobile.user, service_identity_user, original_invitee=None, servicetag=None,
                             origin=None, notify_invitee=False, notify_invitor=False, user_data=None)
            else:
                xmpp.send_message(server_settings.xmppInfoMembers, "User %s registered %s (%s) with account:\n%s" % (
                mobile.user, mobile.hardwareModel, typestr, mobile.account), message_type=xmpp.MESSAGE_TYPE_CHAT)

            service_api_friends.register_result(register_result_response_receiver, logServiceError, svc_profile,
                                                service_identity=service_identity,
                                                user_details=user_details,
                                                origin=REGISTRATION_ORIGIN_QR)
        else:
            xmpp.send_message(server_settings.xmppInfoMembers, "User %s registered %s (%s) with account:\n%s" % (
            mobile.user, mobile.hardwareModel, typestr, mobile.account), message_type=xmpp.MESSAGE_TYPE_CHAT)
            app = get_app_by_id(get_app_id_from_app_user(mobile.user))
            if app.admin_services:
                service_profiles = filter(None, db.get((get_profile_key(users.User(e)) for e in app.admin_services)))
                if service_profiles:
                    user_details = [UserDetailsTO.fromUserProfile(my_profile)]
                    for service_profile in service_profiles:
                        service_api_friends.register_result(register_result_response_receiver,
                                                            logServiceError,
                                                            service_profile,
                                                            service_identity=ServiceIdentity.DEFAULT,
                                                            user_details=user_details,
                                                            origin=REGISTRATION_ORIGIN_DEFAULT)
    else:
        xmpp.send_message(server_settings.xmppInfoMembers,
                          "User %s registered %s (%s) with account:\n%s\nBut registration model was not found!" % (
                          mobile.user, mobile.hardwareModel, typestr, mobile.account),
                          message_type=xmpp.MESSAGE_TYPE_CHAT)

    return mobile
示例#33
0
    def trans():
        service_profile = get_service_profile(service_user, False)
        bizz_check(service_profile,
                   "Service %s does not exist" % service_user.email())
        bizz_check(
            not service_profile.solution
            or service_profile.solution == solution,
            u"Cannot change solution from %s to %s" %
            (service_profile.solution, solution))
        service_profile.solution = solution

        default_si = None
        if apps is not None:
            azzert(apps)
            default_si = get_default_service_identity(service_user)
            default_si.appIds = apps
            default_si.defaultAppId = apps[0]
            default_si.put()

        if organization_type is not None:
            service_profile.organizationType = organization_type

        solution_settings = get_solution_settings(service_user)
        solution_settings_changed = False
        if not solution_settings:
            default_si = default_si or get_default_service_identity(
                service_user)
            solution_settings = SolutionSettings(
                key=SolutionSettings.create_key(service_user),
                name=default_si.name)
            solution_settings_changed = True

        if solution_settings.solution != solution:
            solution_settings.solution = solution
            solution_settings_changed = True

        if languages:
            service_profile.supportedLanguages = languages
            solution_settings.main_language = languages[0]
            solution_settings_changed = True

        if menu_item_color == u"branding":
            solution_settings.menu_item_color = None
            solution_settings_changed = True
        elif menu_item_color:
            try:
                parse_color(menu_item_color)
            except ValueError:
                raise InvalidMenuItemColorException()

            solution_settings.menu_item_color = menu_item_color
            solution_settings_changed = True

        if currency:
            solution_settings.currency = currency
            solution_settings_changed = True

        if modules is not None:
            solution_settings.modules = modules
            solution_settings_changed = True

        if broadcast_types is not None:
            solution_settings.broadcast_types = broadcast_types
            solution_settings_changed = True

        main_branding, branding_settings = db.get([
            SolutionMainBranding.create_key(service_user),
            SolutionBrandingSettings.create_key(service_user)
        ])
        if not main_branding:
            main_branding = SolutionMainBranding(
                key=SolutionMainBranding.create_key(service_user))
            if not branding_url:
                main_branding.put()
        if branding_url:
            main_branding.blob = db.Blob(resp.content)
            main_branding.branding_creation_time = 0
            main_branding.put()

        if not branding_settings:
            branding_settings = _get_default_branding_settings(service_user)
            branding_settings.put()

        if solution_settings.name != name and name is not None:
            solution_settings.name = name
            solution_settings_changed = True
        if solution_settings.address != address and address is not None:
            solution_settings.address = address
            solution_settings_changed = True
        if solution_settings.phone_number != phone_number and phone_number is not None:
            solution_settings.phone_number = phone_number
            solution_settings_changed = True
        if solution_settings.qualified_identifier != qualified_identifier and qualified_identifier is not None:
            solution_settings.qualified_identifier = qualified_identifier
            solution_settings_changed = True
        service_profile.put()
        if solution_settings_changed:
            solution_settings.put()
        return solution_settings
def list_news(cursor=None, batch_count=10, service_identity=None, updated_since=0, tag=None):
    bizz_check(batch_count <= 100, 'Cannot get more than 100 news items at once.')
    service_user = users.get_current_user()
    service_identity_user = get_and_validate_service_identity_user(service_user, service_identity)
    return news.get_news_by_service(cursor, batch_count, service_identity_user, updated_since, tag)
示例#35
0
 def trans():
     user_profile = get_user_profile(user, False)
     bizz_check(user_profile, "User %s does not exist" % user.email())
     user_profile.grant_role(service_identity_user, role)
     user_profile.put()