def main():

    # Handle command line arguments
    args = handle_args()

    # Initialize the configuration object
    config = MultiEngineQueryConfig(args)

    # Get a logger instance
    logger = logging.getLogger('logger')

    start_time = time.time()
    logger.info(
        '================ Starting Multi-Engine Query script ================')

    # Start the process
    finished = run_multi_engine_query(config)

    end_time = time.time()
    total = timer(start_time, end_time)
    logger.info(
        '================ Multi-Engine Query script execution completed in {0} ================'
        .format(total))

    # Send the email if finished completely, or if no Connected Engine Appliacnes were found..
    # Otherwise we had no active metris to process, so ignore.
    if finished:
        send_mail(logger, config)
Ejemplo n.º 2
0
    def close_spider(self, spider):
        sesh = spider.sesh
        lvrs = sesh.query(spider.Leaver).filter_by(track_detail='Yes').all()
        today = datetime.date.today()
        checked = []
        changed = []
        for l in lvrs:
            timestamp = l.track_lst_update
            date = timestamp.date()
            if date == today:
                checked.append(l)
            print('>>Scoring Firm/Role Match Using Name Match Function')
            role_ratio = score_name(l.lrole, l.track_role)
            firm_ratio = score_name(l.lfirm, l.track_firm)
            if role_ratio < 40 or firm_raio < 40:
                changed.append(l)

        if len(changed) > 0:
            html2 = htmldos(changed)
            resp_code2 = send_mail(html2)
            print(resp_code2)
        if len(checked) > 0:
            html = gen_html(checked)
            resp_code = send_mail(html)
            print(resp_code)
Ejemplo n.º 3
0
def checkout():
    if request.method == 'POST':
        if request.form['type'] == 'visitor':
            visitor = db.session.query(Visitor).filter_by(
                uuid_code=request.form['uuid_code']).one()
            if visitor is None:
                flash('No such visitor with a uuid {}'.format(
                    request.form['uuid_code']))
            elif visitor.check_out is None:
                visitor.check_out = datetime.datetime.now()
                db.session.commit()
                to_emails = visitor.email
                subject = 'Visit Details'
                content = "Name: {}\n".format(str(visitor.name)) +  "Phone: {}\n".format(str(visitor.phone)) + \
                        "Checkin Time: {}\n".format(str(visitor.check_in.strftime("%b %d %Y %H:%M:%S"))) + \
                        "Checkout Time: {}\n".format((visitor.check_out.strftime("%b %d %Y %H:%M:%S"))) + "Address: {}\n".format(address) + "Host Name: {}".format(visitor.host.name)
                send_mail(to_emails, subject, content)
                flash('Visitor ID {} has successfully checked out'.format(
                    visitor.uuid_code))
            else:
                flash('The visitor/host has already checked out.')
        elif request.form['type'] == 'host':
            host = db.session.query(Host).filter_by(
                uuid_code=request.form['uuid_code']).one()
            host.check_out = datetime.datetime.now()
            db.session.commit()
            flash('Host ID {} has successfully checked out'.format(
                host.uuid_code))

    return render_template('forms/checkout.html')
Ejemplo n.º 4
0
    def close_spider(self, spider):
        sesh = spider.sesh
        tracking = sesh.query(spider.Leaver).filter_by(result='Tracking').all()
        today = datetime.date.today()
        checked = []
        changed = []
        for t in tracking:
            print('>>>>>>>', t.name)
            timestamp = t.lasttracked.date()
            if timestamp == today:
                checked.append(t)

            role_score = compare_score(t.leaverrole, t.trackrole)
            if role_score == 'No Data':
                print('Role Has no Data to Compare')
            elif role_score == 'Update':
                print(
                    '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Change Detected: %s and %s'
                    % (t.leaverrole, t.trackrole))
                changed.append(track_alert(t, sesh))
            elif role_score < 50:
                print(
                    '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Change Detected: %s and %s'
                    % (t.leaverrole, t.trackrole))
                changed.append(track_alert(t, sesh))
            else:
                print('No Change to Role')

            firm_score = compare_score(t.leaverfirm, t.trackfirm)
            if firm_score == 'No Data':
                print('Firm Has no Data to Compare')
            elif firm_score == 'Update':
                print(
                    '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Change Detected: %s and %s'
                    % (t.leaverfirm, t.trackfirm))
                changed.append(track_alert(t, sesh))
            elif firm_score < 50:
                print(
                    '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Change Detected: %s and %s'
                    % (t.leaverfirm, t.trackfirm))
                changed.append(track_alert(t, sesh))
            else:
                print('>>No Change to Firm')

        try:
            if len(changed) > 0:
                html2 = htmldos(changed)
                resp_code2 = send_mail(html2)
                print(resp_code2)
            if len(checked) > 0:
                html = gen_html(checked)
                resp_code = send_mail(html)
                print(resp_code)
        except:
            print('Emails Not Sent')
Ejemplo n.º 5
0
def schedule_card_end_time(card_id):
    from database.models import Card
    try:
        card = Card.objects.get(id=card_id)
    except DoesNotExist:
        return

    if not card.planned_end_time:
        return

    if now() > card.planned_end_time.replace(tzinfo=utc):
        send_mail("Please end card")
Ejemplo n.º 6
0
def check_for_expirations(request):
    for user in User.objects.all():
        if Subscription.objects.filter(user=user):
            subscription = Subscription.objects.get(user=user)
            days_diff = subscription.get_days_diff()
            if days_diff <= settings.SUBSCRIPTION_NOTIFICATION_DAYS:
                notification, created = \
                    Notification.objects.get_or_create(user=user, content=settings.SUBSCRIPTION_NOTIFICATION_CONTENT)
                if not notification.was_sent:
                    send_mail(settings.SUBSCRIPTION_NOTIFICATION_TOPIC, notification.content, user.email)
                    notification.was_sent = True
                    notification.save()
    return HttpResponse("OK")
Ejemplo n.º 7
0
def main():
    CONFIG = json.load(open('config.json'))

    deadline = parser.parse(CONFIG['DEADLINE'])
    difference = (deadline.date() - dt.date.today()).days

    if difference <= 7:
        body = (f"""
                {difference} {pluralize('day', difference)} left -> '{CONFIG['DEADLINE_DESC']}'.
                Sent by {os.path.basename(__file__)}.
            """)
        email = create_email('Reminder', CONFIG['EMAIL'], CONFIG['EMAIL'],
                             body)
        send_mail(email, CONFIG['EMAIL'], CONFIG['PASSWORD'])
Ejemplo n.º 8
0
def send(request):
    if request.method == "POST":
        send_mail(f"{request.user.username}@devwithme.xyz",
                  request.POST["receiver"], request.POST["subject"],
                  request.POST["body"])

        Email(timestamp=str(current_milli_time()),
              subject=request.POST["subject"],
              body=request.POST["body"],
              from_email=f"{request.user.username}@devwithme.xyz",
              to_email=request.POST["receiver"]).save()

        return HttpResponse("Sent successfully!")

    else:
        return render(request, "dashboard/send.html")
Ejemplo n.º 9
0
def verification_link(user, email):
    Verification(user_id=user.id).save()

    try:
        v = Verification.objects.get(user_id=user.id)
    except Verification.MultipleObjectsReturned:
        v = Verification.objects.filter(user_id=user.id)[::-1][0]

    domain = Site.objects.get_current().domain
    if domain == "example.com":
        domain = "127.0.0.1:8000"

    send_mail(
        email, "Email Verify",
        f"Please click this <a href='http://{domain}/auth/verify/{v.code}'>link</a> to verify your account"
    )
Ejemplo n.º 10
0
def show_me_the_money(sender, **kwargs):
    email_topic = settings.SUBSCRIPTION_EMAIL_TOPIC
    email_content = settings.SUBSCRIPTION_EMAIL_CONTENT
    ipn_obj = sender
    print "custom: " + str(ipn_obj.custom)
    custom_dict = json.loads(ipn_obj.custom)
    print "dict: " + str(custom_dict)
    try:
        user = User.objects.get(id=custom_dict['user_id'])
        promo_code_id = custom_dict['promo_code_id']
        price = custom_dict['price']
        promo_code = None
        if promo_code_id > -1:
            promo_code = PromotionCode.objects.get(id=promo_code_id)
        if promo_code:
            if not promo_code.is_valid():
                return
            else:
                Payment.objects.create(promotion_code=promo_code, subscription_package_name=ipn_obj.item_name,
                                       price=price, user=user)
                promo_code.used = True
                promo_code.save()
                for user_code in UserCode.objects.filter(user=user):
                    user_code.delete()
        else:
            Payment.objects.create(subscription_package_name=ipn_obj.item_name, price=price, user=user)
        sub_pckg = SubscriptionPackage.objects.get(name=ipn_obj.item_name)
        subscription, created = Subscription.objects.get_or_create(user=user)
        if subscription.get_days_diff() < 0:
            subscription.expiration_date = datetime.now()
        subscription.expiration_date += timedelta(days=sub_pckg.days)
        subscription.save()
        email_recipient = user.email
        email_content %= sub_pckg.days
        send_mail(email_topic, email_content, email_recipient)
        notification, created = Notification.objects.get_or_create(user=user,
                                                                   content=settings.SUBSCRIPTION_NOTIFICATION_CONTENT)
        notification.was_sent = False
        notification.save()
        notification, created = Notification.objects.get_or_create(user=user,
                                                                   content=settings.NOTIFICATION_SUBSCRIPTION_ENDED)
        notification.was_sent = False
        notification.save()
    except Exception, e:
        print __file__, 1, 'Blad przy przypisywaniu subskrypcji'
        print "blad: " + str(e)
Ejemplo n.º 11
0
def checkin_visitor():
    if request.method == 'POST':
        try:
            visitor = Visitor(name=request.form['name'],
                              email=request.form['email'],
                              phone=request.form['phone'],
                              check_in=datetime.datetime.now())
            host = db.session.query(Host).get(request.form['host_name'])
            visitor.host = host
            db.session.add(visitor)
            db.session.commit()
        except exc.IntegrityError as e:
            flash('An error has occurred. Please try again.')

        # send sms to host
        client = Client(os.getenv('account_sid'), os.getenv('auth_token'))
        message = client.messages \
                .create(
                     body='A new visitor has checked in. Details: {0}\n{1}\n{2}\n{3}'.format(
                         request.form['name'], request.form['email'], host.phone,
                         visitor.check_in.strftime("%b %d %Y %H:%M:%S")
                     ),
                     from_=from_phone,
                     to=host.phone
                 )
        # send sms to client for checkout code(id)
        message = client.messages \
                .create(
                     body='Greetings Visitor. Here\'s your checkout code. Have a great day!: {0}'.format(visitor.id) ,from_=from_phone, to=request.form['phone'])
        # send email to host
        to_emails = request.form['email']
        subject = 'New Visitor Alert'
        html_content = 'A new visitor has checked in. Details: {0}\n{1}\n{2}\n{3}'.format(
            request.form['name'], request.form['email'], request.form['phone'],
            visitor.check_in.strftime("%b %d %Y %H:%M:%S"))
        send_mail(to_emails, subject, html_content)

    hosts = db.session.query(Host).filter_by(check_out=None).all()
    return render_template('forms/visitor.html', hosts=hosts)
Ejemplo n.º 12
0
def forgot_password_request(request):
    if request.method == "POST":
        email = request.POST["email"]
        user = User.objects.get(email=email)

        ForgotPassword(user_id=user.id).save()
        fp = ForgotPassword.objects.filter(user_id=user.id)[::-1][0]

        code = fp.code

        domain = Site.objects.get_current().domain
        if domain == "example.com":
            domain = "127.0.0.1:8000"

        send_mail(
            email, "Forgot Password",
            f"Please click this <a href='http://{domain}/auth/forgot-password/{code}'>link</a> to reset your password"
        )

        return render(request, "authentication/success.html",
                      {"message": "Check your email for instruction!"})

    else:
        return render(request, "authentication/forgot-password.html")
Ejemplo n.º 13
0
 def close_spider(self, spider):
     sesh = spider.sesh
     susps = sesh.query(spider.Suspect).filter_by(result=None).all()
     today = datetime.date.today()
     added = []
     for s in susps:
         try:
             when = s.datetimeadded
             date = when.date()
             if date == today:
                 added.append(s)
         except:
             pass
     if len(added) > 0:
         try:
             html = gen_html(added)
             resp_code = send_mail(html)
             print(resp_code)
         except:
             pass
Ejemplo n.º 14
0
def sendmail_sample(session):
    """Send email from authenticated user.

    session = requests.Session() instance with a valid access token for
              Microsoft Graph in its default HTTP headers

    This sample retrieves the user's profile photo, uploads it to OneDrive,
    creates a view-only sharing link for the photo, and sends an email
    with the photo attached.

    The code in this function includes many print statements to provide
    information about which endpoints are being called and the status and
    size of Microsoft Graph responses. This information is helpful for
    understanding how the sample works with Graph, but would not be included
    in a typical production application.
    """

    print('\nGet user profile ---------> https://graph.microsoft.com/beta/me')
    user_profile = session.get(api_endpoint('me'))
    print(28*' ' + f'<Response [{user_profile.status_code}]>', f'bytes returned: {len(user_profile.text)}\n')
    if not user_profile.ok:
        pprint.pprint(user_profile.json()) # display error
        return
    user_data = user_profile.json()
    email = user_data['mail']
    display_name = user_data['displayName']

    print(f'Your name ----------------> {display_name}')
    print(f'Your email ---------------> {email}')
    email_to = input(f'Send-to (ENTER=self) -----> ') or email

    print('\nGet profile photo --------> https://graph.microsoft.com/beta/me/photo/$value')
    photo, photo_status_code, _, profile_pic = profile_photo(session, save_as='me')
    print(28*' ' + f'<Response [{photo_status_code}]>',
          f'bytes returned: {len(photo)}, saved as: {profile_pic}')
    if not 200 <= photo_status_code <= 299:
        return

    print(f'Upload to OneDrive ------->',
          f'https://graph.microsoft.com/beta/me/drive/root/children/{profile_pic}/content')
    upload_response = upload_file(session, filename=profile_pic)
    print(28*' ' + f'<Response [{upload_response.status_code}]>')
    if not upload_response.ok:
        pprint.pprint(upload_response.json()) # show error message
        return

    print('Create sharing link ------>',
          'https://graph.microsoft.com/beta/me/drive/items/{id}/createLink')
    response, link_url = sharing_link(session, item_id=upload_response.json()['id'])
    print(28*' ' + f'<Response [{response.status_code}]>',
          f'bytes returned: {len(response.text)}')
    if not response.ok:
        pprint.pprint(response.json()) # show error message
        return

    print('Send mail ---------------->',
          'https://graph.microsoft.com/beta/me/microsoft.graph.sendMail')
    with open('email.html') as template_file:
        template = template_file.read().format(name=display_name, link_url=link_url)

    send_response = send_mail(session=session,
                              subject='email from Microsoft Graph console app',
                              recipients=email_to.split(';'),
                              body=template,
                              attachments=[profile_pic])
    print(28*' ' + f'<Response [{send_response.status_code}]>')
    if not send_response.ok:
        pprint.pprint(send_response.json()) # show error message
Ejemplo n.º 15
0
		os.makedirs(directory)

	failed_categories = []
	try:
		categories_to_scrape = analytics.calc_categories_to_scrape()
		print 'Scraping Queue:'
		for line in categories_to_scrape:
			category_url = line[0]
			print category_url
		for line in categories_to_scrape:
			category_url = line[0]
			start_rank = line[1]
			status, category = rankpage.process_category(category_url, start_rank)
			if status:
				print category + ' successfully scraped!'
				helpers.send_mail(category + ' successfully scraped!')
			else:
				print category + ' scrape failed!'
				helpers.send_mail(category + ' scrape failed!')
				failed_categories.append(category_url)
		analytics.run_analytics()
		analytics.create_report()
	except Exception, e:
		print "AMZN_Scrape Crashed!!!"
		email_message = "At " + unicode(datetime.datetime.now()) + " AMZN_Scrape \
		crashed:" + '\n' + unicode(e) + '\n' + unicode(traceback.print_exc()) + \
		'\n'
		helpers.send_mail(email_message, "AMZN_Scrape Crashed!!!")
		helpers.log("AMZN_Scrape Crashed!!!")
		helpers.log(e)
		helpers.log(traceback.print_exc())
            danger_hosts['mem_percentage'].append(mem_percentage)

#------------------CPU Utilization-------------------
    count_cpu_list = getkeycpu(i_hits)
    for count_cpu in count_cpu_list:
        sys1 = i_hits[count_cpu]['_source']['system']
        cpu_percentage = sys1['cpu']['total']['pct'] * 100
        cpu_host_name = i_hits[count_cpu]['_source']['beat']['hostname']
        if cpu_percentage > threshold_val_cpu:
            danger_hosts['cpu_hostname'].append(cpu_host_name)
            danger_hosts['cpu_percentage'].append(cpu_percentage)

#------------------Disk Utilization-------------------
    count_disk_list = getkeyfilesystem(i_hits)
    for count_disk in count_disk_list:
        sys1 = i_hits[count_disk]['_source']['system']
        disk_percentage = sys1['filesystem']['used']['pct'] * 100
        disk_host_name = i_hits[count_disk]['_source']['beat']['hostname']
        if disk_percentage > threshold_val_disk:
            danger_hosts['disk_hostname'].append(disk_host_name)
            danger_hosts['disk_percentage'].append(disk_percentage)

    # Condition to check if their are any entries in the dictionary , if yes send alert through mail
    if len(danger_hosts) > 0:
        print(danger_hosts)
        if danger_hosts['mem_hostname'] or danger_hosts[
                'cpu_hostname'] or danger_hosts['disk_hostname'] != []:
            ret_code = send_mail(danger_hosts)
        sleep(3600)
        # Loops after every hour