Example #1
0
        def trans():
            si_chunk = db.get(si_keys_chunk)
            for si in reversed(si_chunk):
                if not si.serviceData:
                    si_chunk.remove(si)
                    continue
                old_ancestor = si.serviceData._ancestor
                new_ancestor = _create_new_key(job, si.serviceData._ancestor)
                for chunk in chunks(si.serviceData._keys.values(), 5):
                    _migrate_models(job, db.get([KVBucket.create_key(bucket_id, old_ancestor)
                                                 for bucket_id in chunk]))
                for chunk in chunks(si.serviceData._blob_keys.values(), 5):
                    for blob_bucket_ids in chunk:
                        _migrate_models(job, db.get([KVBlobBucket.create_key(blob_bucket_id, old_ancestor)
                                                     for blob_bucket_id in blob_bucket_ids]))
                si.serviceData._ancestor = new_ancestor
            if si_chunk:
                put_and_invalidate_cache(*si_chunk)

            if si_keys:
                # there is still work to do
                deferred.defer(_2500_migrate_service_data, job_key, si_keys,
                               _transactional=True, _queue=MIGRATION_QUEUE)
                return False
            return True
    def trans():
        to_put = list()
        service_profile = get_service_profile(service_user)
        service_profile.expiredAt = now()
        service_profile.enabled = False
        to_put.append(service_profile)
        service_identity_keys = get_service_identities_query(service_user, True)
        search_configs = db.get(
                [SearchConfig.create_key(create_service_identity_user(users.User(key.parent().name()), key.name())) for
                 key in service_identity_keys])

        svc_index = search.Index(name=SERVICE_INDEX)
        loc_index = search.Index(name=SERVICE_LOCATION_INDEX)

        for search_config in search_configs:
            if search_config:
                search_config.enabled = False
                to_put.append(search_config)
                on_trans_committed(_cleanup_search_index, search_config.service_identity_user.email(), svc_index,
                                   loc_index)

        for objects_to_put in chunks(to_put, 200):
            put_and_invalidate_cache(*objects_to_put)

        deferred.defer(cleanup_sessions, service_user, _transactional=True)
        deferred.defer(cleanup_friend_connections, service_user, _transactional=True)
Example #3
0
        def trans(loyalty_type):
            sln_settings = get_solution_settings(service_user)
            if SolutionModule.HIDDEN_CITY_WIDE_LOTTERY in sln_settings.modules:
                loyalty_type = SolutionLoyaltySettings.LOYALTY_TYPE_CITY_WIDE_LOTTERY
            sln_settings.updates_pending = True

            sln_loyalty_settings = SolutionLoyaltySettings.get_by_user(service_user)

            if sln_loyalty_settings.loyalty_type != loyalty_type:
                sln_loyalty_settings.branding_key = None
                sln_settings.loyalty_branding_hash = None
                sln_loyalty_settings.loyalty_type = loyalty_type

            if sln_loyalty_settings.website != loyalty_website:
                sln_loyalty_settings.modification_time = now()

            sln_loyalty_settings.website = loyalty_website

            if loyalty_type == SolutionLoyaltySettings.LOYALTY_TYPE_REVENUE_DISCOUNT:
                sln_loyalty_settings.x_visits = loyalty_settings.x_visits
                sln_loyalty_settings.x_discount = loyalty_settings.x_discount
            elif loyalty_type == SolutionLoyaltySettings.LOYALTY_TYPE_STAMPS:
                sln_loyalty_settings.x_stamps = loyalty_settings.x_stamps
                sln_loyalty_settings.stamps_type = loyalty_settings.stamps_type
                sln_loyalty_settings.stamps_winnings = loyalty_settings.stamps_winnings
                sln_loyalty_settings.stamps_auto_redeem = loyalty_settings.stamps_auto_redeem

            put_and_invalidate_cache(sln_loyalty_settings, sln_settings)
            return sln_settings
Example #4
0
            def trans():
                if static_content_id:
                    sc = SolutionStaticContent.get(
                        SolutionStaticContent.create_key(
                            service_user, static_content_id))
                    if not sc:
                        logging.error(
                            u"Failed to update static content with id '%s' for user %s",
                            static_content_id, service_user)
                        return sln_settings

                    if sc.old_coords != coords and sc.provisioned:
                        sc.old_coords = sc.coords
                else:
                    sc = SolutionStaticContent(parent=parent_key(
                        sln_settings.service_user, SOLUTION_COMMON))
                    sc.old_coords = coords

                sc.icon_label = icon_label
                sc.icon_name = icon_name
                sc.text_color = None
                sc.background_color = None
                sc.html_content = None
                sc.sc_type = SolutionStaticContent.TYPE_PDF
                sc.visible = visible
                sc.coords = coords
                sc.provisioned = False
                sc.deleted = False
                if branding_hash:
                    sc.branding_hash = branding_hash

                sln_settings.updates_pending = True
                put_and_invalidate_cache(sc, sln_settings)
                return sln_settings
Example #5
0
    def trans():
        followed_new_group = False
        to_put = list()
        for discussion_group in SolutionDiscussionGroup.list(service_user):
            kv_store_dict = discussion_group.members.to_json_dict()
            was_following = app_user_email in kv_store_dict['members']
            now_following = discussion_group.id in selected_ids

            if was_following != now_following:
                if now_following:
                    followed_new_group = True
                    logging.debug('Adding %s to discussion group "%s"',
                                  app_user_email, discussion_group.topic)
                    kv_store_dict['members'].append(app_user_email)
                    on_trans_committed(add_to_chat,
                                       discussion_group.message_key)
                else:
                    logging.debug('Removing %s from discussion group "%s"',
                                  app_user_email, discussion_group.topic)
                    kv_store_dict['members'].remove(app_user_email)
                    on_trans_committed(rm_from_chat,
                                       discussion_group.message_key)
                to_put.append(discussion_group)
                # We need to set members again to force the KVStore to be put
                discussion_group.members.from_json_dict(kv_store_dict)
        if to_put:
            put_and_invalidate_cache(*to_put)
        return followed_new_group
