Example #1
0
def import_urls(user, fresh_urls, mark_read):
    group = uuid()
    size = len(fresh_urls)
    for url in fresh_urls:
        async(subscribe_to_imported_url, user, url, mark_read, group=group)
    start = time.time()
    while True:
        # print("Time", time.time() - start, "count", count_group(group))
        if (time.time() - start) > IMPORT_WAIT:
            # print("TIME!")
            break
        if count_group(group) == size:
            # print("COUNT!")
            break
        time.sleep(1)
    import_results = Counter(result_group(group))
    pretty_results = ', '.join("{}: {}".format(*x) for x in import_results.items())
    num_added = import_results['added']
    num_existed = import_results['existed']
    num_errors = import_results['error']
    if num_added:
        async_messages.success(user, "Import complete - you subscribed to {sub} feed{s}.".format(sub=num_added, s=pluralize(num_added)))
    else:
        async_messages.info(user, "Import complete - no new subscriptions were added.")
    if num_existed:
        async_messages.info(user,
                            "You were already subscribed to {sub_exists} imported feed{s}.".format(sub_exists=num_existed, s=pluralize(num_existed)))
    if num_errors:
        async_messages.error(user, "There was an error subscribing to {errors} imported feed{s}.".format(errors=num_errors, s=pluralize(num_errors)))
    logger.info('User %(user)s OPML import complete - %(results)s', {'user': user, 'results': pretty_results})
    delete_group(group, tasks=True)
    return pretty_results
 def test_info(self):
     messages.info(self.user, "Hello")
     self.assertMessageOk(constants.INFO)
Example #3
0
    def check_subscriptions(self):
        """
        Check if subscriptions are still ok.
        If will use data from "available repositories" for the ones that are ok
        and will restrict rights for others
        """
        subs = {sub.repository.full_name: sub for sub in self.subscriptions.all()}
        avails = self.available_repositories_set.all().select_related('repository__owner')

        todo = set(subs.keys())
        downgraded = {}
        upgraded = {}

        # check from repositories officialy available for the user
        for avail in avails:
            name = avail.repository.full_name

            if name not in subs:
                continue

            todo.remove(name)

            sub = subs[name]
            max_right = self.MAX_RIGHT[avail.permission]

            # sub with no rights: upgrade if possible
            if sub.state == SUBSCRIPTION_STATES.NORIGHTS:
                if max_right != SUBSCRIPTION_STATES.NORIGHTS:
                    upgraded[name] = max_right

            # sub with rights but not on the avail: downgrade with no rights
            elif not avail.permission:
                downgraded[name] = SUBSCRIPTION_STATES.NORIGHTS

            # sub rights not in matchinng one for the avail rights: downgrade to max allowed
            elif avail.permission not in self.AUTHORIZED_RIGHTS[sub.state]:
                downgraded[name] = max_right

            # we have sufficient rigts, but try to upgrade them to max allowed
            elif max_right != sub.state:
                upgraded[name] = max_right

        # check subs that are not done (so, not in officially available ones)
        for name in todo:
            sub = subs[name]
            repo = sub.repository

            # repo owner by the user: ensure we have max rights
            if repo.owner_id == self.id:
                if sub.state != SUBSCRIPTION_STATES.ADMIN:
                    upgraded[name] = SUBSCRIPTION_STATES.ADMIN

            # private repo from another owner: it's not in available ones, so no rights anymore
            elif repo.private:
                if sub.state != SUBSCRIPTION_STATES.NORIGHTS:
                    downgraded[name] = SUBSCRIPTION_STATES.NORIGHTS

            # public repo from another: it's not in available ones, so read rights only
            elif sub.state not in (SUBSCRIPTION_STATES.READ, SUBSCRIPTION_STATES.NORIGHTS):
                downgraded[name] = SUBSCRIPTION_STATES.READ

        # continue if changes
        if upgraded or downgraded:
            message_content = []

            # apply changes
            for is_up, dikt in [(True, upgraded), (False, downgraded)]:
                by_state = {}
                for name, state in dikt.items():
                    sub = subs[name]
                    sub.state = state
                    sub.save(update_fields=['state'])
                    by_state.setdefault(sub.get_state_display(), []).append(name)

                # message for this kind: one li by change (change=[up|down]+new-state)
                message_content += ['<li>%s <strong>%s</strong> to: <strong>%s</strong></li>' % (
                                            'upgraded' if is_up else 'downgraded',
                                            ', '.join(repos),
                                            state,
                                        )
                                   for state, repos in by_state.items()]

            # prepare message
            message = 'Some rights have changed:<ul>%s</ul>' % ''.join(message_content)
            messages.info(self, message)

        return upgraded, downgraded
