Sindbad~EG File Manager

Current Path : /home/numerotech/aiosgreedingsmail.urbanedge.co.in/aios_birthday/core/controller/
Upload File :
Current File : //home/numerotech/aiosgreedingsmail.urbanedge.co.in/aios_birthday/core/controller/UserController.py

from flask import Flask, request, Blueprint, jsonify, redirect, url_for,flash, render_template,render_template_string
from core.model.User_details import User_details
from random import randint
import datetime
from datetime import timedelta,date,datetime

import requests, mandrill, json
from .. import Helper
from datetime import timedelta
from flask import session, app
import ast
from core import app

# from flask_apscheduler import APScheduler
from flask import Response, stream_with_context
import flask
from jinja2 import Environment, FileSystemLoader, select_autoescape
import os
import shutil

import pathlib
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
import random

from core.library.sms import SMS
from core.library.email import EMAIL
import pytz

app = Blueprint('user', __name__)

# scheduler = APScheduler()

UTC = pytz.utc
IST = pytz.timezone('Asia/Kolkata')
datetime_ist = datetime.now()

	
@app.route('/', methods = ["GET"])
def Home():
	return render_template('aios/home_page.html')


@app.route('/test_sms', methods = ["GET"])
def TestSMS():
	mobile = "8637643225"
	msg = "Hi this is test sms from flask application for testing usage"
	sendsms = SMS().Send(mobile,msg)
	return  "Success"

@app.route('/send_mail_index' , methods = ["GET"])
def Send_mail_index():
	mailindex = User_details().send_mail_history()
	return render_template('aios/send_mail_index.html',mailindex = mailindex)


@app.route('/mailto_officebearers' , methods = ["GET"])
def Mailto_officebearers():
	now = datetime.now()
	datetime_ist = datetime.now()
	hour_str_fomat = datetime_ist.strftime('%H')
	min_str_fomat = datetime_ist.strftime('%M')
	min_int = int(min_str_fomat)
	today_dt_1 = datetime_ist.strftime("%Y-%m-%d %H:%M")
	hour_minutes_str = datetime_ist.strftime('%H:%M')
	# return datetime_ist.strftime("%Y-%m-%d %H:%M")
	# hour_str_fomat = now.strftime("%H")
	# local test
	# if hour_str_fomat == "16" and min_int < 58 : # this code is worng just sampl for you please change to correct code and comper to 6 o'clock with indian current time 
	# live code
	if hour_str_fomat == "06"  and min_int < 28 : # this code is worng just sampl for you please change to correct code and comper to 6 o'clock with indian current time 
		print(today_dt_1 +  " :  Office Bearers - Time match .Time now is  "  +  hour_str_fomat + " and time is " + hour_minutes_str)
		dt_string        = now.strftime("%Y-%m-%d %H:%M")
		dt_string_format = now.strftime("%m-%d")
	
		mon_date         = now.strftime("%B ,%d") 
		next_day         = now + timedelta(days=1)
		next_day_str     = next_day.strftime("%m-%d")
	
		today_birthday_members   = User_details().get_testuser(dt_string_format)
		nextday_birthday_members = User_details().get_testuser(next_day_str)

		wa_to_con = {}
		office_bearers = User_details().get_office_bearers()
		print("yes comming...",office_bearers)
		for office_bearer in office_bearers:
			name     = office_bearer["office_bearer_name"]
			email    = office_bearer["office_beared_email"]
			mobile   = office_bearer["office_bearer_mobile"]

			wa_content_today = office_bearer["wa_content_today"]
			wa_content_trw   = office_bearer["wa_content_trw"]
			wa_to_con["OFF_BEAR_NAME"] = name
			
			if today_birthday_members and len(today_birthday_members) > 0 :
				for index,value in enumerate(today_birthday_members):
					mem_prefix   = value["prefix"]
					mem_name_1   = value["full_name"]
					mem_name     = mem_prefix+" "+mem_name_1 if mem_prefix else mem_name_1
					mem_email  = value["email"]
					mem_mobile = value["mobile"]
					prefix     = value["prefix"]
					prefix     = value["prefix"]
					wa_to_con["MEM_NAME"]   = mem_name
					wa_to_con["MEM_EMAIL"]  = mem_email
					wa_to_con["MEM_MOBILE"] = mem_mobile
					if mem_mobile :
						data_today = Helper.merge_tags(wa_content_today,wa_to_con)
						value["wa_content_today"] = data_today


			if nextday_birthday_members and len(nextday_birthday_members) > 0 :
				for index,value in enumerate(nextday_birthday_members):
					mem_prefix   = value["prefix"]
					mem_name_1   = value["full_name"]
					mem_name     = mem_prefix+" "+mem_name_1 if mem_prefix else mem_name_1
					
					mem_email  = value["email"]
					mem_mobile = value["mobile"]
					wa_to_con["MEM_NAME"]   = mem_name
					wa_to_con["MEM_EMAIL"]  = mem_email
					wa_to_con["MEM_MOBILE"] = mem_mobile
					if mem_mobile :
						data_tom = Helper.merge_tags(wa_content_trw,wa_to_con)
						value["wa_content_trw"] = data_tom



			subject  = "AIOS Members Birthday on  " + " " + mon_date 
			file_na = "office_bearers_mail_3.html"
			html1 = render_template('aios/aios_email_two/'+file_na, today_birthday_members = today_birthday_members,nextday_birthday_members = nextday_birthday_members,name=name,office_bearer=office_bearer)
			# EMAIL.sendMail(subject,html1,email)
			# email = 'santhosh@numerotec.com'
			url = 'https://api.mailgun.net/v3/aios-online.com/messages'
			auth = ('api', 'key-e13725db7c3a95b679911c038b490db1')
			data = {
				'from': 'AIOS Members Birthday Digest <support@aios-online.com>',
				'to': [email],
				'cc' : [],
				# 'cc' : [],
				'bcc' : ['aiosbackup@gmail.com'],
				'subject': subject,
				'html': html1
			}
			
			data['h:Reply-To']="<chairmanscientificcommittee@aios.org>"  # <------------- HERE!
			res = requests.post(url, auth=auth, data=data)
			
		return "Mail sent success"
			
