Ejemplo n.º 1
0
    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))
Ejemplo n.º 2
0
def controller(job_key, current_phase=None, retry_interval=0):
    '''Responsible for chaining the different phases'''
    job = _get_job(job_key)
    logging.debug('MigrateServiceJob phase %s->%s (key %s)', current_phase, job.phase, job_key)

    if job.phase == MigrateServiceJob.PHASE_DONE:
        logging.info('Migration of %s to %s completed!', job.from_service_user, job.to_service_user)
        return

    if job.phase == current_phase:
        next_retry_interval = min(retry_interval + 1, 5)
    else:
        worker = PHASES.get(job.phase)
        azzert(worker, 'Unexpected job phase: %s' % job.phase)

        kwargs = dict(job_key=job_key, _queue=MIGRATION_QUEUE)
        deferred.defer(worker, **kwargs)
        channel.send_message(job.executor_user, 'rogerthat.jobs.migrate_service.next_phase',
                             progress=job.estimate_progress(),
                             phase=job.phase)

        next_retry_interval = 1

    deferred.defer(controller, job_key, job.phase, next_retry_interval,
                   _countdown=next_retry_interval, _queue=HIGH_LOAD_CONTROLLER_QUEUE)
Ejemplo n.º 3
0
def _3000_revoke_roles(job_key):
    phase = MigrateServiceJob.PHASE_3000_REVOKE_ROLES
    next_phase = MigrateServiceJob.PHASE_4000_DISCONNECT_FRIENDS

    # Validate that the job still exists
    job = _get_job(job_key, phase)

    # Do the work
    _log_progress(job)

    try:
        si_user_email = job.from_service_user.email()
        profiles = UserProfile.list_by_service_role_email(si_user_email)
        for p in profiles:
            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)

            xg_on = db.create_transaction_options(xg=True)
            db.run_in_transaction_options(xg_on, trans)
    except BusinessException as e:
        logging.exception("Caught BusinessException")
        azzert(False, "Caught BusinessException: %s" % e)

    # Set the next phase
    _set_job_in_next_phase(job_key, phase, next_phase)
Ejemplo n.º 4
0
 def add(self, category):
     if category.id:
         azzert(category.id not in self._table)
         self._table[category.id] = category
     else:
         azzert(category.name not in self._table)
         self._table[category.name] = category
Ejemplo n.º 5
0
    def get(self, info):
        try:
            padding = ""
            while True:
                try:
                    data = base64.b64decode(info + padding)
                    break
                except TypeError:
                    if len(padding) < 2:
                        padding += "="
                    else:
                        raise
            json_params = json.loads(data)

            parent_message_key = json_params['parent_message_key']
            message_key = json_params['message_key']

            azzert(message_key, "message_key is required")

            if parent_message_key == "":
                parent_message_key = None
        except:
            logging.exception("Error in ServiceDownloadPhotoHandler")
            self.error(404)
            return

        logging.debug("Download photo %s %s" % (parent_message_key, message_key))
        photo_upload_result = get_transfer_result(parent_message_key, message_key)
        if not photo_upload_result:
            self.error(404)
            return

        azzert(photo_upload_result.status == photo_upload_result.STATUS_VERIFIED)
        self.response.headers['Content-Type'] = "image/jpeg" if photo_upload_result.content_type == None else str(photo_upload_result.content_type)
        self.response.out.write(assemble_transfer_from_chunks(photo_upload_result.key()))
Ejemplo n.º 6
0
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)
Ejemplo n.º 7
0
def _perform_call(callId, request_json, timestamp):
    api_version, callid, function, parameters = parse_and_validate_request(request_json)
    if not function:
        result = {
            CALL_ID: callId,
            API_VERSION: api_version,
            ERROR: "Unknown function call!",
            STATUS: STATUS_FAIL,
            CALL_TIMESTAMP: timestamp}
        return json.dumps(result), result
    azzert(callid == callId)
    result = dict()
    result[CALL_ID] = callid
    result[API_VERSION] = api_version
    result[CALL_TIMESTAMP] = timestamp
    try:
        check_function_metadata(function)
        kwarg_types = get_parameter_types(function)
        kwargs = get_parameters(parameters, kwarg_types)
        for key in set(kwarg_types.keys()) - set(kwargs.keys()):
            kwargs[key] = MISSING
        result[RESULT] = run(function, [], kwargs)
        result[STATUS] = STATUS_SUCCESS
        return json.dumps(result), result
    except Exception, e:
        result[ERROR] = unicode(e)
        result[STATUS] = STATUS_FAIL
        from rogerthat.rpc.service import ServiceApiException, ApiWarning
        if isinstance(e, (ServiceApiException, ApiWarning)):
            loglevel = logging.WARNING
        else:
            loglevel = logging.ERROR
        logging.log(loglevel, "Error while executing %s: %s" % (function.__name__, traceback.format_exc()))
        return json.dumps(result), result
Ejemplo n.º 8
0
def remove_from_order(item_id):
    service_user = users.get_current_user()
    customer = get_customer(service_user)
    azzert(customer)
    customer_store_order_key = Order.create_key(
        customer.id, Order.CUSTOMER_STORE_ORDER_NUMBER)
    order_item_key = OrderItem.create_key(customer.id,
                                          Order.CUSTOMER_STORE_ORDER_NUMBER,
                                          item_id)
    order_item, order = db.get([order_item_key, customer_store_order_key])

    if not order_item:
        logging.warn(
            "Customer %s tried to delete an already deleted item (%s)",
            service_user.email(), item_id)
        return RETURNSTATUS_TO_SUCCESS
    azzert(order)

    # Subtract the price from this product, then remove the product.
    vat = order_item.count * order_item.price * order.vat_pct / 100
    total = order_item.count * order_item.price
    total_inc_vat = total + vat
    order.amount -= total
    order.total_amount -= total_inc_vat
    order.vat -= vat
    order_item.delete()
    order.put()
    return RETURNSTATUS_TO_SUCCESS
Ejemplo n.º 9
0
 def txn():
     m = SolutionOrder.get(order_key)
     azzert(service_user == m.service_user)
     if m.status == SolutionOrder.STATUS_RECEIVED and m.status != order_status:
         m.status = order_status
         m.put()
     return m
Ejemplo n.º 10
0
def get_friend_service_identity_connections_keys_of_app_user_query(app_user):
    app_user_email = app_user.email()
    azzert('/' not in app_user_email, 'no slash expected in %s' % app_user_email)
    qry = db.GqlQuery("SELECT __key__ FROM FriendServiceIdentityConnection"
                      "  WHERE ANCESTOR IS :ancestor AND deleted = False")
    qry.bind(ancestor=parent_key(app_user))
    return qry
Ejemplo n.º 11
0
    def trans():  # Operates on 2 entity groups
        hookup_with_default_services.schedule(mobile_user, ipaddress)
        deferred.defer(sync_payment_database, mobile_user, _transactional=True)

        if invitor_code and invitor_secret:
            pp = ProfilePointer.get(invitor_code)
            if not pp:
                logging.error("User with userCode %s not found!" % invitor_code)
            else:
                deferred.defer(ack_invitation_by_invitation_secret, mobile_user, pp.user, invitor_secret,
                               _transactional=True, _countdown=10)

        elif invitor_code:
            for ysaaa_hash, static_email in chunks(server_settings.ysaaaMapping, 2):
                if invitor_code == ysaaa_hash:
                    service_user = users.User(static_email)
                    makeFriends(service_user, mobile_user, original_invitee=None, servicetag=None, origin=ORIGIN_YSAAA)
                    break
            else:
                azzert(False, u"ysaaa registration received but not found mapping")

        for _, static_email in chunks(server_settings.staticPinCodes, 2):
            if mobile_user.email() == static_email:
                break
        else:
            deferred.defer(send_messages_after_registration, mobile_key, _transactional=True)
Ejemplo n.º 12
0
def get_message_flow_design_keys_by_sub_flow_key(flow_key):
    kind = MessageFlowDesign.kind()
    azzert(flow_key.kind() == kind)
    qry = MessageFlowDesign.gql("WHERE sub_flows = :flow AND ANCESTOR IS :ancestor AND deleted = false")
    qry.bind(flow=flow_key, ancestor=flow_key.parent())
    for mfd in qry.run():
        yield mfd.key()
    def get(self):
        data_dict, app_user = self.get_user_info()
        if not data_dict or not app_user:
            return
        azzert(data_dict['a'] == "unsubscribe broadcast")

        broadcast_type = data_dict['bt']
        si_user = users.User(data_dict['e'])

        _, user_profile, si, fsic = run_in_xg_transaction(self._un_subscribe, app_user, si_user, broadcast_type)

        if fsic or not si:
            message = '%s,<br><br>%s' % (xml_escape(localize(user_profile.language, u'dear_name',
                                                             name=user_profile.name)),
                                         xml_escape(localize(user_profile.language,
                                                             u'successfully_unsubscribed_broadcast_type',
                                                             notification_type=broadcast_type,
                                                             service=si.name if si else data_dict['n'])))
        else:
            language = get_languages_from_request(self.request)[0]
            if not user_profile:
                # User already deactivated his account
                human_user, app_id = get_app_user_tuple(app_user)
                message = localize(language, u'account_already_deactivated',
                                   account=human_user.email(), app_name=get_app_name_by_id(app_id))
            else:
                # User is not connected anymore to this service identity
                message = localize(language, u'account_already_disconnected_from_service',
                                   service_name=si.name)

        jinja_template = self.get_jinja_environment().get_template('unsubscribe_broadcast_type.html')
        self.response.out.write(jinja_template.render(dict(message=message)))
def get_full_language_string(short_language):
    """ Map short language ('en', 'fr') to long language str ('English', 'French (Français)') """
    language = OFFICIALLY_SUPPORTED_ISO_LANGUAGES.get(short_language)
    if language is None:
        language = OFFICIALLY_SUPPORTED_LANGUAGES.get(short_language)
    azzert(language)
    return language
Ejemplo n.º 15
0
 def parse_data(self, email, data):
     user = users.User(email)
     data = base64.decodestring(data)
     data = decrypt(user, data)
     data = json.loads(data)
     azzert(data["d"] == calculate_secure_url_digest(data))
     return data, user
Ejemplo n.º 16
0
def get_app_user_tuple_by_email(app_user_email):
    azzert('/' not in app_user_email, "app_user_email should not contain /")
    if ':' in app_user_email:
        human_user_email, app_id = app_user_email.split(':')
    else:
        human_user_email, app_id = app_user_email, APP_ID_ROGERTHAT
    return users.User(human_user_email), app_id
def run_local_services(app_user, ipaddress, auto_connected_service, service_helper):
    logging.debug("Checking if %s (ip: %s) is in %s for %s",
                  app_user, ipaddress, auto_connected_service.local, auto_connected_service.service_identity_email)

    profile = get_user_profile(app_user)
    if not profile.language:
        logging.info("Can't connect %s to %s. User has no language set.",
                     app_user, auto_connected_service.service_identity_email)
        return

    if profile.country:
        country_code = profile.country
    elif ipaddress:
        country_code = get_country_code_by_ipaddress(ipaddress)
        azzert(country_code)
    else:
        logging.info("Can't connect %s to %s if there is no ip address, and no country in UserProfile.",
                     app_user, auto_connected_service.service_identity_email)
        return

    local_service_map_key = "%s-%s" % (profile.language, country_code.lower())

    if local_service_map_key in auto_connected_service.local:
        deferred.defer(hookup, app_user, auto_connected_service, service_helper, _queue=HIGH_LOAD_WORKER_QUEUE)
    else:
        logging.info("Not connecting to %s. There is no entry for local key %s",
                     auto_connected_service.service_identity_email, local_service_map_key)
 def parse_data(self, email, data):
     user = users.User(email)
     data = base64.decodestring(data)
     data = decrypt(user, data)
     data = json.loads(data)
     azzert(data["d"] == calculate_secure_url_digest(data))
     return data, user
Ejemplo n.º 19
0
def link_stripe_to_customer(customer_id_or_service_email, stripe_token,
                            stripe_token_created, contact_id):
    solution_server_settings = get_solution_server_settings()
    stripe.api_key = solution_server_settings.stripe_secret_key
    if isinstance(customer_id_or_service_email, unicode):
        customer = Customer.get_by_service_email(customer_id_or_service_email)
    else:
        customer = Customer.get_by_id(customer_id_or_service_email)

    # Resellers and their customers should not be able to do this
    google_user = gusers.get_current_user()
    if not customer.team.legal_entity.is_mobicage:
        logging.error(
            "user %s tried to access function 'link_stripe_to_customer'",
            google_user.email())
        raise NoPermissionException()
    if google_user:
        azzert(user_has_permissions_to_team(google_user, customer.team_id))

    if customer.stripe_id:
        stripe_customer = stripe.Customer.retrieve(customer.stripe_id)
        card = stripe_customer.cards.create(card=stripe_token)
        stripe_customer.default_card = card.id
        stripe_customer.save()
    else:
        stripe_customer = stripe.Customer.create(
            card=stripe_token,
            description=u"%s %s -- %s, %s, %s, %s, %s, %s" %
            (customer.id, customer.vat, customer.name, customer.address1,
             customer.address2, customer.zip_code, customer.city,
             customer.country))
        card = stripe_customer.cards.data[0]
    try_or_defer(store_stripe_link_to_datastore, customer.key(),
                 stripe_customer.id, card.id, stripe_token_created, contact_id)
Ejemplo n.º 20
0
    def get(self):
        data_dict, app_user = self.get_user_info()
        if not data_dict or not app_user:
            language = self.request.get("language", DEFAULT_LANGUAGE)
            title = common_translate(language, SOLUTION_COMMON, u'Error')
            text = common_translate(language, SOLUTION_COMMON, u"error-occured-unknown-try-again")
        else:
            azzert(data_dict['a'] == "loyalty_no_mobiles_lottery_winner")
            service_email = data_dict['e']
            service_identity_user = users.User(service_email)
            service_user, service_identity = get_service_identity_tuple(service_identity_user)
            user_profile = db.get(UserProfile.createKey(app_user))
            if user_profile:
                language = self.request.get("language", user_profile.language)
                if redeem_lottery_winner(service_user, service_identity, data_dict['mk'], app_user, user_profile.name):
                    title = common_translate(language, SOLUTION_COMMON, u'Success')
                    text = common_translate(language, SOLUTION_COMMON, u'loyalty-lottery-loot-receive')
                else:
                    title = common_translate(language, SOLUTION_COMMON, u'Error')
                    text = common_translate(language, SOLUTION_COMMON, u'Unfortunately you have not confirmed on time and lost your chance')
            else:
                language = self.request.get("language", DEFAULT_LANGUAGE)
                title = common_translate(language, SOLUTION_COMMON, u'Error')
                text = common_translate(language, SOLUTION_COMMON, u"error-occured-unknown-try-again")

        params = {
            'title': title,
            'text': text
        }

        jinja_template = JINJA_ENVIRONMENT.get_template('pages/loyalty_title_text.html')
        self.response.out.write(jinja_template.render(params))
Ejemplo n.º 21
0
    def trans():
        app = get_app_by_id(app_id)
        azzert(app)

        shop_app = db.get(shop_app_key)
        if not shop_app:
            shop_app = ShopApp(key=shop_app_key)

        shop_app.name = app.name
        shop_app.searched_south_west_bounds.append(db.GeoPt(sw_lat, sw_lon))
        shop_app.searched_north_east_bounds.append(db.GeoPt(ne_lat, ne_lon))
        shop_app.postal_codes = postal_codes
        shop_app.put()

        deferred.defer(_start_building_grid,
                       google_maps_key,
                       app_id,
                       postal_codes,
                       radius,
                       sw_lat,
                       sw_lon,
                       ne_lat,
                       ne_lon,
                       city_name,
                       check_phone_number,
                       _transactional=True,
                       _queue=HIGH_LOAD_WORKER_QUEUE)
Ejemplo n.º 22
0
def get_child_messages(app_user, parent_messages):
    child_messages = list()
    for m in parent_messages:
        azzert(app_user in m.members)
        for key in m.childMessages:
            child_messages.append(key)
    return db.get(child_messages)
Ejemplo n.º 23
0
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
Ejemplo n.º 24
0
def get_friend_service_identity_connections_of_service_identity_keys_query(service_identity_user):
    azzert('/' in service_identity_user.email(), 'no slash in %s' % service_identity_user.email())
    qry = db.GqlQuery("SELECT __key__ FROM FriendServiceIdentityConnection "
                      "WHERE deleted = False AND service_identity_email = :service_identity_email "
                      "ORDER BY friend_name ASC")
    qry.bind(service_identity_email=service_identity_user.email())
    return qry
Ejemplo n.º 25
0
def create_task_if_not_order(customer_id):
    customer = Customer.get_by_id(customer_id)
    # Check if the customer has linked his credit card after he clicked the 'pay' button
    # If he didn't (one hour after the last time he tried to pay), create a new ShopTask to call this customer.
    if not customer.stripe_valid and customer.team_id:
        if customer.prospect_id:
            rmt, prospect = db.get([
                RegioManagerTeam.create_key(customer.team_id),
                Prospect.create_key(customer.prospect_id)
            ])
        else:
            prospect = create_prospect_from_customer(customer)
            rmt = RegioManagerTeam.get(
                RegioManagerTeam.create_key(customer.team_id))
        azzert(rmt.support_manager,
               'No support manager found for team %s' % rmt.name)
        task = create_task(
            prospect_or_key=prospect,
            status=ShopTask.STATUS_NEW,
            task_type=ShopTask.TYPE_SUPPORT_NEEDED,
            address=None,
            created_by=STORE_MANAGER.email(),
            assignee=rmt.support_manager,
            execution_time=today() + 86400 + 11 * 3600,  # tomorrow, 11:00,
            app_id=prospect.app_id,
            comment=u"Customer wanted to pay an order in the customer store, "
            "but didn't succeed because he did not link his creditcard.",
            notify_by_email=True)
        task.put()
Ejemplo n.º 26
0
def update_profile_from_profile_discovery(app_user, discovery):
    azzert(discovery.user == app_user)
    changed_properties = []
    user_profile = get_user_profile(app_user)
    new_name = discovery.name.strip()
    if user_profile.name != new_name:
        changed_properties.append(u"name")
    user_profile.name = new_name

    if discovery.avatar:
        img = images.Image(str(discovery.avatar))
        img.resize(150, 150)
        avatar = get_avatar_by_id(user_profile.avatarId)
        if not avatar:
            avatar = Avatar(user=app_user)
        image = img.execute_transforms(images.PNG, 100)
        avatar.picture = db.Blob(image)
        avatar.put()
        user_profile.avatarId = avatar.key().id()
        _calculateAndSetAvatarHash(user_profile, image)
        changed_properties.append(u"avatar")
    user_profile.version += 1
    user_profile.put()
    update_mobiles(app_user, user_profile)
    update_friends(user_profile, changed_properties)
Ejemplo n.º 27
0
    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.defaultAppId = supported_app_ids[0]
        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)
        deferred.defer(create_default_news_settings, service_user, profile.organizationType, _transactional=True)

        return profile, service_identity, update_result
Ejemplo n.º 28
0
def send_message_for_pharmacy_order(service_user, order_key, order_status, message):
    from solutions.common.bizz.messaging import send_inbox_forwarders_message

    azzert(order_status in SolutionPharmacyOrder.ORDER_STATUSES)

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

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

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

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

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

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

    send_message(service_user, sm_data, service_identity=order.service_identity)
Ejemplo n.º 29
0
def get_app_user_tuple_by_email(app_user_email):
    azzert('/' not in app_user_email, "app_user_email should not contain /")
    if ':' in app_user_email:
        human_user_email, app_id = app_user_email.split(':')
    else:
        from rogerthat.dal import app
        human_user_email, app_id = app_user_email, app.get_default_app().app_id
    return users.User(human_user_email), app_id
def press_menu_item(service, coords, generation, context):
    # generation is service identity menuGeneration
    from rogerthat.bizz.service import press_menu_item as press_menu_item_bizz
    user = users.get_current_user()
    service_identity_user = add_slash_default(users.User(service))
    azzert(get_friend_serviceidentity_connection(user, service_identity_user),
           "%s tried to press menu item of service %s" % (user.email(), service))
    press_menu_item_bizz(user, service_identity_user, coords, context, generation, timestamp=now())
Ejemplo n.º 31
0
 def parse_data(email, data):
     app_user_email = create_app_user_by_email(email).email()
     user = users.User(app_user_email)
     data = base64.decodestring(data)
     data = decrypt(user, data)
     data = json.loads(data)
     azzert(data["d"] == calculate_secure_url_digest(data))
     return data, user
Ejemplo n.º 32
0
def unregister_mobile_success_callback(context, result):
    mobile_key = context.mobile_key
    mobile = get_mobile_by_key(mobile_key)
    current_user = users.get_current_user()
    azzert(mobile.user == current_user)
    azzert(mobile == users.get_current_mobile())
    mobile.status = mobile.status | Mobile.STATUS_UNREGISTERED
    mobile.put()
Ejemplo n.º 33
0
def generate_unsubscribe_broadcast_link(app_user, service_identity_user, service_identity_name, broadcast_type):
    if not broadcast_type:
        return None

    azzert('/' in service_identity_user.email())
    data = dict(n=service_identity_name, e=service_identity_user.email(), t=0, a="unsubscribe broadcast", c=None,
                bt=broadcast_type)
    return generate_user_specific_link('/unsubscribe_broadcast', app_user, data)
def bizz_check(condition, error_message='', error_class=None):
    if not condition:
        from rogerthat.rpc.service import BusinessException
        if error_class is None:
            error_class = BusinessException
        else:
            azzert(issubclass(error_class, BusinessException))
        raise error_class(error_message)
Ejemplo n.º 35
0
def _validate_app_broadcast(service_identity_user, app_ids, message):
    si = get_service_identity(service_identity_user)
    azzert(si)
    for app_id in app_ids:
        azzert(app_id in si.appIds)

    bizz_check(message and message.strip(), 'Message should not be empty')
    return si
Ejemplo n.º 36
0
 def fromFormMessage(fm):
     from rogerthat.models import FormMessage
     azzert(isinstance(fm, FormMessage))
     rm = RootFormMessageTO()
     rm.__dict__.update(WebFormMessageTO.fromMessage(fm).__dict__)
     rm.messages = list()
     rm.message_type = fm.TYPE
     return rm
Ejemplo n.º 37
0
def ackInvitationByInvitationSecret(request):
    from rogerthat.bizz.friends import ack_invitation_by_invitation_secret, get_profile_info_via_user_code
    from rogerthat.rpc import users
    invitee = users.get_current_user()
    profile_info = get_profile_info_via_user_code(request.invitor_code)
    azzert(profile_info, "User with userCode %s not found!" % request.invitor_code)
    try_or_defer(ack_invitation_by_invitation_secret, invitee, profile_info.user, request.secret)
    return AckInvitationByInvitationSecretResponseTO()
Ejemplo n.º 38
0
 def from_string(cls, settings_string):
     to = cls()
     parts = settings_string.split(":")
     part_ip = [int(p) for p in parts[0].split('.')]
     azzert(len(part_ip) == 4)
     to.ip = parts[0].decode('unicode-escape')
     to.port = int(parts[1])
     return to
Ejemplo n.º 39
0
def signup(user, service_name, service_description):
    solution_server_settings = get_solution_server_settings()
    azzert(users.get_current_user() == users.User(
        solution_server_settings.solution_trial_service_email))

    user = users.User(user)
    from rogerthat.bizz.service.yourservicehere import signup as trial_signup
    return trial_signup(user, service_name, service_description, True)
Ejemplo n.º 40
0
 def txn():
     sln_settings = get_solution_settings(service_user)
     m = SolutionGroupPurchase.get_by_id(
         group_purchase_id,
         parent_key_unsafe(service_identity_user, sln_settings.solution))
     azzert(service_user == m.service_user)
     m.deleted = True
     m.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)
Ejemplo n.º 42
0
        def capied(result_f, error_f, profile, *args, **kwargs):
            synchronous = kwargs.get(PERFORM_CALLBACK_SYNCHRONOUS, False)
            if not synchronous:
                _validate_api_callback(result_f, error_f, profile, function, f)
            cc = dict()
            cc["method"] = function

            default_arg_values = f.meta['fargs'].defaults
            if default_arg_values:
                args_with_defaults = f.meta['fargs'].args[-len(default_arg_values):]
                effective_kwargs = dict(zip(args_with_defaults, default_arg_values))
                effective_kwargs.update(kwargs)
            else:
                effective_kwargs = kwargs

            target_mfr = TARGET_MFR in kwargs
            is_solution = bool(profile.solution)

            if code:  # code 0 is test.test
                if target_mfr:
                    if code == ServiceProfile.CALLBACK_MESSAGING_RECEIVED:
                        return
                elif is_solution:
                    if not solution_supports_api_callback(profile.solution, code) and profile.callBackURI == "mobidick":
                        logging.debug('callback %s is not implemented for solution %s', code, profile.user)
                        return
                else:
                    if not profile.callbackEnabled(code):
                        logging.debug('callback %s is not enabled for %s', code, profile.user)
                        return

            cc["params"] = {arg: serialize_value(effective_kwargs[arg], *get_type_details(type_, effective_kwargs[arg]))
                            for arg, type_ in f.meta["kwarg_types"].iteritems()}
            cc["callback_name"] = kwargs.get("callback_name", None)

            now_ = now()
            callId = unicode(uuid.uuid1())
            cc["id"] = callId
            message = json.dumps(cc)
            timestamp = (now_ + SERVICE_API_CALLBACK_RETRY_UNIT) * 1 if profile.enabled else -1
            service_api_callback = ServiceAPICallback(parent_key(profile.user), callId, call=message,
                                                      timestamp=timestamp,
                                                      resultFunction=result_f and result_f.meta[u"mapping"],
                                                      errorFunction=error_f and error_f.meta[u"mapping"],
                                                      targetMFR=target_mfr, monitor=bool(profile.monitor), code=code,
                                                      is_solution=is_solution)
            if 'service_identity' in kwargs:
                azzert(kwargs['service_identity'], 'service_identity should not be None')
                service_api_callback.internal_service_identity = kwargs['service_identity']
            if synchronous:
                return submit_service_api_callback(profile, service_api_callback, effective_kwargs, function,
                                                   synchronous, call_dict=cc, response_type=f.meta[u'return_type'])
            if not DO_NOT_SAVE_RPCCALL_OBJECTS in kwargs:
                service_api_callback.put()
            if profile.enabled or profile.solution or target_mfr or function == "test.test":
                submit_service_api_callback(profile, service_api_callback, effective_kwargs, function, call_dict=cc,
                                            response_type=f.meta[u'return_type'])
            return service_api_callback
Ejemplo n.º 43
0
def _validate_profile_info_types(expected_types, entries):
    if expected_types is None:
        return
    azzert(len(expected_types) == len(entries))
    for expected_type, entry in zip(expected_types, entries):
        if entry is None:
            continue
        azzert(isinstance(entry, expected_type),
               "%s (%s) is not of expected type %s" % (entry.user.email(), entry.__class__.__name__, expected_type))
Ejemplo n.º 44
0
 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
Ejemplo n.º 45
0
def get_epoch_from_datetime(datetime_):
    if isinstance(datetime_, datetime.datetime):
        epoch = datetime.datetime.utcfromtimestamp(0)
    elif isinstance(datetime_, datetime.date):
        epoch = datetime.date.fromtimestamp(0)
    else:
        azzert(
            False,
            "Provided value should be a datetime.datetime or datetime.date instance"
        )
    delta = datetime_ - epoch
    return int(delta.total_seconds())
Ejemplo n.º 46
0
def generate_unassigned_qr_codes_zip_for_app(app_id, amount, mode):
    current_user = gusers.get_current_user()
    if not is_admin(current_user):
        raise NoPermissionException('Generate unassigned QR codes for app')
    if not get_app_by_id(app_id):
        raise AppNotFoundException(app_id)
    if mode == 'svg':
        azzert(amount <= 500)  # for db entity put() limit is about 700
        f = _generate_unassigned_qr_codes_svgs_for_app
    else:
        f = _generate_unassigned_qr_codes_excel_for_app

    deferred.defer(f, app_id, amount, current_user.email())
Ejemplo n.º 47
0
def get_services(organization_type, cursor=None, limit=50):
    city_service_user = users.get_current_user()
    si = system.get_identity()
    # get all the services in this city
    app_id = si.app_ids[0]
    city_customer = get_customer(city_service_user)
    azzert(organization_type in city_customer.editable_organization_types)
    service_customers_qry = Customer.list_enabled_by_organization_type_in_app(app_id, organization_type)
    service_customers_qry.with_cursor(cursor)
    service_customers = service_customers_qry.fetch(limit)
    new_cursor = unicode(service_customers_qry.cursor())

    services = []
    statistics = get_services_statistics(app_id)
    sln_settings_keys = [SolutionSettings.create_key(city_service_user)]
    for customer in service_customers:
        if not customer.service_email:
            logging.error('Customer %d (%s) has default_app_id, but has no service!', customer.id, customer.name)
        elif customer.app_id == app_id:
            sln_settings_keys.append(SolutionSettings.create_key(users.User(customer.service_email)))
    sln_settings_list = db.get(sln_settings_keys)
    city_sln_settings = sln_settings_list.pop(0)  # type: SolutionSettings
    azzert(city_sln_settings.can_edit_services(city_customer))
    city_service_email = city_sln_settings.service_user.email()
    for customer in service_customers:
        service_email = customer.service_email
        # Exclude the city app's own service
        if customer.app_id == app_id and service_email != city_service_email:
            future_events_count = 0
            broadcasts_last_month = 0
            static_content_count = 0
            last_unanswered_question_timestamp = 0
            modules = []
            for sln_settings in sln_settings_list:
                if sln_settings.key().name() == service_email:
                    modules = sln_settings.modules
            if statistics:
                for mail in statistics.customer_emails:
                    if mail == service_email:
                        index = statistics.customer_emails.index(mail)
                        future_events_count = statistics.future_events_count[index]
                        broadcasts_last_month = statistics.broadcasts_last_month[index]
                        static_content_count = statistics.static_content_count[index]
                        last_unanswered_question_timestamp = statistics.last_unanswered_questions_timestamps[index]

            statistic = ServiceStatisticTO.create(future_events_count, broadcasts_last_month, static_content_count,
                                                  last_unanswered_question_timestamp)
            services.append(ServiceListTO(service_email, customer.name, statistic, modules, customer.id))
    generated_on = statistics.generated_on if statistics else None
    return ServicesTO(sorted(services, key=lambda x: x.name.lower()), generated_on, new_cursor)
Ejemplo n.º 48
0
def get_available_apps_for_customer(customer, demo_only=False):
    if not customer:
        return []
    app_ids = (a for a in customer.sorted_app_ids
               if a != App.APP_ID_OSA_LOYALTY)
    available_apps = list(App.get(map(App.create_key, app_ids)))
    azzert(all(available_apps))
    if available_apps[0].orderable_app_ids:
        extra_app_ids = set(available_apps[0].orderable_app_ids).difference(
            customer.sorted_app_ids)
        if extra_app_ids:
            available_apps += App.get(map(App.create_key, extra_app_ids))
    if demo_only:
        available_apps = filter(lambda x: x.demo, available_apps)
    available_apps.sort(key=lambda app: app.name.upper())
    return available_apps
Ejemplo n.º 49
0
def re_index_prospect(prospect):
    index = search.Index(name=PROSPECT_INDEX)
    azzert(prospect, 'Prospect not found')
    try:
        index.delete(prospect.id)
    except ValueError:
        pass

    fields = [
        search.AtomField(name='key', value=prospect.id),
        search.TextField(name='name', value=prospect.name),
        search.TextField(name='address', value=prospect.address),
        search.TextField(name='phone', value=prospect.phone),
        search.TextField(name='email', value=prospect.email)
    ]
    index.put(search.Document(doc_id=prospect.id, fields=fields))
Ejemplo n.º 50
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
Ejemplo n.º 51
0
def search_services(search_string):
    city_service_user = users.get_current_user()
    city_sln_settings = get_solution_settings(city_service_user)
    si = system.get_identity()
    app_id = si.app_ids[0]
    city_customer = get_customer(city_service_user)
    azzert(city_sln_settings.can_edit_services(city_customer))

    customers = []
    # if app id is set, the customer should have a service
    for c in search_customer(search_string, [app_id], None):
        # exclude own service and disabled services
        if c.service_email == city_service_user.email() or c.service_disabled_at:
            continue
        customers.append(CustomerTO.fromCustomerModel(c, False, False))

    return sorted(customers, key=lambda c: c.name.lower())
Ejemplo n.º 52
0
def get_menu_item_qr_url(service_user, category_index, item_index):
    from solutions.common.bizz.messaging import POKE_TAG_MENU_ITEM_IMAGE_UPLOAD
    from solutions.common.bizz.provisioning import put_menu_item_image_upload_flow
    menu = get_restaurant_menu(service_user)
    for category in menu.categories:
        if category.index == category_index:
            item = category.items[item_index]
            if item.qr_url:
                return item.qr_url

            qr_templates = qr.list_templates().templates
            qr_template_id = qr_templates[0].id if qr_templates else None
            tag = {
                u'__rt__.tag': POKE_TAG_MENU_ITEM_IMAGE_UPLOAD,
                u'category_name': category.name,
                u'item_name': item.name,
                u'category_id': category.id,
                u'item_id': item.id
            }

            def create_qr():
                return qr.create(common_translate(
                    get_solution_settings(service_user).main_language,
                    SOLUTION_COMMON,
                    u'upload_menu_item_image',
                    item_name=item.name),
                                 json.dumps(tag),
                                 qr_template_id,
                                 flow=u'Upload image')

            try:
                qr_code = create_qr()
            except MessageFlowNotFoundException:
                sln_setting, main_branding = db.get([
                    SolutionSettings.create_key(service_user),
                    SolutionMainBranding.create_key(service_user)
                ])
                put_menu_item_image_upload_flow(main_branding.branding_key,
                                                sln_setting.main_language)
                qr_code = create_qr()

            item.qr_url = qr_code.image_uri
            menu.put()
            return item.qr_url
    azzert(False)
Ejemplo n.º 53
0
def reply_sandwich_order(service_user, service_identity, sandwich_id, message=unicode):
    from solutions.common.bizz.messaging import send_inbox_forwarders_message

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

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

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

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

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

    send_message(service_user, sm_data, service_identity=sandwich_order.service_identity)
Ejemplo n.º 54
0
def create_task_for_order(customer_team_id, prospect_id, order_number):
    team, prospect = db.get([
        RegioManagerTeam.create_key(customer_team_id),
        Prospect.create_key(prospect_id)
    ])
    azzert(team.support_manager,
           u'No support manager found for team %s' % team.name)
    comment = u'Customer placed a new order: %s' % (order_number)
    task = create_task(
        created_by=STORE_MANAGER.email(),
        prospect_or_key=prospect,
        app_id=prospect.app_id,
        status=ShopTask.STATUS_NEW,
        task_type=ShopTask.TYPE_SUPPORT_NEEDED,
        address=None,
        assignee=team.support_manager,
        comment=comment,
        execution_time=today() + 86400 + 11 * 3600,  # tomorrow at 11:00
        notify_by_email=True)
    task.put()
    broadcast_task_updates([team.support_manager])
Ejemplo n.º 55
0
    def get(self):
        data_dict, app_user = self.get_user_info()
        if not data_dict or not app_user:
            language = self.request.get("language", DEFAULT_LANGUAGE)
            title = common_translate(language, SOLUTION_COMMON, u'Error')
            text = common_translate(language, SOLUTION_COMMON, u"error-occured-unknown-try-again")
        else:
            azzert(data_dict['a'] == "loyalty_no_mobiles_unsubscribe")
            service_name = data_dict['n']
            service_identity_user_email = data_dict['e']

            suls_key = SolutionUserLoyaltySettings.createKey(app_user)
            suls = SolutionUserLoyaltySettings.get(suls_key)
            if not suls:
                suls = SolutionUserLoyaltySettings(key=suls_key)
                suls.reminders_disabled = False
                suls.reminders_disabled_for = []

            if service_identity_user_email not in suls.reminders_disabled_for:
                suls.reminders_disabled_for.append(service_identity_user_email)
                suls.put()

            user_profile = db.get(UserProfile.createKey(app_user))
            if user_profile:
                language = self.request.get("language", user_profile.language)
            else:
                language = self.request.get("language", DEFAULT_LANGUAGE)

            title = common_translate(language, SOLUTION_COMMON, u'You have been unsubscribed')
            text = common_translate(language, SOLUTION_COMMON, u'You will not receive any loyalty updates from "%(name)s" anymore', name=service_name)

        params = {
            'title': title,
            'text': text
        }

        jinja_template = JINJA_ENVIRONMENT.get_template('pages/loyalty_title_text.html')
        self.response.out.write(jinja_template.render(params))
Ejemplo n.º 56
0
def _migrate_models(job, old_models, delete_old_models=True, put_new_models=True):
    azzert(db.is_in_transaction())
    new_models = list()

    for old_model in old_models:
        kwargs = copy_model_properties(old_model)

        # Patch props of (ServiceMenuDef, ServiceInteractionDef), (Broadcast), (ServiceProfile)
        for prop in ['staticFlowKey', 'message_flow', 'editableTranslationSet']:
            old_prop = kwargs.get(prop)
            if old_prop:
                kwargs[prop] = str(_create_new_key(job, db.Key(old_prop)))

        new_model = old_model.__class__(key=_create_new_key(job, old_model.key()),
                                        **kwargs)
        new_models.append(new_model)

    if put_new_models:
        _put_and_invalidate_cache_and_allocate_ids(*new_models)
    if delete_old_models:
        db.delete(old_models)

    return new_models
Ejemplo n.º 57
0
    def get(self):
        app_id = self.request.get("app_id", None)
        azzert(app_id is not None, "app_id is not found")
        logging.debug("GetOSALaucherAppHandler app_id: %s", app_id)

        app = OSALauncherApp.get_by_app_id(app_id)
        if app:
            filename = "%s-%s.apk" % (app.app_id, app.version_code)
            try:
                gae_filename = '%s/oca/launcher/apps/%s.apk' % (
                    ROGERTHAT_ATTACHMENTS_BUCKET, app_id)
                self.response.headers[
                    'Content-Type'] = "application/vnd.android.package-archive"
                self.response.headers['Content-Disposition'] = str(
                    'attachment; filename=%s' % filename)
                with cloudstorage.open(gae_filename, 'r') as gcs_file:
                    self.response.write(gcs_file.read())

            except cloudstorage.errors.NotFoundError:
                logging.warn("GetOSALaucherAppHandler NOT found in gcs")
                self.error(500)
        else:
            self.error(500)
Ejemplo n.º 58
0
def create_app_user_by_email(human_user_email, app_id):
    azzert('/' not in human_user_email,
           "human_user_email should not contain /")
    azzert(':' not in human_user_email,
           "human_user_email should not contain :")
    azzert(app_id, "app_id should not be empty")
    if app_id != APP_ID_ROGERTHAT:
        return users.User(u"%s:%s" % (human_user_email, app_id))
    return users.User(human_user_email)
