Bläddra i källkod

add send email

ming 4 år sedan
förälder
incheckning
438fea71d1
6 ändrade filer med 52 tillägg och 189 borttagningar
  1. BIN
      .DS_Store
  2. 0 63
      OpenshotService/mail.py
  3. 11 122
      OpenshotService/openshot_video_generator.py
  4. 0 2
      OpenshotService/password.txt
  5. 27 0
      api/mailer.py
  6. 14 2
      api/main.py

BIN
.DS_Store


+ 0 - 63
OpenshotService/mail.py

@@ -1,63 +0,0 @@
-
-import dataset
-import smtplib
-from email.mime.multipart import MIMEMultipart      # email內容載體
-from email.mime.text import MIMEText                # 用於製作文字內文
-from email.mime.base import MIMEBase                # 用於承載附檔
-from email import encoders                          # 用於附檔編碼
-import datetime
-import ssl
-
-
-def get_db(db_name, table_name):
-    db = dataset.connect(f'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/{db_name}?charset=utf8mb4')
-    user_table = db[table_name]
-    return user_table
-
-
-def mail_to_users(user_id: int, subject: str, contents: str):
-    """
-        1. 透過id查詢DB, 找出使用者email、username
-        2. 訊息制定(如: Aaron, 您的影片於2021/7/12 14:00 "ChoozMo測試影片" 完成了,請前往官網: "url")下載。
-        3. 傳送。
-            - 根據server不同,可以區分。
-            - 先用Gmail。(可以動就好)
-    """
-    # 連線DB得到使用者郵件、姓名
-    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
-    rows = db.query(f'SELECT * FROM users WHERE id={user_id}')
-    for row in rows:
-        email = row['email']
-        name = row['username']
-        print(name, email)
-
-    # 寄件者使用的Gmail帳戶資訊
-    time_now = datetime.datetime.utcnow() + datetime.timedelta(hours=8)
-    with open('password.txt') as f:
-        gmail_user, gmail_password = f.readlines()
-    # gmail_user = 'aaron@choozmo.com'
-    # gmail_password = 'Choozmo1015'
-    from_address = gmail_user
-    # 設定信件內容與收件人資訊
-    to_address = email  if type(email) == type([]) else [email]
-
-    # 開始組合信件內容
-    mail = MIMEMultipart()
-    mail['From'] = from_address
-    mail['To'] = ', '.join(to_address)
-    mail['Subject'] = subject
-    # 將信件內文加到email中
-    mail.attach(MIMEText(contents))
-    print(to_address)  
-
-    # 設定smtp伺服器並寄發信件    
-    smtpserver = smtplib.SMTP_SSL("smtp.gmail.com", 465)
-    smtpserver.ehlo()
-    smtpserver.login(gmail_user, gmail_password)
-    smtpserver.sendmail(from_address, to_address, mail.as_string())
-    smtpserver.quit()
-
-
-if __name__ == '__main__':
-    mail_to_users(4, 'subject', 'contents')
-

+ 11 - 122
OpenshotService/openshot_video_generator.py

@@ -19,8 +19,6 @@ import math
 import dataset
 from datetime import datetime
 from gtts import gTTS
-import cv2
-from mail import mail_to_users
 
 dir_sound = 'mp3_track/'
 dir_photo = 'photo/'
@@ -31,36 +29,18 @@ dir_subtitle = 'subtitle/'
 dir_anchor = 'anchor_raw/'
 tmp_video_dir = 'tmp_video/'
 video_sub_folder = 'ai_anchor_video/'
-#
+
 dir_list = [dir_sound,dir_photo,dir_text,dir_video,dir_title,dir_subtitle,dir_anchor,tmp_video_dir]
 
-def notify_group(msg, glist=['7vilzohcyQMPLfAMRloUawiTV4vtusZhxv8Czo7AJX8','WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD','1dbtJHbWVbrooXmQqc4r8OyRWDryjD4TMJ6DiDsdgsX','HOB1kVNgIb81tTB4Ort1BfhVp9GFo6NlToMQg88vEhh']):
+def notify_group(msg):
+    glist=['7vilzohcyQMPLfAMRloUawiTV4vtusZhxv8Czo7AJX8','WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD','1dbtJHbWVbrooXmQqc4r8OyRWDryjD4TMJ6DiDsdgsX','HOB1kVNgIb81tTB4Ort1BfhVp9GFo6NlToMQg88vEhh']
     for gid in glist:
         headers = {
                 "Authorization": "Bearer " + gid,
                 "Content-Type": "application/x-www-form-urlencoded"
         }
-    params = {"message": msg}   
-    r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
-
-
-def get_mp4_duration(video_name='mp4-test-file.mp4'): # 可輸入url
-    cap = cv2.VideoCapture(video_name)
-    # 幀率
-    fps = int(round(cap.get(cv2.CAP_PROP_FPS)))
-    # 分辨率-寬度
-    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
-    # 分辨率-高度
-    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
-    # 總幀數
-    frame_counter = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
-
-    cap.release()
-    cv2.destroyAllWindows()
-    # 時長,單位:秒(s)
-    duration = int(frame_counter / fps)
-    return duration
-
+        params = {"message": msg}   
+        r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
 
 def cKey(r,g,b,fuzz):
     col=openshot.Color()
@@ -132,7 +112,6 @@ def file_prepare(name, name_hash,text_content,image_urls,lang='zh'):
     make_dir(name_hash)
     img_num = 1
     for imgu in image_urls:
-
         if get_url_type(imgu) =='video/mp4':
             r=requests.get(imgu)
             f=open(dir_photo+name_hash+"/"+str(img_num)+".mp4",'wb')
@@ -167,7 +146,7 @@ def file_prepare(name, name_hash,text_content,image_urls,lang='zh'):
     print("mp3 file made")
     #make title as image
     txt2image_title(name, dir_title+name_hash+".png",lang)
-    
+
 def txt2image(content, save_target,lang='zh'):
     unicode_text = trim_punctuation(content)
     font = ''
@@ -273,7 +252,6 @@ def generate_subtitle_image_ENG(name_hash,text_content):
     return img_list
 
 def anchor_video_v2(name_hash,name,text_content, image_urls,avatar):
-    """ 影片產生主程式。 """
     print(os.getcwd())
     print('sub image made')
     file_prepare(name, name_hash, text_content,image_urls)
@@ -410,26 +388,8 @@ def anchor_video_v2(name_hash,name,text_content, image_urls,avatar):
     for n in range(frames):
         f=t.GetFrame(n)
         w.WriteFrame(f)
-    
-    # 更新剩下時間、duration
-    video_link = f"www.choozmo.com:8168/{video_sub_folder}{name_hash}.mp4"
-    duration, user_id = update_hisotry_duration(video_link)
-    is_left_time = update_user_left_time(user_id, duration)
-
-    # 1.餘額足 2. 餘額不足
-    # 找到user-line群組token
-    email, line_token = get_user_line_token_email(user_id)
-
-    if is_left_time:
-        notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4", glist=[line_token, 'WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD'])
-        contents = f"""  影片下載網址: {video_link}"""
-        mail_to_users(user_id, f'您好,您的影片 "{name}" 已經完成', contents=contents)
-    else:
-        notify_group(msg="您的餘額不足,請去...儲值,才能取得影片唷!", glist=[line_token, 'WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD'])
-        contents = f"""  餘額不足,請往: ...儲值url儲值 """
-        mail_to_users(user_id, f'您好,您的餘額不足', contents)
-    
-    
+        
+    #notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
     t.Close()
     w.Close()
     print("video at : www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
@@ -567,26 +527,8 @@ def anchor_video_eng(name_hash,name,text_content, image_urls,sub_titles,avatar):
     for n in range(frames):
         f=t.GetFrame(n)
         w.WriteFrame(f)
+        
     
-
-    # 更新剩下時間、duration
-    video_link = f"www.choozmo.com:8168/{video_sub_folder}{name_hash}.mp4"
-    duration, user_id = update_hisotry_duration(video_link)
-    is_left_time = update_user_left_time(user_id, duration)
-
-    # 1.餘額足 2. 餘額不足
-    # 找到user-line群組token
-    email, line_token = get_user_line_token_email(user_id)
-    
-    if is_left_time:
-        notify_group(name+", Your video is complete! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4", glist=[line_token, 'WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD'])
-        contents = f"""  The download address: {video_link}"""
-        mail_to_users(user_id, f'Hi, your video "{name}" is complete', contents=contents)
-    else:
-        notify_group(msg="The left money is not enough, please deposit to get the video!", glist=[line_token, 'WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD'])
-        contents = f"""  The left money is not enough, please go to ... to deposit. """
-        mail_to_users(user_id, f'Hi, your remain deposit is not enough', contents)
-
     t.Close()
     w.Close()
     print("video at : www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
@@ -600,62 +542,9 @@ class video_service(rpyc.Service):
         anchor_video_eng(name_hash,name,text_content, image_urls,sub_titles,avatar)
 
 
-def update_hisotry_duration(video_link):
-    """  更新資訊影片長度資訊。  """
-    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
-    table = db['history_input']
-    duration = get_mp4_duration(video_link)
-    data = dict(link=video_link, duration=duration)
-    table.update(data, ['link'])
-    
-    rows = db.query(f'SELECT * FROM history_input WHERE link="{video_link}"')
-    for row in rows:
-        user_id = row['user_id']
-
-    return duration, user_id
-
-
-def update_user_left_time(user_id, duration):
-    """  更新使用者剩下時間,如果為負,接著提醒。 """
-    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
-    table = db['users']
-    rows = db.query(f"SELECT * FROM user WHERE id={user_id}")
-    for row in rows:
-        left_time = row['left_time']
-        line_token = row['line_token']
-    left_time -= duration
-    data = dict(id=user_id, left_time=left_time-duration)
-    table.update(data, ['id'])
-
-    if left_time < 0:       
-        return False
-    else:
-        return True
-
-
-def get_user_line_token_email(user_id):
-    """ 取得使用者line-token、email用以通知用。 """
-    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
-    query = f"""
-        select 
-            A.user_id, A.link, B.email, B.line_token
-        from
-            ((select link, user_id,  duration
-            from AI_anchor.history_input ) as A
-        inner join (select  id, email, line_token from AI_anchor.users where id={user_id}) as B
-        on A.user_id=B.id);
-    """
-    rows = db.query(query)
-    for row in rows:
-        line_token = row['line_token']
-        email = row['email']
-        break
-    return line_token, email
-    
-
-
 
 from rpyc.utils.server import ThreadedServer
 t = ThreadedServer(video_service, port=8858)
 print('service started')
-t.start()
+t.start()
+

+ 0 - 2
OpenshotService/password.txt

@@ -1,2 +0,0 @@
-aaron@choozmo.com
-Choozmo1015

+ 27 - 0
api/mailer.py

@@ -0,0 +1,27 @@
+import smtplib
+import traceback
+import os
+from email.mime.text import MIMEText
+from email.mime.image import MIMEImage
+from email.mime.multipart import MIMEMultipart
+from email.message import EmailMessage
+import codecs
+
+gmail_user = 'ming@choozmo.com'
+gmail_password='lzpxinencaawsjus'
+
+sent_from = gmail_user
+#to = ['jared@choozmo.com','nina.huang@choozmo.com','ana@choozmo.com','ming@choozmo.com','mike@choozmo.com','andy@choozmo.com','hana@choozmo.com','stacy@choozmo.com','wen@choozmo.com','yukyo@choozmo.com','fxp87257@gmail.com','noodlesloves@gmail.com']
+to = ['ming013r@gmail.com']
+def send(msg):
+    try:
+        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
+        server.ehlo()
+        server.login(gmail_user, gmail_password)
+        server.sendmail(sent_from, to,  'test mail')
+        server.close()
+        print ('Email sent!')
+    except:
+        traceback.print_exc()
+        print ('Something went wrong...')
+

+ 14 - 2
api/main.py

@@ -36,6 +36,8 @@ from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
 import models
 import pymysql
 from first import first
+import mailer
+from moviepy.editor import VideoFileClip
 pymysql.install_as_MySQLdb()
 
 app = FastAPI()
@@ -226,7 +228,7 @@ async def make_anchor_video(req:models.request,token: str = Depends(oauth2_schem
             return {'msg':"無法辨別圖片網址"+imgu}
     user_id = get_user_id(token)
     save_history(req,name_hash,user_id)
-    x = threading.Thread(target=gen_video_queue, args=(name_hash,req.name, req.text_content, req.image_urls,int(req.avatar)))
+    x = threading.Thread(target=gen_video_queue, args=(name_hash,req.name, req.text_content, req.image_urls,int(req.avatar),user_id))
     x.start()
     return {"msg":"製作影片需要時間,請您耐心等候,成果會傳送至LINE群組中"} 
 
@@ -394,7 +396,7 @@ def gen_video_eng(name_hash,name,text_content, image_urls,sub_titles,avatar):
     shutil.copy(tmp_video_dir+name_hash+'.mp4',video_dest+name_hash+'.mp4')
     os.remove(tmp_video_dir+name_hash+'.mp4')
 
-def gen_video_queue(name_hash,name,text_content, image_urls,avatar):
+def gen_video_queue(name_hash,name,text_content, image_urls,avatar,user_id):
     db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
     time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
     txt_content_seperate_by_dot = ''
@@ -422,6 +424,16 @@ def gen_video_queue(name_hash,name,text_content, image_urls,avatar):
             my_answer = remote_svc.call_video(top1['name_hash'],top1['name'],top1['text_content'].split(','), top1['image_urls'].split(','),top1['avatar']) # method call
             shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
             os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
+            vid_duration = VideoFileClip("test.mp4").duration
+            left_time = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))['left_time']
+            if left_time is None:
+                left_time = 5*60
+            if left_time < vid_duration:
+                mailer.send('您本月額度剩下'+str(left_time)+'秒,此部影片有'+duration+'秒, 若要繼續產生影片請至 http://192.168.1.106:8007/confirm_add_value?name_hash='+name_hash+' 加值')
+            else:
+                left_time = left_time - duration
+                db.query('UPDATE users SET left_time ='+str(left_time)+' WHERE id='+str(user_id)+';')
+                notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
         except:
             print('video generation error')
             notify_group('影片錯誤')