# 	if hour_str_fomat == "05"  and min_int > 25 : # this code is worng just sampl for you please change to correct code and comper to 8 o'clock with indian current time 
		# print(today_dt_1 +  " :  Office Bearers - Time match .Time now is  "  +  hour_str_fomat + " and time is " + hour_minutes_str)
# 		dt_string        = now.strftime("%Y-%m-%d %H:%M")
# 		dt_string_format = now.strftime("%m-%d")
	
# 		mon_date         = now.strftime("%B ,%d") 
# 		next_day         = now + timedelta(days=1)
# 		next_day_str     = next_day.strftime("%m-%d")
		# start
# 		today_birthday_members   = User_details().get_testuser(dt_string_format)
# 		nextday_birthday_members = User_details().get_testuser(next_day_str)
	
# 		name     = "Chitra Ramamurthy"
# 		email    = "chairmanarc@aios.org"
# 		mobile   = "9443317792"
# 		subject  = "AIOS Members Birthday on " + " " + mon_date 

# 		file_na = "office_bearers_mail_3.html"
# 		html1 = render_template('aios/aios_email_two/'+file_na, today_birthday_members = today_birthday_members,nextday_birthday_members = nextday_birthday_members,name=name)
		# EMAIL.sendMail(subject,html1,email) # Comments on May 23, 2023
		# end
		## send mail using mail gun
# 		print("...................",email)
		# url = 'https://api.mailgun.net/v3/aios-online.com/messages'
		# auth = ('api', 'key-e13725db7c3a95b679911c038b490db1')
		# data = {
		# 	'from': 'Dr.Namrata Sharma,  Hon. Gen. Secretary, AIOS <support@aios-online.com>',
		# 	'to': [email],
		# 	'bcc' : ['sai@numerotec.com','aiosbackup@gmail.com'],
		# 	'subject': subject,
		# 	'html': html1
		# }
		# data['h:Reply-To']="AIOS Secretary <secretary@aios.org>"  # <------------- HERE!
		# res = requests.post(url, auth=auth, data=data)	
			
		# mail to dr.santhosh honavar at 6:00 clock
	if hour_str_fomat == "06"  and min_int < 29 : # this code is worng just sampl for you please change to correct code and comper to 8 o'clock with indian current time 
		print(today_dt_1 +  " :  Office Bearers - Time match .Time now is  "  +  hour_str_fomat + " and time is " + hour_minutes_str)
		dt_string        = now.strftime("%Y-%m-%d %H:%M")
		dt_string_format = now.strftime("%m-%d")
	
		mon_date         = now.strftime("%B ,%d") 
		next_day         = now + timedelta(days=1)
		next_day_str     = next_day.strftime("%m-%d")
		# start