Example #4
0
def initialize_simulation(simulation_id):
    """
    Initialize the simulation (async Celery task).

    -Creates stocks
    -Creates a liquidity manager
    -Initialize the ticker
    -Creates opening transactions

    :param simulation: Simulation object
    :return: None
    """
    simulation = Simulation.objects.get(pk=simulation_id)
    msg_info = ""
    msg_error = ""
    if simulation.teams.count() == 0:
        messages.error(simulation.user, _("You need to select at least one team for the simulation!"))
    else:
        if simulation.simulation_type == Simulation.INTRO or simulation.simulation_type == Simulation.ADVANCED:
            msg_info += _("Initialization of simulation running...") + "<br />"
            # stocks creation
            print("Initialization of simulation running...")
            print("Create generic stocks")
            stocks = create_generic_stocks(simulation.id)
            if stocks > 0:
                msg_info += _("%s stocks were created..." % stocks) + "<br />"
                print("%s stocks created" % stocks)
            else:
                msg_error += _("No stocks were created!") + "<br />"

        elif simulation.simulation_type == Simulation.LIVE or simulation.simulation_type == Simulation.INDEXED:
            if simulation.simulation_type == Simulation.LIVE:
                full_clock = clock_erpsim(simulation.id, full=True)
                ticker = simulation.ticker
                ticker.nb_companies = full_clock['nb_teams']
                ticker.nb_rounds = full_clock['max_rounds']
                ticker.nb_days = full_clock['max_days']
                ticker.save()
                create_generic_stocks(simulation.id)
            else:
                game = create_mssql_simulation(simulation.id)
                ticker = simulation.ticker
                ticker.nb_companies = game['nb_teams']
                ticker.nb_rounds = game['max_rounds']
                ticker.nb_days = game['max_days']
                ticker.save()
                create_generic_stocks(simulation_id, symbols=game['list_of_teams'])

        if simulation.simulation_type in (Simulation.INTRO, Simulation.ADVANCED, Simulation.LIVE, Simulation.INDEXED):
            liquidity_manager = create_liquidity_manager(simulation.id)
            if liquidity_manager:
                msg_info += _("%s was created..." % liquidity_manager.name) + "<br />"
            else:
                msg_error += _("No liquidity manager was created!") + "<br />"

            # initialize ticker
            if simulation.simulation_type == Simulation.INTRO or simulation.simulation_type == Simulation.ADVANCED:
                for stock in simulation.stocks.all():
                    create_company_simulation(simulation.id, stock.id)

            elif simulation.simulation_type == Simulation.LIVE or simulation.simulation_type == Simulation.INDEXED:
                for stock in simulation.stocks.all():
                    create_company_live(simulation.id, stock.id)

            # opening transactions (gives cash and stock to each team)
            print("Process openings...............")
            process_opening_transactions(simulation.id)

            if msg_info != "":
                msg_info += _("Initialization succeeded! You can start running the simulation.")
                messages.info(simulation.user, msg_info)
            if msg_error != "":
                msg_error += _("There were errors during the initialization process!")
                messages.error(simulation.user, msg_error)

        else:
            messages.error(simulation.user, _("Initialization of simulation failed!"))
