def _1000_disable_old_service(job_key): phase = MigrateServiceJob.PHASE_1000_DISABLE_OLD_SERVICE next_phase = MigrateServiceJob.PHASE_2000_MIGRATE_USER_DATA # Validate that the job still exists job = _get_job(job_key, phase) # Do the work _log_progress(job) logging.info("1/ Set enabled=False") from_service_profile = get_service_profile(job.from_service_user) if from_service_profile.enabled: from_service_profile.enabled = False from_service_profile.solution = None from_service_profile.put() logging.info("2/ Drop search indexes asynchronously") _delete_search_indexes(job.from_service_user) logging.info("3/ Delete Sessions asynchronously") _delete_sessions(job.from_service_user) # Set the next phase _set_job_in_next_phase(job_key, phase, next_phase)
def login_as(account): user = users.get_current_user() session_ = users.get_current_session() if not (user and session_): logging.warning("login_as called from unauthenticated context") return # Get service identities of session.user if session_.user.email() == account: session_ = switch_to_service_identity(session_, None, False, False) users.update_session_object(session_, session_.user) logging.info("Switching session of %s from %s to %s", session_.user, user, account) return session_.user.email() else: service_identity_user = users.User(account) logging.info("Validating if %s has a role in %s", session_.user, service_identity_user) if session_.has_access(account): service_profile = get_service_profile(get_service_user_from_service_identity_user(service_identity_user)) if service_profile.expiredAt > 0: raise ServiceExpiredException() session_ = switch_to_service_identity(session_, service_identity_user, False, False) service_user, _ = get_service_identity_tuple(service_identity_user) users.update_session_object(session_, service_user) logging.info("Switching session of %s from %s to %s", session_.user, user, service_identity_user) return service_identity_user.email() logging.critical("%s tried getting access to %s!", session_.user, account)
def get(self): service_user = users.get_current_user() azzert(get_service_profile(service_user)) # must exist message_flow_designs = get_service_message_flow_designs(service_user) result = [] for wiring in message_flow_designs: if wiring.deleted or not wiring.definition: continue wiringDefinition = json.loads(wiring.definition) for k in wiringDefinition.iterkeys(): if k == u"modules": for m in wiringDefinition[k]: if m["value"]: m["config"]["formMessageDef"] = m["value"] result.append({"name": wiring.name, "language": wiring.language, "working": json.dumps(wiringDefinition)}) if not result: wiring_id = "Sample message flow" language = "MessageFlow" result.append({"name": wiring_id, "language": language, "working": SAMPLE_MF}) message_flow_design = MessageFlowDesign(parent=parent_key(service_user), key_name=wiring_id) message_flow_design.definition = SAMPLE_MF message_flow_design.name = wiring_id message_flow_design.language = language message_flow_design.design_timestamp = now() message_flow_design.status = MessageFlowDesign.STATUS_VALID message_flow_design.js_flow_definitions = JsFlowDefinitions() message_flow_design.put() self.response.out.write(json.dumps(result))
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
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)
def _delete_non_ancestor_models(parent_service_user, service_user): sp = get_service_profile(service_user) if sp: def get_service_identity_based_keys(): keys = list() si_users = list() for si in get_service_identities(service_user): keys.append(ProfilePointer.create_key(si.service_identity_user)) si_users.append(si.service_identity_user) for qr in ServiceInteractionDef.all().ancestor(parent_key(service_user)): keys.append(db.Key.from_path(ShortURL.kind(), ServiceInteractionDef.shortUrl.get_value_for_datastore(qr).id())) return keys, si_users keys = [db.Key.from_path(Avatar.kind(), sp.avatarId)] keys.extend(TrialServiceAccount.all(keys_only=True).filter("service", service_user)) more_keys, service_identity_users = db.run_in_transaction(get_service_identity_based_keys) keys.extend(more_keys) keys.extend(MessageFlowRunRecord.all(keys_only=True).filter("service_identity >=", service_user.email() + '/').filter("service_identity <", service_user.email() + u"/\ufffd")) keys.extend(Branding.all(keys_only=True).filter("user", service_user)) keys.extend(SIKKey.all(keys_only=True).filter("user", service_user)) keys.extend(APIKey.all(keys_only=True).filter("user", service_user)) logging.info(keys) db.delete(keys) delete_service_tasks = DeleteServiceTasks(key_name=service_user.email()) delete_service_tasks.tasks = 3 delete_service_tasks.put() deferred.defer(_delete_sessions, parent_service_user, service_user) deferred.defer(_delete_service_log, parent_service_user, service_user) deferred.defer(_delete_service_models, parent_service_user, service_user) deferred.defer(_cleanup_service_identities, service_identity_users) else: if parent_service_user and parent_service_user != service_user: deferred.defer(delete_service_finished, parent_service_user, service_user.email(), True)
def get_service_identity_details(identifier): azzert(identifier) service_user = users.get_current_user() service_identity_user = create_service_identity_user(service_user, identifier) service_identity = get_service_identity_not_cached(service_identity_user) service_profile = get_service_profile(service_user, cached=False) return ServiceIdentityDetailsTO.fromServiceIdentity(service_identity, service_profile)
def put_loyalty_user(service_user, url, email): su = None # ShortURL m = re.match("(HTTPS?://)(.*)/(M|S)/(.*)", url.upper()) if m: from rogerthat.pages.shortner import get_short_url_by_code code = m.group(4) su = get_short_url_by_code(code) if su and not su.full.startswith("/q/i"): su = None if su: si = None else: logging.debug('Create new unassigned short url, because the provided loyalty user URL is unkown (%s)', url) si = get_default_service_identity(service_user) su = generate_unassigned_short_urls(si.app_id, 1)[0] url = su.full user_code = su.full[4:] pp = ProfilePointer.get(user_code) if pp: app_user = pp.user else: service_profile = get_service_profile(service_user) si = si or get_default_service_identity(service_user) app_id = si.app_id app_user = put_loyalty_user_profile(email.strip(), app_id, user_code, su.key().id(), service_profile.defaultLanguage) return url, app_user
def sync_service_translations(service_user): service_profile = get_service_profile(service_user) translation_set = None if service_profile.editableTranslationSet: translation_set = ServiceTranslationSet.get(db.Key(encoded=service_profile.editableTranslationSet)) translation_set.status = ServiceTranslationSet.SYNCING translation_set.put() else: translation_set = ServiceTranslationSet.create_editable_set(service_user) translation_set.status = ServiceTranslationSet.SYNCING translation_set.put() service_profile.editableTranslationSet = str(translation_set.key()) service_profile.put() current_translations = get_all_translations(translation_set) current_service_strings = assemble_service_strings(service_user) current_service_strings[ServiceTranslation.BRANDING_CONTENT] = current_translations.get(ServiceTranslation.BRANDING_CONTENT, dict()) updated_translations = dict() for translation_type, default_strings in current_service_strings.iteritems(): current_translations_for_type = current_translations.get(translation_type, dict()) updated_translations_for_type = dict() for default_string in default_strings: updated_translations_for_type[default_string] = current_translations_for_type.get(default_string, None) updated_translations[translation_type] = updated_translations_for_type save_translations(translation_set, updated_translations)
def trans(): user_profile = get_user_profile(app_user) if user_profile.isCreatedForService: return ui = get_user_interaction(app_user) if acs.service_identity_email not in ui.services: service_identity_user = users.User(acs.service_identity_email) do_make_friends = True if acs.service_roles: do_make_friends = False # is app_user in one of the roles? service_user, si_id = get_service_identity_tuple(service_identity_user) synced_roles = list() for service_role in get_service_roles_by_ids(service_user, acs.service_roles): if user_profile.has_role(service_identity_user, u'sr:%s' % service_role.role_id): do_make_friends = True break elif service_role.type == ServiceRole.TYPE_SYNCED: synced_roles.append(service_role) else: # for loop did not reach BREAK: user_profile does not have any role --> send friend.is_in_roles user_details = [UserDetailsTO.fromUserProfile(user_profile)] send_is_in_roles(app_user, get_service_profile(service_user), si_id, user_details, map(RoleTO.fromServiceRole, synced_roles), make_friends_if_in_role=True) if do_make_friends: ui.services.append(acs.service_identity_email) ui.put() logging.info("Connecting %s with auto-connected service %s", app_user, acs.service_identity_email) deferred.defer(makeFriends, service_identity_user, app_user, app_user, None, notify_invitee=False, origin=ORIGIN_USER_INVITE, _transactional=True)
def get_menu(identifier): service_user = users.get_current_user() service_identity_user = create_service_identity_user(service_user, identifier) service_identity = get_service_identity(service_identity_user) dummy_translator = DummyTranslator(get_service_profile(service_user).defaultLanguage) sm = WebServiceMenuTO.fromServiceIdentity(service_identity, dummy_translator.default_language, dummy_translator) return sm
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)
def trans(): service_profile = get_service_profile(service_user, False) if not broadcast_type in service_profile.broadcastTypes: return service_profile.broadcastTypes.remove(broadcast_type) set_broadcast_types(service_user, service_profile.broadcastTypes)
def list_identities(cursor=None): service_user = users.get_current_user() if cursor: try: cursor = decrypt(service_user, cursor) except: from rogerthat.bizz.exceptions import InvalidCursorException raise InvalidCursorException() from rogerthat.dal.service import get_service_identities_query qry = get_service_identities_query(service_user) qry.with_cursor(cursor) identities = qry.fetch(1000) # prevent extra roundtrip by trying to detect whether there are more results to fetch if len(identities) < 1000 and cursor: extra_identities = qry.fetch(10) if len(extra_identities) == 0: cursor = None else: identities.extend(extra_identities) cursor = qry.cursor() service_profile = get_service_profile(service_user) result = ServiceIdentityListResultTO() result.cursor = unicode(encrypt(service_user, cursor)) if cursor else None result.identities = [ServiceIdentityDetailsTO.fromServiceIdentity(i, service_profile) for i in identities] return result
def assemble_message_flow_strings(service_user): """Go over all flows of this service user and create an in-memory dict. Key = translation_type e.g. ServiceTranslation.MFLOW_POPUP Value = set of strings in default language Must run from a deferred Returns dict(translation_type: set(default strings)) """ flows = get_multilanguage_message_flow_designs_by_status(service_user, MessageFlowDesign.STATUS_VALID) language_map = dict((translation_type, set()) for translation_type in set(MFLOW_XPATH_MAP.values())) default_language = get_service_profile(service_user).defaultLanguage for flow in flows: thexml = flow.xml.replace('xmlns="https://rogerth.at/api/1/MessageFlow.xsd"', '') # Dont want complex xpath queries due to namespace tree = etree.fromstring(thexml.encode('utf-8')) # @UndefinedVariable for (path, translation_type) in MFLOW_XPATH_MAP.iteritems(): for default_str in tree.xpath(path, lang=default_language): if default_str: if translation_type == ServiceTranslation.MFLOW_TEXT: default_str = default_str.strip() language_map[translation_type].add(default_str) else: logging.warning("XPATH ERROR - found empty str for path %s" % path) return language_map
def get_languages(): service_user = users.get_current_user() service_profile = get_service_profile(service_user) languages = LanguagesTO() languages.default_language = service_profile.defaultLanguage languages.supported_languages = service_profile.supportedLanguages[1:] return languages
def process(service_api_callback): try: svc_profile = get_service_profile(service_api_callback.service_user) if not svc_profile.enabled: service_api_callback.timestamp = 0 - service_api_callback.timestamp service_api_callback.put() return retry_call_back = True service_api_callback.retryCount += 1 service_api_callback.timestamp = now() + (SERVICE_API_CALLBACK_RETRY_UNIT * 2 ** service_api_callback.retryCount) if service_api_callback.retryCount > 2: logging.warn('Service api failure for %s with retrycount %s', service_api_callback.key(), service_api_callback.retryCount) monitoring.log_service_api_failure(service_api_callback, monitoring.SERVICE_API_CALLBACK) if service_api_callback.retryCount > 7: send_callback_delivery_warning(svc_profile, "callback timeout delivery") service_api_callback.put() if not retry_call_back: return success, message = submit_service_api_callback(svc_profile, service_api_callback) request = json.loads(service_api_callback.call) log_service_activity(svc_profile.user, request["id"], ServiceLog.TYPE_CALLBACK, ServiceLog.STATUS_WAITING_FOR_RESPONSE if success else ServiceLog.STATUS_ERROR, request["method"], service_api_callback.call, message) except Exception, e: logging.error("Could not process service api callback retention:\n%s" % e, exc_info=True)
def post(self): email = self.request.POST.get("email", None) if not email: self.redirect(result="Supply the email of the user!") return mobidick = self.request.POST.get("mobidick", "") logging.info("Email: %s" % email) logging.info("Mobidick: %s" % mobidick) user = users.User(email) profile_info = get_profile_info(user) if not profile_info: self.redirect(result="User %s is not found!" % email, cts_email=email) return if profile_info.isServiceIdentity: service_profile = get_service_profile(user) if service_profile.callBackURI != "mobidick" and mobidick == "CHECKED": try: configure_mobidick(user) self.redirect(result="Configured %s to use mobidick backend!" % email) except Exception, e: logging.exception(e) self.redirect(result=str(e), cts_email=email, cts_mobidick=mobidick) else: self.redirect(result="The user is already a service!") return
def _must_continue_with_update_service(service_profile_or_user, bump_service_version=False, clear_broadcast_settings_cache=False): def trans(service_profile): azzert(service_profile) service_profile_updated = False if not service_profile.autoUpdating and not service_profile.updatesPending: service_profile.updatesPending = True service_profile_updated = True if bump_service_version: service_profile.version += 1 service_profile_updated = True if clear_broadcast_settings_cache: service_profile.addFlag(ServiceProfile.FLAG_CLEAR_BROADCAST_SETTINGS_CACHE) service_profile_updated = True if service_profile_updated: channel.send_message(service_profile.user, 'rogerthat.service.updatesPendingChanged', updatesPending=service_profile.updatesPending) service_profile.put() return service_profile.autoUpdating is_user = not isinstance(service_profile_or_user, ServiceProfile) if db.is_in_transaction(): azzert(not is_user) service_profile = service_profile_or_user auto_updating = trans(service_profile_or_user) else: service_profile = get_service_profile(service_profile_or_user, False) if is_user else service_profile_or_user auto_updating = db.run_in_transaction(trans, service_profile) if not auto_updating: logging.info("Auto-updates for %s are suspended." % service_profile.user.email()) return auto_updating
def mapper(service_identity): # type: (ServiceIdentity) -> GeneratorType service_profile = get_service_profile(service_identity.service_user) if not service_profile: logging.error('No service profile found for service identity %s', service_identity.service_user) else: yield service_identity.app_id, str((service_profile.organizationType, 1)) # must return a string
def test_form(service_user, form_id, testers): # type: (users.User, int, list[users.User]) -> None form = get_form(form_id, service_user) request = TestFormRequestTO(id=form_id, version=form.version) to_put = [] prof = get_service_profile(service_user) branding = prof.broadcastBranding caption = localize(prof.defaultLanguage, 'forms.test_form') answers = [AnswerTO(id_=u'test', caption=caption, action=u'form://%d?version=%d&test=true' % (form_id, form.version))] flags = Message.FLAG_AUTO_LOCK alert_flags = Message.ALERT_FLAG_VIBRATE tag = None message = localize(prof.defaultLanguage, 'forms.click_button_to_test') for user_profile in get_profile_infos(testers): mobiles = db.get([get_mobile_key_by_account(mobile_detail.account) for mobile_detail in user_profile.mobiles]) has_other = False android_mobile = None for mobile in mobiles: if mobile.is_android: android_mobile = mobile else: has_other = True if has_other: messaging.send(None, None, message, answers, flags, [MemberTO.from_user(user_profile.user)], branding, tag, alert_flags=alert_flags) else: title = localize(prof.defaultLanguage, 'forms.test_form_x', title=form.title) body = localize(prof.defaultLanguage, 'forms.click_to_test_your_form') kwargs = {CAPI_KEYWORD_PUSH_DATA: TestFormNotification(title, body, form.id, form.version)} to_put.extend(testForm(test_form_response_handler, logError, user_profile.user, request=request, MOBILE_ACCOUNT=android_mobile, DO_NOT_SAVE_RPCCALL_OBJECTS=True, **kwargs)) db.put(to_put)
def message_flow_designs(with_design_only=False): service_user = users.get_current_user() mfds = (mfd for mfd in get_service_message_flow_designs(service_user) if not with_design_only or mfd.definition) result = MessageFlowListTO() result.message_flows = sorted(map(MessageFlowDesignTO.fromMessageFlowDesign, mfds), key=lambda mfd: (not mfd.multilanguage, mfd.name.upper())) result.service_languages = get_service_profile(service_user).supportedLanguages return result
def trans(): service_profile = get_service_profile(service_user) if image: _update_avatar(service_profile, image, add_trial_overlay) service_profile.version += 1 service_profile.put() schedule_update_all_friends_of_service_user(service_profile)
def translate_service_strings(service_user): service_profile = get_service_profile(service_user) sync_service_translations(service_user) translation_set = get_editable_translation_set(service_user) tr_dict = get_all_translations(translation_set) for type_, translations in tr_dict.iteritems(): for k in translations.iterkeys(): for l in service_profile.supportedLanguages[1:]: translated = "%s_%s" % (l, k) if tr_dict[type_][k]: tr_dict[type_][k][l] = translated else: tr_dict[type_][k] = {l: translated} save_translations(translation_set, tr_dict) deploy_translation(service_user) service_profile = get_service_profile(service_user) assert get_active_translation_set(service_profile)
def trans(): service_profile = get_service_profile(service_user) if not service_profile: return sln_avatar = SolutionAvatar( key=SolutionAvatar.create_key(service_user)) sln_avatar.picture = get_avatar_by_id(service_profile.avatarId).picture sln_avatar.put()
def testSvcIdentityDetailsTOs(self): id_default, id_child = self.prepare_svc('*****@*****.**', [u"rogerthat"]) default_dict = {'phone_number': u'123456123123', 'search_use_default': False, 'description_use_default': False, 'description_branding': u'DESCBR', 'description': u'Default name ([email protected])', 'created': id_default.creationTimestamp, 'qualified_identifier': u'qual1', 'phone_number_use_default': False, 'phone_call_popup': None, 'phone_call_popup_use_default': False, 'admin_emails': [], 'search_config':{'keywords': None, 'enabled': False, 'locations': []}, 'menu_branding_use_default': False, 'menu_branding': u'MENUBR', 'recommend_enabled': id_default.shareEnabled, 'identifier': u'+default+', 'description_branding_use_default': False, 'name': u'Default name', 'email_statistics': False, 'email_statistics_use_default': False, 'app_data': None, 'app_ids_use_default':False, 'app_ids':[App.APP_ID_ROGERTHAT], 'app_names':["Rogerthat"], 'can_edit_supported_apps':False, 'content_branding_hash': None, 'home_branding_hash': u'HOMEBR', 'home_branding_use_default': False} service_profile = get_service_profile(users.User(u'*****@*****.**')) # print serialize_complex_value(ServiceIdentityDetailsTO.fromServiceIdentity(id_default, service_profile), ServiceIdentityDetailsTO, False) # print default_dict current_dict = serialize_complex_value(ServiceIdentityDetailsTO.fromServiceIdentity(id_default, service_profile), ServiceIdentityDetailsTO, False) azzert(current_dict == default_dict) child_dict = default_dict.copy() child_dict['menu_branding'] = None child_dict['name'] = u'child' child_dict['qualified_identifier'] = None child_dict['identifier'] = u'childid' child_dict['description_branding_use_default'] = True child_dict['phone_number_use_default'] = True child_dict['description'] = u'Child description' child_dict['created'] = id_child.creationTimestamp child_dict['recommend_enabled'] = False child_dict['email_statistics'] = False child_dict['home_branding_use_default'] = True # print serialize_complex_value(ServiceIdentityDetailsTO.fromServiceIdentity(id_child, service_profile), ServiceIdentityDetailsTO, False) # print child_dict azzert(serialize_complex_value(ServiceIdentityDetailsTO.fromServiceIdentity(id_child, service_profile), ServiceIdentityDetailsTO, False) == child_dict)
def get_status(): service = users.get_current_user() profile = get_service_profile(service, cached=False) status = ServiceStatusTO() status.enabled = True if profile.enabled else False # Prevent sending None status.test_callback_needed = profile.testCallNeeded status.auto_updating = profile.autoUpdating status.updates_pending = profile.updatesPending return status
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 fromServiceIdentity(cls, service_identity, language, translator): service_profile = get_service_profile(service_identity.service_user) actionMenu = cls() actionMenu.aboutLabel = translator.translate(ServiceTranslation.HOME_TEXT, service_profile.aboutMenuItemLabel, language) actionMenu.messagesLabel = translator.translate(ServiceTranslation.HOME_TEXT, service_profile.messagesMenuItemLabel, language) actionMenu.shareLabel = translator.translate(ServiceTranslation.HOME_TEXT, service_profile.shareMenuItemLabel, language) actionMenu.callLabel = translator.translate(ServiceTranslation.HOME_TEXT, service_profile.callMenuItemLabel, language) actionMenu.callConfirmation = translator.translate(ServiceTranslation.IDENTITY_TEXT, service_identity.callMenuItemConfirmation, language) return actionMenu
def post(self): service_user = users.get_current_user() azzert(get_service_profile(service_user)) # must exist wiring_id = self.request.get('name', None) result = dict(error=None) try: delete_message_flow_by_name(service_user, wiring_id) except BusinessException, e: result['error'] = e.message
def store_branding(service_user, zip_stream, description): azzert(get_service_profile(service_user) is not None) zip_stream.seek(0) try: zip_ = ZipFile(zip_stream) except BadZipfile, e: raise BadBrandingZipException(e.message)
def trans(): editable_translation_set = get_editable_translation_set(service_user) if not editable_translation_set: editable_translation_set = ServiceTranslationSet.create_editable_set(service_user) editable_translation_set.put() service_profile = get_service_profile(service_user) service_profile.editableTranslationSet = str(editable_translation_set.key()) service_profile.put() return editable_translation_set
def trans(): service_profile = get_service_profile(service_user, False) for service_identity in identities: deferred.defer(_delete_solution_models, service_user, service_identity, [service_profile.solution, SOLUTION_COMMON], delete_svc, _transactional=True) service_profile.solution = None service_profile.put()
def translate_service_strings(service_user): service_profile = get_service_profile(service_user) sync_service_translations(service_user) translation_set = get_editable_translation_set(service_user) tr_dict = get_all_translations(translation_set) for type_, translations in tr_dict.iteritems(): for k in translations.iterkeys(): for l in service_profile.supportedLanguages[1:]: translated = "%s_%s" % (l, k) if tr_dict[type_][k]: tr_dict[type_][k][l] = translated else: tr_dict[type_][k] = {l: translated} save_translations(translation_set, tr_dict) deploy_translation(service_user) assert get_active_translation_set(service_user)
def _provision_without_publish(sln_settings_key): service_user = users.User(sln_settings_key.parent().name()) service_profile = get_service_profile(service_user) if not service_profile or service_profile.solution != SOLUTION_FLEX: return with users.set_user(service_user): default_lang = get_default_language() sln_settings = get_and_complete_solution_settings( service_user, SOLUTION_FLEX) put_avatar_if_needed(service_user) # Force update branding settings branding_settings = SolutionBrandingSettings.get( SolutionBrandingSettings.create_key(service_user)) if not branding_settings: return if branding_settings.color_scheme == u'dark': branding_settings.menu_item_color = SolutionBrandingSettings.default_menu_item_color( u'light') branding_settings.modification_time = now() branding_settings.color_scheme = u'light' branding_settings.background_color = SolutionBrandingSettings.default_background_color( branding_settings.color_scheme) branding_settings.text_color = SolutionBrandingSettings.default_text_color( branding_settings.color_scheme) branding_settings.show_avatar = False branding_settings.put() main_branding = get_and_store_main_branding(service_user) populate_identity(sln_settings, main_branding.branding_key) for i, label in enumerate(['About', 'History', 'Call', 'Recommend']): system.put_reserved_menu_item_label( i, translate(sln_settings.main_language, SOLUTION_COMMON, label)) xg_on = db.create_transaction_options(xg=True) allow_transaction_propagation(db.run_in_transaction_options, xg_on, provision_all_modules, sln_settings, DEFAULT_COORDS, main_branding, default_lang)
def trans2(): to_service_profile = get_service_profile(job.to_service_user) to_service_profile.enabled = job.service_enabled to_service_profile.solution = job.solution to_service_profile.put()
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 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)