# 		today_birthday_members   = User_details().get_testuser(dt_string_format)
# 		nextday_birthday_members = User_details().get_testuser(next_day_str)
	
# 		name     = "Santhosh G. Honavar"
# 		email    = "santosh.honavar@gmail.com"
# 		mobile   = "9848304001"
# 		subject  = "AIOS Members Birthday on " + " " + mon_date 

# 		file_na = "office_bearers_mail_3.html"
# 		html1 = render_template('aios/aios_email_two/'+file_na, today_birthday_members = today_birthday_members,nextday_birthday_members = nextday_birthday_members,name=name)
		# EMAIL.sendMail(subject,html1,email) # Comments on May 23, 2023
		# end
		
		### send mail using mail gun
# 		url = 'https://api.mailgun.net/v3/aios-online.com/messages'
# 		auth = ('api', 'key-e13725db7c3a95b679911c038b490db1')
# 		data = {
# 			'from': 'Dr.Namrata Sharma,  Hon. Gen. Secretary, AIOS <support@aios-online.com>',
# 			'to': [email],
# 			'bcc' : ['sai@numerotec.com','aiosbackup@gmail.com'],
# 			'subject': subject,
# 			'html': html1
# 		}
# 		data['h:Reply-To']="AIOS Secretary <secretary@aios.org>"  # <------------- HERE!
# 		res = requests.post(url, auth=auth, data=data)	
		# end

			# EMAIL.sendMail(subject,html1,email)
			
# 		flash("Mail sent to Office Bearers")	
		return "Mail sent success"
	else:
		# print("Office Bearers - Time not match .Time now is  "  +  hour_str_fomat + " and time is " + hour_minutes_str)
		return  "time no match"
			

@app.route('/today_birthday_members' , methods = ["GET"])
def Today_birthday_membesrs():
	now = datetime.now()
	dt_string_format = now.strftime("%m-%d")
	test_users= User_details().get_testuser(dt_string_format)
	if test_users:
		return render_template('aios/today_birthday_index.html',users = test_users)
	else :
		flash("Today Birthday list is nothing .")
		return redirect(request.referrer)

			

@app.route('/office_bearers_index' , methods = ["GET"])
def Office_bearers_index():
	office_bearers = User_details().get_office_bearers()
	if office_bearers:
		# json_data = json.dumps(office_bearers,default =str)
		# return json_data
		return render_template('aios/office_bearers_index.html',office_bearers = office_bearers)
	else:
		flash("No data available .")
		return redirect(request.referrer)


@app.route('/post_send_mail', methods = ["POST"])
def Post_send_mail():
	if request.method == "POST":
		now = datetime.now()
		dt_string = datetime_ist.strftime("%Y-%m-%d %H:%M")
		
		mon_date         = now.strftime("%B ,%d")

		# fetching data from form..
		test_user_ids = request.form.getlist('test_user_id')
		length_of_ids = len(test_user_ids)
		template_name_list= [] 
		if length_of_ids == 0:
			flash("Please select atleast one member")
			return redirect (url_for('user.Today_birthday_membesrs'))
		else :
			templatess = User_details().send_mail_template_html()
			for row in templatess:
				
				filename = row["template_name"]
				template_name_list.append(filename)
				
			for i in test_user_ids:
				user_id = i
				get_testuser = User_details().get_testuser_byid(user_id)
				name_1 = get_testuser['full_name']
				prefix = get_testuser['prefix']
				name   = prefix + name_1 if prefix else name_1
				email  = get_testuser['email']
				mobile = get_testuser['mobile']

				dob    = get_testuser['dob']
				subject  = "Wish you a happy birthday, "  +   name 
				today_dt_1 = datetime_ist.strftime("%Y-%m-%d %H:%M")
				data = {
				'receiver_name':name,
				'receiver_email' : email,
				'receiver_mobile' : mobile,
				'dob':dob,
				'send_at' : today_dt_1,
				'created_at' : dt_string
				}
				
				insert_mail_data = User_details().insert_mail_data(data)
				
				file_na = random.choice(template_name_list)
				# file_na = "dob_temp_9.html"
				html1 = render_template('aios/aios_email_two/'+file_na, name = name)
				# email = 'santhosh@numerotec.com'
				## send mail using mail gun
				url = 'https://api.mailgun.net/v3/aios-online.com/messages'
				auth = ('api', 'key-e13725db7c3a95b679911c038b490db1')
				data = {
					'from': 'Prof. (Dr.) Namrata Sharma - Chairperson, Scientific Committee <support@aios-online.com>',
					'to': [email],
					'cc' : [],
					# 'cc' : [],
					'bcc' : ['aiosbackup@gmail.com'],
					'subject': subject,
					'html': html1
				}
				
				data['h:Reply-To']="<chairmanscientificcommittee@aios.org>"  # <------------- HERE!
				res = requests.post(url, auth=auth, data=data)

			flash("Greetings Mail send to selected members only")
			return redirect (url_for('user.Send_mail_index')) 
	else :
		return redirect (url_for('user.Today_birthday_membesrs'))