Example #5
0
def initialize_simulation(simulation_id):
    """
    Initialize the simulation (async Celery task).

    -Creates stocks
    -Creates a liquidity manager
    -Initialize the ticker
    -Creates opening transactions

    :param simulation: Simulation object
    :return: None
    """
    simulation = Simulation.objects.get(pk=simulation_id)
    msg_info = ""
    msg_error = ""
    if simulation.teams.count() == 0:
        messages.error(
            simulation.user,
            _("You need to select at least one team for the simulation!"))
    else:
        if simulation.simulation_type == Simulation.INTRO or simulation.simulation_type == Simulation.ADVANCED:
            msg_info += _("Initialization of simulation running...") + "<br />"
            # stocks creation
            print("Initialization of simulation running...")
            print("Create generic stocks")
            stocks = create_generic_stocks(simulation.id)
            if stocks > 0:
                msg_info += _("%s stocks were created..." % stocks) + "<br />"
                print("%s stocks created" % stocks)
            else:
                msg_error += _("No stocks were created!") + "<br />"

        elif simulation.simulation_type == Simulation.LIVE or simulation.simulation_type == Simulation.INDEXED:
            if simulation.simulation_type == Simulation.LIVE:
                full_clock = clock_erpsim(simulation.id, full=True)
                ticker = simulation.ticker
                ticker.nb_companies = full_clock['nb_teams']
                ticker.nb_rounds = full_clock['max_rounds']
                ticker.nb_days = full_clock['max_days']
                ticker.save()
                create_generic_stocks(simulation.id)
            else:
                game = create_mssql_simulation(simulation.id)
                ticker = simulation.ticker
                ticker.nb_companies = game['nb_teams']
                ticker.nb_rounds = game['max_rounds']
                ticker.nb_days = game['max_days']
                ticker.save()
                create_generic_stocks(simulation_id,
                                      symbols=game['list_of_teams'])

        if simulation.simulation_type in (Simulation.INTRO,
                                          Simulation.ADVANCED, Simulation.LIVE,
                                          Simulation.INDEXED):
            liquidity_manager = create_liquidity_manager(simulation.id)
            if liquidity_manager:
                msg_info += _(
                    "%s was created..." % liquidity_manager.name) + "<br />"
            else:
                msg_error += _("No liquidity manager was created!") + "<br />"

            # initialize ticker
            if simulation.simulation_type == Simulation.INTRO or simulation.simulation_type == Simulation.ADVANCED:
                for stock in simulation.stocks.all():
                    create_company_simulation(simulation.id, stock.id)

            elif simulation.simulation_type == Simulation.LIVE or simulation.simulation_type == Simulation.INDEXED:
                for stock in simulation.stocks.all():
                    create_company_live(simulation.id, stock.id)

            # opening transactions (gives cash and stock to each team)
            print("Process openings...............")
            process_opening_transactions(simulation.id)

            if msg_info != "":
                msg_info += _(
                    "Initialization succeeded! You can start running the simulation."
                )
                messages.info(simulation.user, msg_info)
            if msg_error != "":
                msg_error += _(
                    "There were errors during the initialization process!")
                messages.error(simulation.user, msg_error)

        else:
            messages.error(simulation.user,
                           _("Initialization of simulation failed!"))
 def test_info(self):
     messages.info(self.user, "Hello")
     self.assertMessageOk(constants.INFO)
Example #7
0
    return None


def debug(request, message, extra_tags='', fail_silently=False, async=False):
    """Adds a message with the ``DEBUG`` level."""
    if ASYNC and async:
        messages.debug(_get_user(request), message)
    else:
        add_message(request, constants.DEBUG, message, extra_tags=extra_tags,
                    fail_silently=fail_silently)


def info(request, message, extra_tags='', fail_silently=False, async=False):
    """Adds a message with the ``INFO`` level."""
    if ASYNC and async:
        messages.info(_get_user(request), message)
    else:
        add_message(request, constants.INFO, message, extra_tags=extra_tags,
                    fail_silently=fail_silently)


def success(request, message, extra_tags='', fail_silently=False, async=False):
    """Adds a message with the ``SUCCESS`` level."""
    if ASYNC and async:
        messages.success(_get_user(request), message)
    else:
        add_message(request, constants.SUCCESS, message, extra_tags=extra_tags,
                    fail_silently=fail_silently)


def warning(request, message, extra_tags='', fail_silently=False, async=False):
Example #8
0
def debug(request, message, extra_tags='', fail_silently=False, async=False):
    """Adds a message with the ``DEBUG`` level."""
    if ASYNC and async:
        messages.debug(_get_user(request), message)
    else:
        add_message(request,
                    constants.DEBUG,
                    message,
                    extra_tags=extra_tags,
                    fail_silently=fail_silently)


def info(request, message, extra_tags='', fail_silently=False, async=False):
    """Adds a message with the ``INFO`` level."""
    if ASYNC and async:
        messages.info(_get_user(request), message)
    else:
        add_message(request,
                    constants.INFO,
                    message,
                    extra_tags=extra_tags,
                    fail_silently=fail_silently)


def success(request, message, extra_tags='', fail_silently=False, async=False):
    """Adds a message with the ``SUCCESS`` level."""
    if ASYNC and async:
        messages.success(_get_user(request), message)
    else:
        add_message(request,
                    constants.SUCCESS,