Example #6
0
def edit_loyalty_lottery_info(key, winnings, date):
    ll_info_edit = SolutionLoyaltyLottery.get(key)
    if not ll_info_edit:
        return RETURNSTATUS_TO_SUCCESS

    service_user = users.get_current_user()
    session_ = users.get_current_session()
    service_identity = session_.service_identity
    sln_settings = get_solution_settings(service_user)

    try:
        now_ = now()
        end_timestamp = date.toEpoch()
        if end_timestamp <= (now_ + 24 * 3600):
            raise BusinessException("end-date-24h-in-future")

        ll_info = SolutionLoyaltyLottery.load_pending(service_user, service_identity)
        if ll_info_edit.key() != ll_info.key() and end_timestamp <= ll_info.end_timestamp:
            raise BusinessException("lottery-time-bigger-first-upcoming")

        ll_info_edit.end_timestamp = end_timestamp
        ll_info_edit.schedule_loot_time = ll_info_edit.end_timestamp - 24 * 3600
        ll_info_edit.winnings = winnings
        ll_info_edit.put()

        sln_settings.updates_pending = True
        put_and_invalidate_cache(sln_settings)
        broadcast_updates_pending(sln_settings)

        send_message(service_user, u"solutions.common.loyalty.lottery.update", service_identity=service_identity)

        return RETURNSTATUS_TO_SUCCESS
    except BusinessException, e:
        return ReturnStatusTO.create(False, common_translate(sln_settings.main_language, SOLUTION_COMMON, e.message))
Example #7
0
    def trans():
        if new_event.id:
            event = get_event_by_id(service_user, sln_settings.solution,
                                    new_event.id)
            if new_event.new_picture:
                event.picture_version += 1
        else:
            event = Event(
                parent=parent_key(service_user, sln_settings.solution))
            event.picture_version = 0

        event.title = new_event.title
        event.place = new_event.place
        event.organizer = new_event.organizer
        event.description = new_event.description
        start_dates = []
        for start_date in new_event.start_dates:
            start_dates.append(start_date.toEpoch())

        start_dates_sorted, end_dates_sorted = zip(
            *sorted(zip(start_dates, new_event.end_dates)))
        startDates = list(start_dates_sorted)
        new_event.end_dates = list(end_dates_sorted)

        event.last_start_date = max(startDates)
        event.start_dates = start_dates
        event.end_dates = new_event.end_dates
        event.first_start_date = event.get_first_event_date()
        event.url = new_event.external_link
        event.picture = picture
        event.calendar_id = new_event.calendar_id
        sln_settings.updates_pending = True
        put_and_invalidate_cache(event, sln_settings)
        return sln_settings
Example #8
0
def _migrate_sids(job, old_sids):
    @db.non_transactional
    def put_new_short_urls(new_sids):
        new_short_urls = [get_shorturl_for_qr(job.to_service_user, new_sid.key().id())[0]
                          for new_sid in new_sids]
        _put_and_invalidate_cache_and_allocate_ids(*new_short_urls)
        return new_short_urls

    @db.non_transactional
    def delete_old_short_urls(old_sids):
        old_short_url_keys = [db.Key.from_path(ShortURL.kind(),
                                               ServiceInteractionDef.shortUrl.get_value_for_datastore(qr).id())
                              for qr in old_sids]
        db.delete(old_short_url_keys)

    new_sids = _migrate_models(job, old_sids, delete_old_models=False, put_new_models=True)
    new_short_urls = put_new_short_urls(new_sids)

    for new_sid, new_short_url in zip(new_sids, new_short_urls):
        new_sid.shortUrl = new_short_url
        old_qr_template_key = ServiceInteractionDef.qrTemplate.get_value_for_datastore(new_sid)
        if old_qr_template_key:
            new_sid.qrTemplate = _create_new_key(job, old_qr_template_key)
    put_and_invalidate_cache(*new_sids)

    delete_old_short_urls(old_sids)
    db.delete(old_sids)
    return new_sids
Example #9
0
def enable_or_disable_solution_module(service_user, module, enabled):
    """Add or remove the module from solution settings"""
    if module not in SolutionModule.FUNCTIONALITY_MODUELS:
        return

    sln_settings = get_solution_settings(service_user)
    # for broadcast module, it can be enabled only
    if module == SolutionModule.BROADCAST:
        if enabled:
            set_default_broadcast_types(sln_settings)
        else:
            return

    to_put = []
    if enabled:
        activate_solution_module(sln_settings, module)
        if module == SolutionModule.ORDER:
            order_settings = set_advanced_order_settings(sln_settings)
            if order_settings:
                to_put.append(order_settings)
        elif module == SolutionModule.HIDDEN_CITY_WIDE_LOTTERY:
            deactivate_solution_module(sln_settings, SolutionModule.LOYALTY)
        # don't enable loyalty if this is a city service
        if module == SolutionModule.LOYALTY and SolutionModule.CITY_APP in sln_settings.modules:
            return
    else:
        deactivate_solution_module(sln_settings, module)

    sln_settings.updates_pending = True
    to_put.append(sln_settings)
    put_and_invalidate_cache(*to_put)
    broadcast_updates_pending(sln_settings)
Example #10
0
def try_to_set_location(settings_key):
    to_put = set()

    def set_location(settings):
        if settings.address and not settings.location:
            lines = settings.address.splitlines()
            if lines[0] == lines[1]:
                settings.address = '\n'.join(lines[1:])
                to_put.add(settings)
            try:
                lat, lon = _get_location(settings.address)
                settings.location = db.GeoPt(lat, lon)
                to_put.add(settings)
            except:
                logging.warning("Failed to resolve address of %s: %s",
                                settings.service_user.email(),
                                settings.address,
                                exc_info=1)

    sln_settings = db.get(settings_key)
    if sln_settings:
        if sln_settings.identities:
            for identity in sln_settings.identities:
                identity_settings = get_solution_settings_or_identity_settings(
                    sln_settings, identity)
                set_location(identity_settings)
        else:
            set_location(sln_settings)

        if to_put:
            put_and_invalidate_cache(*to_put)
            service_user = sln_settings.service_user
            main_branding_key = get_solution_main_branding(
                service_user).branding_key
            populate_identity_and_publish(service_user, main_branding_key)
Example #11
0
    def trans():
        sln_settings = get_solution_settings(service_user)
        new_coords = map(int, [
            static_content.position.x, static_content.position.y,
            static_content.position.z
        ])
        if static_content.id is MISSING or static_content.id is None:
            sc = SolutionStaticContent(parent=parent_key(
                service_user, SOLUTION_COMMON),
                                       deleted=False)
            sc.old_coords = new_coords
        else:
            sc = SolutionStaticContent.get(
                SolutionStaticContent.create_key(service_user,
                                                 static_content.id))
            if sc.old_coords != new_coords and sc.provisioned:
                sc.old_coords = sc.coords
        sc.icon_label = static_content.icon_label
        sc.icon_name = static_content.icon_name
        if static_content.sc_type == SolutionStaticContent.TYPE_OWN:
            sc.text_color = static_content.text_color
            sc.background_color = static_content.background_color
            sc.html_content = static_content.html_content
            sc.branding_hash = branding_hash
        elif static_content.sc_type == SolutionStaticContent.TYPE_WEBSITE:
            sc.website = static_content.website
        sc.sc_type = static_content.sc_type
        sc.visible = static_content.visible
        sc.provisioned = False
        sc.coords = new_coords
        sc.put()

        sln_settings.updates_pending = True
        put_and_invalidate_cache(sc, sln_settings)
        return sln_settings