@app.route('/mail_selected_officebearers', methods = ["POST"])
def Mail_selected_officebearers():
	if request.method == "POST":
		now = datetime.now()
		dt_string        = now.strftime("%Y-%m-%d %H:%M")	
		dt_string_format = now.strftime("%m-%d")
		# dt_string_format = "06-01"
		
		mon_date         = now.strftime("%B ,%d") 
		next_day         = now + timedelta(days=1)
		next_day_str     = next_day.strftime("%m-%d")
		today_birthday_members   = None
		nextday_birthday_members = None
		today_birthday_members   = User_details().get_testuser(dt_string_format)

		office_bearers_ids = request.form.getlist('office_bearers_id')

		if today_birthday_members:
			length_of_ids = len(office_bearers_ids)
			
			if length_of_ids == 0:
				flash("Please select atleast one office bearer")
				print("Please select atleast one office bearer")
				return redirect (url_for('user.Office_bearers_index'))
			else :
				wa_to_con = {}
				nextday_birthday_members = User_details().get_testuser(next_day_str)
				for i in office_bearers_ids:
				
					office_bearers_id = i
					office_bearer = User_details().get_office_bearers_byid(office_bearers_id)
					
					name     = office_bearer["office_bearer_name"]
					email    = office_bearer["office_beared_email"]
					mobile   = office_bearer["office_bearer_mobile"]

					wa_content_today = office_bearer["wa_content_today"]
					wa_content_trw   = office_bearer["wa_content_trw"]
					wa_to_con["OFF_BEAR_NAME"] = name
					
					if today_birthday_members and len(today_birthday_members) > 0 :
						for index,value in enumerate(today_birthday_members):
							mem_prefix   = value["prefix"]
							mem_name_1   = value["full_name"]
							mem_name     = mem_prefix+" " +mem_name_1 if mem_prefix else mem_name_1
							mem_email  = value["email"]
							mem_mobile = value["mobile"]
							
							wa_to_con["MEM_NAME"]   = mem_name
							wa_to_con["MEM_EMAIL"]  = mem_email
							if mem_mobile :
								wa_to_con["MEM_MOBILE"] = mem_mobile
								data_today = Helper.merge_tags(wa_content_today,wa_to_con)
								value["wa_content_today"] = data_today


					if nextday_birthday_members and len(nextday_birthday_members) > 0 :
						for index,value in enumerate(nextday_birthday_members):
							mem_prefix = value["prefix"]
							mem_name_1 = value["full_name"]
							mem_name   = mem_prefix+" " +mem_name_1 if mem_prefix else mem_name_1
							mem_email  = value["email"]
							mem_mobile = value["mobile"]
							wa_to_con["MEM_NAME"]   = mem_name
							wa_to_con["MEM_EMAIL"]  = mem_email
							wa_to_con["MEM_MOBILE"] = mem_mobile
							if mem_mobile :
								data_tom = Helper.merge_tags(wa_content_trw,wa_to_con)
								value["wa_content_trw"] = data_tom



					subject  = "AIOS Members Birthday on  " + " " + mon_date 
					file_na = "office_bearers_mail_3.html"
					html1 = render_template('aios/aios_email_two/'+file_na, today_birthday_members = today_birthday_members,nextday_birthday_members = nextday_birthday_members,name=name,office_bearer=office_bearer)
					# EMAIL.sendMail(subject,html1,email) # Comment by Ganesan J
					# email = 'santhosh@numerotec.com'
					## send mail using mail gun
					url = 'https://api.mailgun.net/v3/aios-online.com/messages'
					auth = ('api', 'key-e13725db7c3a95b679911c038b490db1')
					data = {
						'from': 'AIOS Members Birthday Digest <support@aios-online.com>',
						'to': [email],
						'cc' : [],
						# 'cc' : [],
						'bcc' : ['aiosbackup@gmail.com'],
						'subject': subject,
						'html': html1
					}
					
					data['h:Reply-To']="<chairmanscientificcommittee@aios.org>"  # <------------- HERE!
					res = requests.post(url, auth=auth, data=data)
					
				flash("Greetings Mail send to selected office bearers only")
				return redirect (url_for('user.Home'))

		else :
			
			flash("Today Birthday Members list nothing")
			return redirect (url_for('user.Home'))
			