Ejemplo n.º 59
0
    def post(self):
        app_id = self.request.POST.get("app_id", None)
        azzert(app_id is not None, "app_id is not found")
        azzert(app_id is not "com.mobicage.osa.launcher", "app_id is invalid")

        mobileInfo = self.request.POST.get("mobileInfo", None)
        logging.debug("GetOSALaucherAppsHandler mobileInfo: %s" % mobileInfo)
        azzert(mobileInfo is not None, "mobileInfo is not found")
        mobileInfoJSON = json.loads(mobileInfo)
        mobileInfo = parse_complex_value(MobileInfoTO, mobileInfoJSON, False)

        result = []

        for a in OSALauncherApp.all():
            result.append({"app_id": a.app_id, "version_code": a.version_code})

        r = json.dumps(dict(result=result))
        self.response.out.write(r)
Ejemplo n.º 60
0
def add_all_products(mobicage_entity=None):
    if mobicage_entity:
        azzert(mobicage_entity.is_mobicage)
    else:
        mobicage_entity = get_mobicage_legal_entity()
    mobicage_legal_entity_id = mobicage_entity.key().id()
    to_put = []
    to_put.append(create_beac_product(mobicage_legal_entity_id))
    to_put.append(create_demo_product(mobicage_legal_entity_id))
    to_put.append(create_kfup_product(mobicage_legal_entity_id))
    to_put.append(create_ksup_product(mobicage_legal_entity_id))
    to_put.append(create_kspp_product(mobicage_legal_entity_id))
    to_put.append(create_mssu_product(mobicage_legal_entity_id))
    to_put.append(create_ocap_product(mobicage_legal_entity_id))
    to_put.append(create_msup_product(mobicage_legal_entity_id))
    to_put.append(create_msub_product(mobicage_legal_entity_id))
    to_put.append(create_ssup_product(mobicage_legal_entity_id))
    to_put.append(create_visi_product(mobicage_legal_entity_id))
    to_put.append(create_sszp_product(mobicage_legal_entity_id))
    to_put.append(create_setu_product(mobicage_legal_entity_id))
    to_put.append(create_xtra_product(mobicage_legal_entity_id))
    to_put.append(create_xtrb_product(mobicage_legal_entity_id))
    to_put.append(create_cred_product(mobicage_legal_entity_id))
    to_put.append(create_sjup_product(mobicage_legal_entity_id))
    to_put.append(create_sgup_product(mobicage_legal_entity_id))
    to_put.append(create_sx6m_product(mobicage_legal_entity_id))
    to_put.append(create_sxdm_product(mobicage_legal_entity_id))
    to_put.append(create_posm_product(mobicage_legal_entity_id))
    to_put.append(create_csub_product(mobicage_legal_entity_id))
    to_put.append(create_csux_product(mobicage_legal_entity_id))
    to_put.append(create_loya_product(mobicage_legal_entity_id))
    to_put.append(create_lsup_product(mobicage_legal_entity_id))
    to_put.append(create_klup_product(mobicage_legal_entity_id))
    to_put.append(create_xcty_product(mobicage_legal_entity_id))
    to_put.append(create_a3ct_product(mobicage_legal_entity_id))
    to_put.append(create_ilos_product(mobicage_legal_entity_id))
    to_put.append(create_setx_product(mobicage_legal_entity_id))
    to_put.append(create_bnnr_product(mobicage_legal_entity_id))
    to_put.append(create_updi_product(mobicage_legal_entity_id))
    to_put.append(create_vsdi_product(mobicage_legal_entity_id))
    to_put.append(create_term_product(mobicage_legal_entity_id))
    to_put.append(create_otrm_product(mobicage_legal_entity_id))
    to_put.append(create_kkrt_product(mobicage_legal_entity_id))
    to_put.append(create_subx_product(mobicage_legal_entity_id))
    to_put.append(create_suby_product(mobicage_legal_entity_id))
    to_put.append(create_news_product(mobicage_legal_entity_id))
    to_put.append(create_free_product(mobicage_legal_entity_id))
    to_put.append(create_fcty_product(mobicage_legal_entity_id))
    to_put.append(create_pres_product(mobicage_legal_entity_id))
    to_put.append(create_appl_product(mobicage_legal_entity_id))

    to_put.append(create_kfup_product(ACTIVE_S_LEGAL_ENTITY_ID, 'AS_'))
    to_put.append(
        create_msup_product(ACTIVE_S_LEGAL_ENTITY_ID, 'AS_', default_count=1))
    to_put.append(
        create_msud_product(ACTIVE_S_LEGAL_ENTITY_ID, 'AS_', default_count=1))
    to_put.append(
        create_setu_product(ACTIVE_S_LEGAL_ENTITY_ID, 'AS_', price=7000))
    to_put.append(
        create_setd_product(ACTIVE_S_LEGAL_ENTITY_ID, 'AS_', price=-7000))
    to_put.append(create_xcty_product(ACTIVE_S_LEGAL_ENTITY_ID, 'AS_'))
    to_put.append(create_xctd_product(ACTIVE_S_LEGAL_ENTITY_ID, 'AS_'))

    to_put.append(create_fcty_product(VEDA_LEGAL_ENTITY_ID, 'VEDA_'))
    to_put.append(create_free_product(VEDA_LEGAL_ENTITY_ID, 'VEDA_'))

    to_put.append(create_drc_stud_product())
    to_put.append(create_drc_sb_product())
    to_put.append(create_drc_hefl_product())
    to_put.append(create_drc_corp_product())

    db.put(to_put)