Example #12
0
    def trans():
        translator = get_translator(service_user)
        mfds = get_multilanguage_message_flow_designs_by_status(service_user, MessageFlowDesign.STATUS_VALID)
        for mfd in mfds:
            render_xml_for_message_flow_design(mfd, translator, dict())

        put_and_invalidate_cache(*mfds)
Example #13
0
    def trans():
        sln_settings = get_solution_settings(service_user)
        service_identity_user = create_service_identity_user_wo_default(
            service_user, service_identity)
        if group_purchase.id:
            sgp = SolutionGroupPurchase.get_by_id(
                group_purchase.id,
                parent_key_unsafe(service_identity_user,
                                  sln_settings.solution))
            if group_purchase.new_picture:
                sgp.picture_version += 1
        else:
            sgp = SolutionGroupPurchase(parent=parent_key_unsafe(
                service_identity_user, sln_settings.solution))
            sgp.picture_version = 0

        sgp.title = group_purchase.title
        sgp.description = group_purchase.description
        sgp.units = group_purchase.units
        sgp.unit_description = group_purchase.unit_description
        sgp.unit_price = group_purchase.unit_price
        sgp.min_units_pp = group_purchase.min_units_pp
        sgp.max_units_pp = group_purchase.max_units_pp
        sgp.time_from = group_purchase.time_from
        sgp.time_until = group_purchase.time_until
        sgp.picture = picture

        sln_settings.updates_pending = True
        put_and_invalidate_cache(sgp, sln_settings)
        return sln_settings
    def trans_create():
        rogerthat_profile = get_service_or_user_profile(users.User(email))
        if rogerthat_profile and isinstance(rogerthat_profile, ServiceProfile):
            from rogerthat.bizz.service import AppFailedToCreateUserProfileWithExistingServiceException
            raise AppFailedToCreateUserProfileWithExistingServiceException(email)

        user_profile = get_user_profile(app_user, cached=False)
        is_new_profile = False
        if not user_profile:
            deactivated_user_profile = get_deactivated_user_profile(app_user)
            if deactivated_user_profile:
                deferred.defer(reactivate_user_profile, deactivated_user_profile, app_user, _transactional=True)
                ActivationLog(timestamp=now(), email=app_user.email(), mobile=None, description="Reactivate user account by registering a paper loyalty card").put()
            else:
                is_new_profile = True
                avatar, image = _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 = name
                user_profile.language = language
                user_profile.avatarId = avatar.key().id()
                user_profile.app_id = app_id
                _calculateAndSetAvatarHash(user_profile, image)

        pp = ProfilePointer(key=db.Key.from_path(ProfilePointer.kind(), user_code))
        pp.user = app_user
        pp.short_url_id = short_url_id

        if is_new_profile:
            put_and_invalidate_cache(user_profile, pp, ProfilePointer.create(app_user))
        else:
            pp.put()
    def trans_create(avatar, image, share_sid_key):
        azzert(not get_service_profile(service_user, cached=False))
        azzert(not get_default_service_identity_not_cached(service_user))

        profile = ServiceProfile(parent=parent_key(service_user), key_name=service_user.email())
        profile.avatarId = avatar.key().id()
        _calculateAndSetAvatarHash(profile, image)

        service_identity_user = create_service_identity_user(service_user, ServiceIdentity.DEFAULT)
        service_identity = ServiceIdentity(key=ServiceIdentity.keyFromUser(service_identity_user))
        service_identity.inheritanceFlags = 0
        service_identity.name = name
        service_identity.description = "%s (%s)" % (name, service_user.email())
        service_identity.shareSIDKey = share_sid_key
        service_identity.shareEnabled = False
        service_identity.creationTimestamp = now()
        service_identity.appIds = supported_app_ids

        update_result = update_func(profile, service_identity) if update_func else None

        put_and_invalidate_cache(profile, service_identity,
                                 ProfilePointer.create(service_user),
                                 ProfileHashIndex.create(service_user))

        deferred.defer(create_default_qr_templates, service_user, _transactional=True)

        return profile, service_identity, update_result
Example #16
0
def delete_loyalty_lottery_info(key):
    ll_info_delete = SolutionLoyaltyLottery.get(key)
    if not ll_info_delete:
        return RETURNSTATUS_TO_SUCCESS

    service_user = users.get_current_user()
    session_ = users.get_current_session()
    service_identity = session_.service_identity
    sln_settings = get_solution_settings(service_user)

    try:
        ll_info = SolutionLoyaltyLottery.load_pending(service_user, service_identity)
        if ll_info_delete.key() == ll_info.key():
            raise RETURNSTATUS_TO_SUCCESS
        if ll_info_delete.schedule_loot_time > 0:
            ll_info_delete.delete()

        sln_settings.updates_pending = True
        put_and_invalidate_cache(sln_settings)
        broadcast_updates_pending(sln_settings)

        send_message(service_user, u"solutions.common.loyalty.lottery.update", service_identity=service_identity)

        return RETURNSTATUS_TO_SUCCESS
    except BusinessException, e:
        return ReturnStatusTO.create(False, common_translate(sln_settings.main_language, SOLUTION_COMMON, e.message))
Example #17
0
def _translate_all_message_flows(service_user):
    '''update all multi-language flows after editable set was deployed'''
    from rogerthat.bizz.service.mfd import render_xml_for_message_flow_design, render_js_for_message_flow_designs, \
        get_message_flow_design_context

    logging.debug("Re-translating all message flows of %s" % service_user.email())

    translator = None
    puts = list()
    multilanguage_flows = get_multilanguage_message_flow_designs_by_status(service_user, MessageFlowDesign.STATUS_VALID)
    for mfd in multilanguage_flows:
        if translator is None:
            translator = get_translator(service_user, ServiceTranslation.MFLOW_TYPES)
        try:
            context = get_message_flow_design_context(mfd) if mfd.definition else None
            render_xml_for_message_flow_design(mfd, translator, context)
            puts.append(mfd)
        except:
            logging.warning("Could not translate msg flow", exc_info=True)


    try:
        changed_languages = render_js_for_message_flow_designs(puts)
    except:
        logging.warning("Could not render JS for flows", exc_info=True)
        changed_languages = None

    put_and_invalidate_cache(*puts)

    if not changed_languages:
        from rogerthat.bizz.job.update_friends import schedule_update_all_friends_of_service_user
        schedule_update_all_friends_of_service_user(service_user, bump_service_version=True, clear_broadcast_settings_cache=True)
Example #18
0
 def trans():
     sln_settings = get_solution_settings(service_user)
     sln_i_settings = get_solution_settings_or_identity_settings(
         sln_settings, service_identity)
     sln_i_settings.holiday_out_of_office_message = db.Text(message)
     sln_settings.updates_pending = True
     put_and_invalidate_cache(sln_settings, sln_i_settings)
     return sln_settings
Example #19
0
def get_profile_for_facebook_user(access_token, app_user, update=False, language=DEFAULT_LANGUAGE, app_id=App.APP_ID_ROGERTHAT):
    gapi = facebook.GraphAPI(access_token)
    fields = ["id", "first_name", "last_name", "name", "verified", "locale", "gender", "email", "birthday", "link"]
    fb_profile = gapi.get_object("me", fields=','.join(fields))
    logging.debug("/me graph response: %s", fb_profile)

    if not app_user:
        if "email" in fb_profile:
            app_user = create_app_user(users.User(fb_profile["email"]), app_id)
        else:
            raise FailedToBuildFacebookProfileException(
                localize(language, 'There is no e-mail address configured in your facebook account. Please use the e-mail based login.'))

        # TODO we should validate app.user_regex
        # TODO we should check if email is not used for a service account

    couple_facebook_id_with_profile(app_user, access_token)
    profile = get_user_profile(app_user)
    if not profile or update:
        if not profile:
            profile = FacebookUserProfile(parent=parent_key(app_user), key_name=app_user.email())
            profile.app_id = app_id
            avatar = Avatar(user=app_user)
        else:
            avatar = get_avatar_by_id(profile.avatarId)
            if not avatar:
                avatar = Avatar(user=app_user)

        if fb_profile.get("name"):
            profile.name = fb_profile["name"]
        else:
            profile.name = get_human_user_from_app_user(app_user).email().replace("@", " at ")

        if profile.birthdate is None and fb_profile.get("birthday"):
            birthday = fb_profile["birthday"].split("/")
            profile.birthdate = get_epoch_from_datetime(
                datetime.date(int(birthday[2]), int(birthday[0]), int(birthday[1])))

        if profile.gender is None and fb_profile.get("gender"):
            gender = fb_profile["gender"]
            if gender == "male":
                profile.gender = UserProfile.GENDER_MALE
            elif gender == "female":
                profile.gender = UserProfile.GENDER_FEMALE
            else:
                profile.gender = UserProfile.GENDER_CUSTOM

        avatar = _get_and_save_facebook_avatar(app_user, fb_profile["id"], profile, avatar)

        profile.avatarId = avatar.key().id()
        profile.language = language
        profile.profile_url = fb_profile.get("link")
        profile.access_token = access_token
        profile.version = 1
        put_and_invalidate_cache(profile, ProfilePointer.create(app_user))
        update_friends(profile, [u"name", u"avatar"])
        update_mobiles(app_user, profile)
    return profile
Example #20
0
def twitter_logout(service_user):
    sln_settings = get_solution_settings(service_user)
    sln_settings.twitter_oauth_token = None
    sln_settings.twitter_oauth_token_secret = None
    sln_settings.twitter_username = None
    put_and_invalidate_cache(sln_settings)
    send_message(service_user,
                 u"solutions.common.twitter.updated",
                 username=None)
 def trans():
     sc = SolutionCalendar(parent=parent_key(sln_settings.service_user,
                                             sln_settings.solution),
                           name="Default",
                           deleted=False)
     sc.put()
     sln_settings.default_calendar = sc.calendar_id
     put_and_invalidate_cache(sln_settings)
     return sc
Example #22
0
    def trans():
        user_profile = get_user_profile(app_user)
        if not user_profile:
            logging.info("unsubscribe_from_reminder_email account that does not exists: %s", app_user)
            return False

        user_profile.unsubscribed_from_reminder_email = True
        put_and_invalidate_cache(user_profile)
        return True
Example #23
0
            def trans():
                job = db.get(job_key)

                for si_email, granted_roles in p.grants.iteritems():
                    if si_email.startswith(si_user_email + '/'):
                        si_user = users.User(si_email)
                        for role in granted_roles:
                            p.revoke_role(si_user, role)
                            job.add_service_grant(si_user, p.user, role)
                put_and_invalidate_cache(p, job)
Example #24
0
 def trans():
     mfd_list = [
         mfd for mfd in get_message_flow_designs_by_status(
             service_user, MessageFlowDesign.STATUS_VALID)
         if mfd.xml and not mfd.definition
     ]  # XML-only flows
     render_js_for_message_flow_designs(mfd_list, notify_friends=False)
     for chunk in chunks(mfd_list, 200):
         put_and_invalidate_cache(*chunk)
     schedule_update_all_friends_of_service_user(service_user)
Example #25
0
    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
Example #26
0
def clear_table_id_in_reservations(service_user, service_identity, table_id):
    service_identity_user = create_service_identity_user_wo_default(
        service_user, service_identity)
    qry = RestaurantReservation.all().filter("service_user =",
                                             service_identity_user)
    qry.filter('tables =', table_id)
    reservations = qry.fetch(None)
    for r in reservations:
        r.tables.remove(table_id)
    put_and_invalidate_cache(*reservations)
Example #27
0
    def trans():
        sln_main_branding = get_solution_main_branding(service_user)
        sln_main_branding.blob = db.Blob(zip_content)
        sln_main_branding.branding_creation_time = 0

        common_settings = get_solution_settings(service_user)
        common_settings.updates_pending = True
        common_settings.events_branding_hash = None

        put_and_invalidate_cache(sln_main_branding, common_settings)
        return common_settings
def _set_main_service_email(app_key, main_services):
    app = db.get(app_key)

    if app:
        app_id = app.app_id
        if app_id in [App.APP_ID_ROGERTHAT, App.APP_ID_OSA_LOYALTY]:
            return

        if app_id in main_services:
            app.main_service = main_services[app.app_id]
            put_and_invalidate_cache(app)
Example #29
0
    def trans():
        mobile, ms, my_profile = db.get((mobile_key, ms_key, get_user_profile_key(current_user)))
        ms.majorVersion = majorVersion
        ms.minorVersion = minorVersion
        ms.lastHeartBeat = now_time

        if appType != MISSING:
            mobile.type = my_profile.mobiles[mobile.account].type_ = appType
        if simCountry != MISSING:
            mobile.simCountry = simCountry
        if simCountryCode != MISSING:
            mobile.simCountryCode = simCountryCode
        if simCarrierCode != MISSING:
            mobile.simCarrierCode = simCarrierCode
        if simCarrierName != MISSING:
            mobile.simCarrierName = simCarrierName
        if netCountry != MISSING:
            mobile.netCountry = netCountry
        if netCountryCode != MISSING:
            mobile.netCountryCode = netCountryCode
        if netCarrierCode != MISSING:
            mobile.netCarrierCode = netCarrierCode
        if netCarrierName != MISSING:
            mobile.netCarrierName = netCarrierName
        if deviceModelName != MISSING:
            mobile.hardwareModel = deviceModelName
        if osVersion != MISSING:
            mobile.osVersion = osVersion
        if localeCountry != MISSING:
            mobile.localeCountry = localeCountry
        if localeLanguage != MISSING:
            mobile.localeLanguage = localeLanguage
        if timezone != MISSING:
            mobile.timezone = timezone
        if timezoneDeltaGMT != MISSING:
            mobile.timezoneDeltaGMT = timezoneDeltaGMT

        language = mobile.localeLanguage
        if language:
            if '-' in language:
                language = get_iso_lang(language.lower())
            elif mobile.localeCountry:
                language = '%s_%s' % (mobile.localeLanguage, mobile.localeCountry)

            if my_profile.language != language:
                my_profile.language = language
                # trigger friend.update service api call
                deferred.defer(update_friend_service_identity_connections, my_profile.key(), _transactional=True)
                db.delete_async(get_broadcast_settings_flow_cache_keys_of_user(my_profile.user))
        my_profile.country = mobile.netCountry or mobile.simCountry or mobile.localeCountry
        my_profile.timezone = mobile.timezone
        my_profile.timezoneDeltaGMT = mobile.timezoneDeltaGMT

        put_and_invalidate_cache(ms, mobile, my_profile)
def get_profile_for_google_user(email, language, name):
    user = users.User(email)
    user_profile = get_user_profile(user)
    if not user_profile:
        user_profile = UserProfile(parent=parent_key(user), key_name=user.email())
        user_profile.name = name if name else user.email()
        user_profile.language = language
        user_profile.version = 1
        put_and_invalidate_cache(user_profile, ProfilePointer.create(user))
        update_friends(user_profile)
    return user_profile
Example #31
0
def delete_appointment_weekday_timeframe(service_user, appointment_id):
    sln_settings = get_solution_settings(service_user)
    sawt = SolutionAppointmentWeekdayTimeframe.get_by_id(appointment_id, parent_key(service_user, sln_settings.solution))
    if sawt:
        sawt.delete()
        sln_settings = get_solution_settings(service_user)
        sln_settings.updates_pending = True
        put_and_invalidate_cache(sln_settings)

        broadcast_updates_pending(sln_settings)
        send_message(service_user, u"solutions.common.appointment.settings.timeframe.update")
 def update_friend(friend, mobile):
     request = UpdateFriendRequestTO()
     request.friend = friend
     request.generation = friend_map.generation  # deprecated
     request.status = status
     capi_calls = updateFriend(update_friend_response, logError, target_user, request=request,
                               DO_NOT_SAVE_RPCCALL_OBJECTS=True, MOBILE_ACCOUNT=mobile, SKIP_ACCOUNTS=skip_mobiles)
     for capi_call in capi_calls:
         capi_call.update_status = status
     put_and_invalidate_cache(*capi_calls)
     return request.friend
Example #33
0
 def trans():
     settings = get_solution_settings(service_user)
     event = get_event_by_id(service_user, settings.solution, event_id)
     if event:
         if event.source == Event.SOURCE_CMS:
             event.delete()
         else:
             event.deleted = True
             event.put()
         settings.updates_pending = True
         put_and_invalidate_cache(settings)
     return settings
def _migrate_profile(profile_keys):
    profiles = db.get(profile_keys)  # type: list[ServiceProfile]
    to_put = []
    for profile in profiles:
        if not profile.callBackURI:
            logging.info('Updating callBackURI from %s to %s', profile.callBackURI, 'mobidick')
            profile.callBackURI = 'mobidick'
            profile.testCallNeeded = False
            profile.enabled = True
            to_put.append(profile)
    if to_put:
        put_and_invalidate_cache(*to_put)
Example #35
0
def _update_next_charge_date(order_key, default_next_charge_date,
                             all_products):
    """Set next charge date to next month."""
    order = Order.get(order_key)

    def is_free_subscription(order_item):
        product = all_products[order_item.product_code]
        return product.is_subscription and product.price == 0

    order_items = order.list_items()
    if any((is_free_subscription(item) for item in order_items)):
        order.next_charge_date = default_next_charge_date
        put_and_invalidate_cache(order)
Example #36
0
    def trans():
        sln_settings = get_solution_settings(service_user)
        sln_i_settings = get_solution_settings_or_identity_settings(
            sln_settings, service_identity)
        for i in range(len(sln_i_settings.holidays) / 2):
            if sln_i_settings.holidays[2 * i] == holiday.start:
                del sln_i_settings.holidays[2 * i:2 * i + 2]
                break
        else:
            raise InvalidHolidayException('holiday-not-found')

        sln_settings.updates_pending = True
        put_and_invalidate_cache(sln_settings, sln_i_settings)
        return sln_settings
Example #37
0
def _remove_new_event_item(sln_settings):
    users.set_user(sln_settings.service_user)
    try:
        service_menu = system.get_menu()
        current_coords = get_coords_of_service_menu_item(service_menu, POKE_TAG_NEW_EVENT)
        logging.info("remove new event item for %s coords %s", sln_settings.service_user, current_coords)
        if current_coords:
            system.delete_menu_item(current_coords)

        sln_settings.events_branding_hash = None
        put_and_invalidate_cache(sln_settings)
        deferred.defer(common_provision, sln_settings.service_user)
    finally:
        users.clear_user()
    def trans():
        new_branding = store_branding_zip(service_user, zip_, description, skip_meta_file)

        if original_branding_hashes:
            # Mark brandings with same description as deleted
            deferred.defer(_mark_brandings_deleted, original_branding_hashes, _transactional=True)
            # Replace branding hash in menu items
            for menu_item in menu_items:
                menu_item.screenBranding = new_branding.hash
            to_put = menu_items

            # Replace branding hash in message flows
            branding_hash_re = re.compile('|'.join(original_branding_hashes))
            for flow in message_flows:
                must_update = False
                if flow.definition:
                    updated_flow_def = branding_hash_re.sub(new_branding.hash, flow.definition)
                    if flow.definition != updated_flow_def:
                        flow.definition = updated_flow_def
                        must_update = True
                if flow.xml:
                    updated_xml = branding_hash_re.sub(new_branding.hash, flow.xml)
                    if flow.xml != updated_xml:
                        flow.xml = updated_xml
                        # update flow definitions
                        render_js_for_message_flow_designs([flow], False)
                        must_update = True
                else:
                    logging.debug('Not updating flow %s xml because its xml is %s', flow.name, flow.xml)
                if must_update:
                    to_put.append(flow)

            # Replace branding hash in service identities
            for service_identity in service_identities:  # type: ServiceIdentity
                assert isinstance(service_identity, ServiceIdentity)
                if service_identity.contentBrandingHash in original_branding_hashes:
                    service_identity.contentBrandingHash = new_branding.hash
                if service_identity.descriptionBranding in original_branding_hashes:
                    service_identity.descriptionBranding = new_branding.hash
                if service_identity.menuBranding in original_branding_hashes:
                    service_identity.menuBranding = new_branding.hash
                if service_identity.homeBrandingHash in original_branding_hashes:
                    service_identity.homeBrandingHash = new_branding.hash
                to_put.append(service_identity)

            put_and_invalidate_cache(*to_put)
            schedule_update_all_friends_of_service_user(get_service_profile(service_user), bump_service_version=True)

        return new_branding, original_branding_hashes