#  *************************************Members mail - CRON JOB *************************** #
@app.route('/members_mail' , methods = ["GET"])
def MembersMail():
	now = datetime.now()
	datetime_ist = datetime.now()
	dt_string   = datetime_ist.strftime("%Y-%m-%d %H:%M")
	dt_string_format = now.strftime("%m-%d")
	mon_date         = now.strftime("%B ,%d") 
	hour_str_fomat = datetime_ist.strftime('%H')
	min_str_fomat  = datetime_ist.strftime('%M')
	min_int  = int(min_str_fomat)
	hour_minutes_str = datetime_ist.strftime('%H:%M')
	# test
	# if hour_str_fomat == "01" and min_int < 28 :
	# live
	if hour_str_fomat == "08" and min_int < 27 :
		print(dt_string +  " : Members - Time match and current time is " + hour_minutes_str)
		test_users= User_details().get_testuser(dt_string_format)
		template_name_list= [] 
		if test_users:
			templatess = User_details().send_mail_template_html()
			for row in templatess:
				filename = row["template_name"]
				template_name_list.append(filename)

			# below 5 line may be change for dict value in model  
			for user in test_users:
				prefix   = user['prefix']
				name_1   = user['full_name']
				name      = prefix+" "+name_1 if prefix else name_1
		
				email  = user['email']
				# email  = 'sai@numerotec.com'
				mobile = user['mobile']

				dob    = user['dob']
				user_id  = user['user_id']
				subject  = "Wish you a happy birthday, "  +   name
				data = {
				'receiver_name':name,
				'receiver_email' : email,
				'receiver_mobile' : mobile,
				'dob':dob,
				'send_at' : dt_string,
				'created_at' : dt_string
				}

				insert_mail_data = User_details().insert_mail_data(data)
				# May 10 2021 
				file_na = random.choice(template_name_list)
				# file_na = "dob_temp_22.html"
				html1 = render_template('aios/aios_email_two/'+file_na, name = name)

				# return html1
				#'cc' : ['chairmanscientificcommittee@aios.org'],
				# send mail using mail gun
				# email = 'santhosh@numerotec.com'
				# print(email)
				# email = 'sridhar@numerotec.com'
				url   = 'https://api.mailgun.net/v3/aios-online.com/messages'
				auth  = ('api', 'key-e13725db7c3a95b679911c038b490db1')
				data  = {
					'from': 'Prof. (Dr.) Namrata Sharma - Chairperson, Scientific Committee <support@aios-online.com>',
					'to': [email],
					'bcc' : ['aiosbackup@gmail.com'],
					'subject': subject,
					'html': html1
				}
				
				data['h:Reply-To']="<chairmanscientificcommittee@aios.org>"  # <------------- HERE!
				res = requests.post(url, auth=auth, data=data)

				
			flash("Mail sent to Members")
			return  "Mail send to Members"	
		else :
			flash("Today Birthday list is nothing")
			return ("Mail sent success")
	else :
		flash("Time not match")
		print("Members - Time not match and current time is  "  +  hour_minutes_str )
		return ("Time not match")
#  *********************************** Members mail - CRON JOB End **********************  #				
			

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists