Пример #1
0
def send_email(server, _from, to, subject, html, headers=None):
    conf = get_conf()['email']
    text = strip_html(html)
    test_email = os.environ.get('TEST_EMAIL', None)
    if conf["emails_for_real"] and test_email is None:
        to = [to]
        subject = "{}".format(subject)
    else:

        if test_email:
            to = [test_email]
        else:
            to = conf["debug_emails"]
        subject = "(TESTE) {}".format(subject)
    for _to in to:
        msg = MIMEMultipart('alternative')
        msg['Subject'] = Header(subject, 'utf-8')
        msg['From'] = _from
        msg['To'] = _to
        msg.attach(MIMEText(text, 'plain', 'UTF-8'))
        msg.attach(MIMEText(html, 'html', 'UTF-8'))

        sent = server.sendmail(msg['From'], msg['To'], msg.as_string())

        myprint(  # TODO: add logging
            "Email sent to {} with title \"{}\"".format(
                *map(smart_unicode_with_ignore, [msg['To'], subject])))
    return sent
Пример #2
0
def run_report():
    cli, db = get_conn()
    films = db['films']
    users = db['users']
    now = datetime.now()

    # query = films.find({
    #     "screening.created_at": { "$exists" : False }
    # })

    query = films.find({'screening.updated_at': {'$exists': True}})
    # query = films.find({'screening.user_id': 'kwoicbbJMkKvF6dSR'})
    stop = False
    for film in query:
        # import ipdb; ipdb.set_trace()
        for screening in film.get('screening', []):

            try:
                created_at = screening.get('created_at', None)
                screening_date = screening.get('date', None)
                updated = screening.get('updated_at', None)
                #
                # if not updated:
                #     continue

                # if created_at:
                #     continue
                # if not (screening_date and screening_date >= now):
                #     continue

                user = users.find_one({'_id': screening['user_id']})
                myprint(u";".join([
                    # user and user['_id'],
                    # user and user['profile']['name'],
                    # user and user['emails'][0]['address'],
                    # film['_id'],
                    # film['title'],
                    screening['_id'],
                    str(created_at or ''),
                    str(updated or ''),
                    str(screening_date or ''),
                ]))
                xxx = db.films.update_one(
                    {"screening._id": screening['_id']}, {
                        "$set": {
                            "screening.$.created_at": now,
                            "screening.$.updated_at": now
                        }
                    })
            except:
                pass
Пример #3
0
def filter_and_send_3_days():
    from datetime import datetime
    cli, db = get_conn()
    films = db['films']
    users = db['users']
    # cron take some seconds to call the script so we replace here to 0
    now = datetime.now().replace(second=0, microsecond=0)

    # myprint("DEBUG <= 3, should find ELENA created at 2017-07-04 15:39:07")
    # now = datetime(2017, 7, 5, 15, 35, 0)

    start = now + timedelta(days=1)
    end = start + timedelta(minutes=5)
    query = films.find({"screening.date": {"$gte": start, "$lt": end}})
    myprint(
        "Getting screenings from {:%Y-%m-%d %H:%M:%S} to {:%Y-%m-%d %H:%M:%S}."
        .format(start, end))

    found = 0
    server = None

    for film in query:
        for screening in film['screening']:

            created_at = screening.get('created_at', None)
            screening_date = screening.get('date', None)

            if not created_at or not screening_date:
                continue  # too old screening

            if screening_date and screening_date >= start and screening_date < end:

                delta = screening_date - created_at

                if delta.total_seconds() > T3:
                    continue

                if not server:
                    server = get_smtp_conn()

                ambassador = \
                    users.find_one({"_id": screening['user_id']})

                myprint("{} :: {} :: {}".format(
                    created_at, screening_date,
                    smart_unicode_with_ignore(film['title'])))

                parse_and_send(server=server,
                               _from=const.FROM,
                               to=ambassador['emails'][0]['address'],
                               subject=SUBJECT,
                               template=TPL_NAME.format(3),
                               context={
                                   'ambassador': ambassador,
                                   'movie': film,
                                   'screening': screening
                               })
                found += 1

    myprint("Mails sent: {}".format(found))
Пример #4
0
def filter_and_send():
    from datetime import datetime
    cli, db = get_conn()
    films = db['films']
    users = db['users']
    # cron take some seconds to call the script so we replace here to 0
    now = datetime.now().replace(second=0, microsecond=0)

    # myprint("DEBUG >= 10 dias, should find ELENA created at 2017-08-31 11:49:11")
    # now = datetime(2017, 8, 31, 23, 50, 0)

    # myprint("DEBUG >= 4 e <= 9, should find ELENA created at 2017-09-03 14:03:40")
    # now = datetime(2017, 9, 4, 2, 3, 45)

    # myprint("DEBUG <= 3 dias, should find ELENA created at 2017-07-04 15:39:07")
    # now = datetime(2017, 7, 5, 3, 40)

    end = now - timedelta(hours=12)
    start = end - timedelta(minutes=5)
    query = films.find({"screening.created_at": {"$gte": start, "$lt": end}})
    myprint(
        "Getting screenings from {:%Y-%m-%d %H:%M:%S} to {:%Y-%m-%d %H:%M:%S}."
        .format(start, end))

    found = {'<=3': 0, '>3 and <=9': 0, '>=10': 0}
    server = None

    for film in query:
        for screening in film['screening']:
            created_at = screening.get('created_at', None)
            screening_date = screening.get('date', None)

            if not created_at or not screening_date:
                continue  # too old screening

            if created_at >= start and created_at < end:

                delta = screening_date - created_at

                if delta.total_seconds() <= T9:
                    continue

                days = 10
                found['>=10'] += 1

                myprint(
                    "FOUND => days: {days} :: created: {created_at} :: screening date"
                    ": {screening_date} :: {film}".format(
                        film=smart_unicode_with_ignore(film['title']),
                        created_at=created_at.strftime("%Y-%m-%d %H:%M:%S"),
                        screening_date=screening_date.strftime(
                            "%Y-%m-%d %H:%M:%S"),
                        days=days))

                if not server:
                    server = get_smtp_conn()

                ambassador = \
                    users.find_one({"_id": screening['user_id']})

                parse_and_send(server=server,
                               _from=const.FROM,
                               to=ambassador['emails'][0]['address'],
                               subject=SUBJECT,
                               template=TPL_NAME.format(days),
                               context={
                                   'ambassador': ambassador,
                                   'movie': film,
                                   'screening': screening
                               })

    myprint("Mails sent:")
    for k, v in found.items():
        myprint("{}: {}".format(k, v))
Пример #5
0
def filter_and_send():
    from datetime import datetime
    cli, db = get_conn()
    films = db['films']
    users = db['users']
    # cron take some seconds to call the script so we replace here to 0
    now = datetime.now().replace(second=0, microsecond=0)

    # myprint("DEBUG >= 10 dias, deve pegar ELENA c/ sessão em 2017-09-14 15:00:00")
    # now = datetime(2017, 9, 4, 15, 05)

    end = now + timedelta(days=10)
    start = end - timedelta(minutes=5)
    query = films.find({
        "screening.date": {"$gte": start, "$lt": end}
    })
    myprint(
        "Getting screenings from {:%Y-%m-%d %H:%M:%S} to {:%Y-%m-%d %H:%M:%S}."
        .format(start, end)
    )

    found = 0
    server = None

    for film in query:
        for screening in film['screening']:
            created_at = screening.get('created_at', None)
            screening_date = screening.get('date', None)

            if not created_at or not screening_date:
                continue  # too old screening

            if screening_date >= start and screening_date < end:

                delta = screening_date - created_at
                if delta.total_seconds() < T10:
                    continue

                myprint(
                    "FOUND => days: {days} :: created: {created_at} :: screening date"
                    ": {screening_date} :: {film}".format(
                        film=smart_unicode_with_ignore(film['title']),
                        created_at=created_at.strftime("%Y-%m-%d %H:%M:%S"),
                        screening_date=screening_date.strftime("%Y-%m-%d %H:%M:%S"),
                        days=10
                    )
                )

                if not server:
                    server = get_smtp_conn()

                ambassador = \
                    users.find_one({"_id": screening['user_id']})

                parse_and_send(
                    server=server,
                    _from=const.FROM,
                    to=ambassador['emails'][0]['address'],
                    subject=SUBJECT,
                    template=TPL_NAME,
                    context={
                        'ambassador': ambassador,
                        'movie': film,
                        'screening': screening
                    }
                )

                found += 1

    myprint("Mails sent: {}".format(found))
Пример #6
0
def filter_and_send_9_days():
    from datetime import datetime
    cli, db = get_conn()
    films = db['films']
    # {
    users = db['users']
    # cron take some seconds to call the script so we replace here to 0
    now = datetime.now().replace(second=0, microsecond=0)
    # myprint("DEBUG >= 4 e <= 9, should find ELENA created at 2017-09-03 14:03:40")
    # now = datetime(2017, 9, 5, 14, 0, 0)

    # Dates are in UTC
    # "_id" : "GiWtfWAaDXjNRfjtc",
    # "title" : "Realidade Visceral",
    #     "date" : ISODate("2017-11-02T11:00:00.000Z"),
    #     "created_at" : ISODate("2017-10-26T06:22:12.349Z"),
    #     "user_id" : "io9RPivt6s9TpSMpg",
    #     "_id" : "487852f4b13f70fc87f53281"
    # }

    start = now + timedelta(days=2)
    end = start + timedelta(minutes=5)
    query = films.find({"screening.date": {"$gte": start, "$lt": end}})
    myprint(
        "Getting screenings from {:%Y-%m-%d %H:%M:%S} to {:%Y-%m-%d %H:%M:%S}."
        .format(start, end))

    found = 0
    server = None

    for film in query:
        # if u'Visceral' in film['title']:
        #     print("Now", now)
        #     print("Start", start)
        #     print("End", end)
        for screening in film['screening']:

            created_at = screening.get('created_at', None)
            screening_date = screening.get('date', None)

            if not created_at or not screening_date:
                continue  # too old screening

            if screening_date and screening_date >= start and screening_date < end:

                delta = screening_date - created_at

                if delta.total_seconds() < T4 or delta.total_seconds() > T9:
                    continue

                if not server:
                    server = get_smtp_conn()

                ambassador = \
                    users.find_one({"_id": screening['user_id']})

                myprint("{} :: {} :: {} :: {}".format(
                    created_at, screening_date, ambassador,
                    smart_unicode_with_ignore(film['title'])))

                parse_and_send(server=server,
                               _from=const.FROM,
                               to=ambassador['emails'][0]['address'],
                               subject=SUBJECT,
                               template=TPL_NAME.format(9),
                               context={
                                   'ambassador': ambassador,
                                   'movie': film,
                                   'screening': screening
                               })
                found += 1
    myprint("Mails sent: {}".format(found))