def add_translations_to_all_app_brandings(service_user, branding_translations_dict):
    # branding_translations_dict: { en_text : { web_lang : translation } }
    for translations in branding_translations_dict.itervalues():
        for web_lang in translations.keys():
            iso_lang = get_iso_lang(web_lang)
            translations[iso_lang] = translations.pop(web_lang)

    new_translations_content = _get_translations_js_content(service_user, branding_translations_dict)
    replaced_brandings = dict()  # { old_branding_hash : new_branding_hash }
    to_put = list()
    smis = list()

    for old_branding in Branding.list_by_type(service_user, Branding.TYPE_APP):
        if old_branding.timestamp < 0:
            continue
        with closing(StringIO(old_branding.blob)) as stream:
            with ZipFile(stream) as zip_file:
                try:
                    old_translations_content = zip_file.read(TRANSLATIONS_JS_FILE)
                except KeyError:
                    continue  # __translations__.js not found ==> it did not contain <x-rogerthat-t> tags

                if new_translations_content != old_translations_content:
                    zip_content = replace_file_in_zip(zip_file, TRANSLATIONS_JS_FILE, new_translations_content)
                    new_branding_hash = hashlib.sha256(zip_content).hexdigest().upper()
                    kwargs = copy_model_properties(old_branding)
                    kwargs['blob'] = db.Blob(zip_content)
                    kwargs['timestamp'] = now()
                    to_put.append(Branding(key_name=new_branding_hash, **kwargs))

                    old_branding.timestamp *= -1
                    to_put.append(old_branding)

                    replaced_brandings[old_branding.hash] = new_branding_hash

                    for smi in get_service_menu_items_by_screen_branding(service_user, old_branding.hash):
                        smi.screenBranding = new_branding_hash
                        to_put.append(smi)
                        smis.append(smi)

    if to_put:
        logging.info('Updating %s models', len(to_put))
        put_and_invalidate_cache(*to_put)
        if smis:
            schedule_update_all_friends_of_service_user(service_user, bump_service_version=True)

        system.brandings_updated(brandings_updated_response_handler, logServiceError, get_service_profile(service_user),
                                 brandings=UpdatedBrandingTO.from_dict(replaced_brandings),
                                 reason=UpdatedBrandingTO.REASON_NEW_TRANSLATIONS)
Example #40
0
    def trans():
        sln_settings = get_solution_settings(service_user)
        sln_i_settings = get_solution_settings_or_identity_settings(
            sln_settings, service_identity)
        i = 0
        while i < len(sln_i_settings.holidays) / 2:
            if holiday.start < sln_i_settings.holidays[2 * i]:
                break
            i += 1
        sln_i_settings.holidays.insert(2 * i, holiday.start)
        sln_i_settings.holidays.insert(2 * i + 1, holiday.end)

        sln_settings.updates_pending = True
        put_and_invalidate_cache(sln_settings, sln_i_settings)
        return sln_settings
Example #41
0
    def trans(old_default_app_key):
        new_default_app = get_app_by_id(app_id)
        if new_default_app.key() == old_default_app_key:
            return

        new_default_app.is_default = True

        if old_default_app_key:
            old_default_app = App.get(old_default_app_key)
            old_default_app.is_default = False
            put_and_invalidate_cache(new_default_app, old_default_app)
            on_trans_committed(logging.info, "Default app updated from %s (%s) to %s (%s)", old_default_app.app_id,
                               old_default_app.name, new_default_app.app_id, new_default_app.name)
        else:
            put_and_invalidate_cache(new_default_app)
    def trans_create():
        azzert(not get_user_profile(app_user, cached=False))

        avatar, image = _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 = name
        user_profile.language = language
        user_profile.avatarId = avatar.key().id()
        user_profile.app_id = get_app_id_from_app_user(app_user)
        _calculateAndSetAvatarHash(user_profile, image)

        put_and_invalidate_cache(user_profile, ProfilePointer.create(app_user), ProfileHashIndex.create(app_user))

        return user_profile
Example #43
0
def _put_and_invalidate_cache_and_allocate_ids(*models):

    @db.non_transactional
    def _allocate_non_transactional():
        _allocate()

    def _allocate():
        from google.appengine.api import datastore
        datastore._GetConnection()._reserve_keys([m.key() for m in models if m.key().id() is not None])

    put_and_invalidate_cache(*models)
    if db.is_in_transaction():
        _allocate_non_transactional()
    else:
        _allocate()
    def trans():
        app = get_app(app_id)
        to_put = [app]

        app.admin_services = data.admin_services
        app.name = data.name
        app.type = data.type
        app.main_service = data.main_service
        app.facebook_app_id = data.facebook_app_id
        app.ios_app_id = data.facebook_app_secret
        app.android_app_id = data.android_app_id
        app.dashboard_email_address = data.dashboard_email_address
        app.contact_email_address = data.contact_email_address
        app.user_regex = data.user_regex
        app.demo = data.demo
        app.beta = data.beta
        app.secure = data.secure
        app.chat_enabled = data.chat_enabled
        app.mdp_client_id = data.mdp_client_id
        app.mdp_client_secret = data.mdp_client_secret
        app.owncloud_base_uri = data.owncloud_base_uri
        app.owncloud_admin_username = data.owncloud_admin_username
        app.owncloud_admin_password = data.owncloud_admin_password

        if set(app.embedded_apps).symmetric_difference(data.embedded_apps):
            deferred.defer(send_update_all_embedded_apps, app_id, _countdown=2, _transactional=True)
        app.embedded_apps = data.embedded_apps

        old_auto_connected_services = {acs.service_identity_email for acs in app.auto_connected_services}
        app.auto_connected_services = AutoConnectedServices()
        for acs in data.auto_connected_services:
            service_identity_user = add_slash_default(users.User(acs.service_identity_email))
            if service_identity_user in identities_to_patch:
                si = get_service_identity(service_identity_user)
                si.appIds.append(app_id)
                to_put.append(si)
            acs.service_identity_email = service_identity_user.email()
            app.auto_connected_services.add(acs)

        new_acs = [acs for acs in app.auto_connected_services
                   if acs.service_identity_email not in old_auto_connected_services]
        if new_acs:
            logging.info('There are new auto-connected services for %s: %s', app_id,
                         [acs.service_identity_email for acs in new_acs])
        for acs in new_acs:
            deferred.defer(connect_auto_connected_service, app_id, acs, _transactional=True)
        put_and_invalidate_cache(*to_put)
        return app
Example #45
0
    def trans(old_default_app):
        old_default_app_key = old_default_app and old_default_app.key()
        new_default_app = get_app(app_id)
        if new_default_app.key() == old_default_app_key:
            return new_default_app

        new_default_app.is_default = True

        if old_default_app_key:
            old_default_app.is_default = False
            put_and_invalidate_cache(new_default_app, old_default_app)
            on_trans_committed(logging.info, 'Default app updated from %s (%s) to %s (%s)', old_default_app.app_id,
                               old_default_app.name, new_default_app.app_id, new_default_app.name)
        else:
            put_and_invalidate_cache(new_default_app)
        return new_default_app
Example #46
0
    def trans():
        sln_settings = get_solution_settings(service_user)

        translated_broadcast_types = get_translated_broadcast_types(
            sln_settings)
        diff = set(translated_broadcast_types).symmetric_difference(
            broadcast_types)
        if diff:
            raise InvalidBroadcastTypeException(diff.pop())

        sln_settings.broadcast_types = [
            translated_broadcast_types[bt] for bt in broadcast_types
        ]
        sln_settings.updates_pending = True
        put_and_invalidate_cache(sln_settings)
        broadcast_updates_pending(sln_settings)
Example #47
0
    def trans():
        logo = get_solution_logo(service_user) or SolutionLogo(
            key=SolutionLogo.create_key(service_user))
        logo.picture = db.Blob(jpg_bytes)
        logo.is_default = False

        settings = get_solution_settings(service_user)
        settings.updates_pending = True

        put_and_invalidate_cache(logo, settings)

        deferred.defer(_regenerate_branding_with_logo,
                       service_user,
                       _transactional=True)

        return settings
    def setup_qr_templates(self, app_id):
        app = App.get(App.create_key(app_id))
        app.qrtemplate_keys = list()

        description = u"DEFAULT"
        key_name = create_qr_template_key_name(app_id, description)
        store_template(None, DEFAULT_QR_CODE_OVERLAY, description, u"".join(("%X" % c).rjust(2, '0')
                                                                            for c in DEFAULT_QR_CODE_COLOR), key_name)
        app.qrtemplate_keys.append(key_name)

        description = u"HAND"
        key_name = create_qr_template_key_name(app_id, description)
        store_template(None, HAND_ONLY_QR_CODE_OVERLAY, description, u"".join(("%X" % c).rjust(2, '0')
                                                                              for c in DEFAULT_QR_CODE_COLOR), key_name)
        app.qrtemplate_keys.append(key_name)

        put_and_invalidate_cache(app)
Example #49
0
def create_prospect_from_customer(customer):
    azzert(customer.prospect_id is None and customer.service_email)

    contact = Contact.get_one(customer.key())
    azzert(contact)

    si = get_default_service_identity(users.User(customer.service_email))

    prospect = Prospect(key_name=str(uuid.uuid4()) + str(uuid.uuid4()))
    prospect.name = customer.name
    prospect.address = ', '.join(filter(None, [customer.address1 + ((' ' + customer.address2) if customer.address2 else ''),
                                               customer.zip_code,
                                               customer.city,
                                               OFFICIALLY_SUPPORTED_COUNTRIES.get(customer.country, customer.country)]))
    prospect.phone = contact.phone_number
    prospect.email = contact.email
    prospect.type = ['establishment']
    if customer.organization_type == OrganizationType.EMERGENCY:
        prospect.type.append('health')
    prospect.customer_id = customer.id
    prospect.status = Prospect.STATUS_CUSTOMER
    prospect.app_id = si.app_id
    
    solution_server_settings = get_solution_server_settings()
    prospect.add_comment(u'Converted customer to prospect', users.User(solution_server_settings.shop_no_reply_email)) 
    try:
        result = geo_code(prospect.address)
    except GeoCodeZeroResultsException:
        try:
            result = geo_code(' '.join(filter(None, [customer.zip_code,
                                                     customer.city,
                                                     OFFICIALLY_SUPPORTED_COUNTRIES.get(customer.country,
                                                                                        customer.country)])))
        except GeoCodeZeroResultsException:
            logging.warn('Could not geo_code customer: %s', db.to_dict(customer))
            return

    prospect.geo_point = db.GeoPt(result['geometry']['location']['lat'],
                                  result['geometry']['location']['lng'])

    customer.prospect_id = prospect.id
    prospect.customer_id = customer.id

    logging.info('Creating prospect: %s', db.to_dict(prospect, dict(prospect_id=prospect.id)))
    put_and_invalidate_cache(customer, prospect)
    return prospect
def _delete_ownership_users(service_email):
    to_put = []
    for up in UserProfile.all().filter("owningServiceEmails =", service_email):
        if service_email in up.owningServiceEmails:
            up.owningServiceEmails.remove(service_email)
        if list(get_user_active_mobiles(up.user)):
            if not up.owningServiceEmails:
                up.isCreatedForService = False
            to_put.append(up)
        else:
            if not up.owningServiceEmails:
                deferred.defer(delete_account, up.user, _countdown=5)
            else:
                to_put.append(up)

    if to_put:
        put_and_invalidate_cache(*to_put)
    def trans():
        app = get_app(app_id)
        to_be_put = [app]

        si_users = [add_slash_default(users.User(acs.service_identity_email)) for acs in services]
        service_identities = get_service_identities_by_service_identity_users(si_users)
        for si, acs in zip(service_identities, services):
            if not si:
                raise ServiceWithEmailDoesNotExistsException(acs.service_identity_email)
            if app_id not in si.appIds:
                si.appIds.append(app_id)
                to_be_put.append(si)

            acs.service_identity_email = si.user.email()
            app.auto_connected_services.add(acs)

        put_and_invalidate_cache(*to_be_put)
def delete_app(app_id):
    app = get_app(app_id)
    validate_can_delete_app(app)
    to_delete = [
        AppSettings.create_key(app_id),
        app.key()
    ]
    to_put = []
    for profile_key in UserProfile.all(keys_only=True).filter('app_id', app_id):
        delete_account(users.User(profile_key.parent().name()))
    for other_app in App.all():
        if app_id in other_app.orderable_app_ids:
            other_app.orderable_app_ids.remove(app_id)
            to_put.append(other_app)
    db.delete(to_delete)
    if to_put:
        put_and_invalidate_cache(to_put)
Example #53
0
    def trans_create(avatar_image):
        azzert(not get_user_profile(app_user, cached=False))

        avatar, image = _create_new_avatar(app_user, False, avatar_image)

        user_profile = UserProfile(parent=parent_key(app_user), key_name=app_user.email())
        user_profile.name = name
        user_profile.language = language
        user_profile.avatarId = avatar.key().id()
        user_profile.app_id = get_app_id_from_app_user(app_user)
        user_profile.owncloud_password = owncloud_password
        if tos_version:
            user_profile.tos_version = tos_version
        if consent_push_notifications_shown:
            user_profile.consent_push_notifications_shown = True
        _calculateAndSetAvatarHash(user_profile, image)

        put_and_invalidate_cache(user_profile, ProfilePointer.create(app_user), ProfileHashIndex.create(app_user))

        return user_profile
Example #54
0
    def trans():
        to_put = set()

        service_profile = get_service_profile(service_user)
        if not service_profile.editableTranslationSet:
            logging.error("Deploy translation error - no editable translation found for svc %s" % service_user.email())
            return

        # 1. Archive old active translation set
        if service_profile.activeTranslationSet:
            old_active_translation_set = ServiceTranslationSet.get(service_profile.activeTranslationSet)
            old_active_translation_set.status = ServiceTranslationSet.ARCHIVED
            to_put.add(old_active_translation_set)

        # 2. Promote old editable translation set to new active
        service_profile.activeTranslationSet = service_profile.editableTranslationSet
        to_put.add(service_profile)
        new_active_translation_set = ServiceTranslationSet.get(service_profile.activeTranslationSet)
        new_active_translation_set.status = ServiceTranslationSet.ACTIVE
        to_put.add(new_active_translation_set)

        # 3. Create new editable translation set
        new_editable_translation_set = ServiceTranslationSet.create_editable_set(service_user)
        new_editable_translation_set.latest_export_timestamp = new_active_translation_set.latest_export_timestamp
        service_profile.editableTranslationSet = str(new_editable_translation_set.key())
        to_put.add(new_editable_translation_set)

        # 4. Copy existing translations to new
        branding_translations_dict = None
        for tr in ServiceTranslation.all().ancestor(new_active_translation_set).fetch(None):
            translation_dict = tr.translation_dict
            if tr.translation_type == ServiceTranslation.BRANDING_CONTENT:
                branding_translations_dict = translation_dict
            to_put.add(ServiceTranslation.create(new_editable_translation_set, tr.translation_type, translation_dict))

        # 5. Store all in db
        put_and_invalidate_cache(*to_put)

        return service_profile, branding_translations_dict
    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)

        put_and_invalidate_cache(mobile, ms, my_profile)

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

        return mobile, my_profile
 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)
    def trans():
        # type: () -> tuple[Mobile, UserProfile, bool]
        keys = (mobile_key, ms_key, get_user_profile_key(current_user))
        mobile, ms, my_profile = db.get(keys)  # type: (Mobile, MobileSettings, UserProfile)
        if mobile.account not in my_profile.mobiles:
            logging.warn('Mobile account "%s" of user %s has been unregistered', mobile.account, current_user)
            return mobile, my_profile, False

        if appType != MISSING:
            mobile.type = my_profile.mobiles[mobile.account].type_ = appType
        if simCountry != MISSING:
            mobile.simCountry = simCountry
        if simCountryCode != MISSING:
            mobile.simCountryCode = simCountryCode
        if simCarrierCode != MISSING:
            mobile.simCarrierCode = simCarrierCode
        if simCarrierName != MISSING:
            mobile.simCarrierName = simCarrierName
        if netCountry != MISSING:
            mobile.netCountry = netCountry
        if netCountryCode != MISSING:
            mobile.netCountryCode = netCountryCode
        if netCarrierCode != MISSING:
            mobile.netCarrierCode = netCarrierCode
        if netCarrierName != MISSING:
            mobile.netCarrierName = netCarrierName
        if deviceModelName != MISSING:
            mobile.hardwareModel = deviceModelName
        if osVersion != MISSING:
            mobile.osVersion = osVersion
        if localeCountry != MISSING:
            mobile.localeCountry = localeCountry
        if localeLanguage != MISSING:
            mobile.localeLanguage = localeLanguage
        if timezone != MISSING:
            mobile.timezone = timezone
        if timezoneDeltaGMT != MISSING:
            mobile.timezoneDeltaGMT = timezoneDeltaGMT
        if deviceId != MISSING:
            mobile.deviceId = deviceId

        language = mobile.localeLanguage
        if language:
            should_update_embedded_apps = False
            if '-' in language:
                language = get_iso_lang(language.lower())
            elif mobile.localeCountry:
                language = '%s_%s' % (mobile.localeLanguage, mobile.localeCountry)

            if my_profile.language != language:
                my_profile.language = language
                # trigger friend.update service api call
                deferred.defer(update_friend_service_identity_connections, my_profile.key(), [u"language"],
                               _transactional=True)
                db.delete_async(get_broadcast_settings_flow_cache_keys_of_user(my_profile.user))
                if embeddedApps:
                    should_update_embedded_apps = True
            deferred.defer(update_look_and_feel_for_user, current_user, _transactional=True, _queue=FAST_QUEUE)

            # User updated to app version x.1.x, send custom translations
            # todo: this will also trigger when user updates from 3.0.x to 3.1.x which we don't really want
            should_update_embedded_apps = should_update_embedded_apps or majorVersion > 1 and ms.majorVersion == 0
            # Update when embedded apps are different
            should_update_embedded_apps = should_update_embedded_apps or not set(embeddedApps).issubset(
                set(my_profile.embedded_apps or []))
            if should_update_embedded_apps:
                deferred.defer(update_embedded_app_translations_for_user, current_user, embeddedApps, language,
                               _transactional=True)

        ms.majorVersion = majorVersion
        ms.minorVersion = minorVersion
        ms.lastHeartBeat = now_time

        my_profile.country = mobile.netCountry or mobile.simCountry or mobile.localeCountry
        my_profile.timezone = mobile.timezone
        my_profile.timezoneDeltaGMT = mobile.timezoneDeltaGMT
        my_profile.embedded_apps = embeddedApps
        must_update_app_settings = False
        if my_profile.tos_version != get_current_document_version(DOC_TERMS):
            if mobile.is_android:
                version = Features.ASK_TOS.android
            elif mobile.is_ios:
                version = Features.ASK_TOS.ios
            else:
                version = Version(0, 1)
            must_update_app_settings = Version(majorVersion, minorVersion) >= version
        put_and_invalidate_cache(ms, mobile, my_profile)
        return mobile, my_profile, must_update_app_settings
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
    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
    def trans_update(mfds):
        service_profile = get_service_profile(service_user)
        service_profile.version += 1

        put_and_invalidate_cache(service_profile, *mfds)