# -*- coding: utf-8 -*-
from linepy import *
from datetime import datetime
from threading import Thread
import os,sys,youtube_dl,pafy,pytz,requests,time
timenow = datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y.%m.%d %H:%M:%S')
tokenPath = 'authToken.txt'
if os.path.isfile(tokenPath):
    f = open(tokenPath,'r')
    savedAuthToken = f.read()
    f.close()
else:
    print("[YTER影頭][{}]登入失敗(原因:authToken.txt不存在於當前目錄)".format(timenow))
    os._exit(0)
timenow = datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y.%m.%d %H:%M:%S')
try:
    cl = LINE(savedAuthToken)
except Exception as e:
    print("[YTER影頭][{}]登入失敗(原因:{})".format(timenow,str(e)))
    os._exit(0)
oepoll = OEPoll(cl)
profile = cl.getProfile()
clMID = cl.profile.mid
timenow = datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y.%m.%d %H:%M:%S')
print("[YTER影頭][{}]登入完成\n登入者名稱:{}\nMID:{}".format(timenow,cl.profile.displayName,cl.profile.mid))
if os.path.isfile('{}.jpg'.format(clMID)):
    os.remove('{}.jpg'.format(clMID))
if os.path.isfile('{}.mp4'.format(clMID)):
    os.remove('{}.mp4'.format(clMID))
admin = ["u8b9d115e85202db06eb798e8c1b40ae9","u9eea170f8f82341436ca2d52619c8586","ue45e2ade6b0ef86d63fbe6b88be93fd4","ubc977dab1825cd7aed0a2224f78cad42","u5a51f8f2689356bedc1ece068ba66c57"]
wait = {
    'mode1': False,
    'mode2': False,
    'mode3': False,
    'mode4': False,
    'mode5': False,
    'mode6': False,
    'mode7': False,
    'mode8': False,
    'mode9': False
}
def logError(text):
    timenow = datetime.now(tz=pytz.timezone("Asia/Taipei")).strftime('%Y.%m.%d %H:%M:%S')
    print("[YTER影頭][{}][錯誤]".format(timenow)+str(text))
def ytdl(url):
    video = pafy.new(url)
    best = video.getbest()
    best.download(filepath="{}.mp4".format(clMID))
def lineBot(op):
    try:
        if op.type == 0:
            return
        if op.type == 25 or op.type == 26:
            msg = op.message
            text = msg.text
            msg_id = msg.id
            receiver = msg.to
            sender = msg._from
            if msg.toType == 0:
                if sender != cl.profile.mid:
                    to = sender
                else:
                    to = receiver
            else:
                to = receiver
            if sender in clMID or sender in admin:
                if msg.contentType == 1:
                    if wait["mode1"] == True:
                        cl.sendReplyMessage(msg_id,to, "正在下載圖片")
                        image = cl.downloadObjectMsg(msg_id, saveAs="{}.jpg".format(clMID))
                        data = cl.getContact(clMID)
                        if data.videoProfile is None:
                            cl.sendReplyMessage(msg_id,to, "圖片下載完成 正在更換頭貼")
                            cl.updateProfilePicture('{}.jpg'.format(clMID))
                        else:
                            cl.sendReplyMessage(msg_id,to, "圖片下載完成 正在下載影片")
                            video = cl.downloadFileURL("http://dl.profile.line-cdn.net/" + data.pictureStatus + "/vp", saveAs="{}.mp4".format(clMID))
                            cl.sendReplyMessage(msg_id,to, "影片下載完成 正在更換頭貼")
                            cl.updateVideoAndPictureProfile('{}.jpg'.format(clMID),'{}.mp4'.format(clMID))
                            os.remove('{}.mp4'.format(clMID))
                        os.remove('{}.jpg'.format(clMID))
                        wait["mode1"] = False
                        cl.sendReplyMessage(msg_id,to, "更改完成")
                    elif wait["mode5"] == True:
                        cl.sendReplyMessage(msg_id,to, "正在下載圖片")
                        image = cl.downloadObjectMsg(msg_id, saveAs="{}.jpg".format(clMID))
                        if os.path.isfile("{}.mp4".format(clMID)):
                            cl.sendReplyMessage(msg_id,to, "圖片下載完成 正在更換頭貼")
                            cl.updateVideoAndPictureProfile('{}.jpg'.format(clMID),'{}.mp4'.format(clMID))
                            os.remove('{}.mp4'.format(clMID))
                            os.remove('{}.jpg'.format(clMID))
                            wait["mode5"] = False
                            cl.sendReplyMessage(msg_id,to, "更改完成")
                        else:
                            cl.sendReplyMessage(msg_id,to, "圖片下載完成 請傳送影片(請以影片而非檔案形式傳送)")
                    elif wait["mode7"] == True:
                        cl.sendReplyMessage(msg_id,to, "正在下載圖片")
                        image = cl.downloadObjectMsg(msg_id, saveAs="{}.jpg".format(clMID))
                        cl.sendReplyMessage(msg_id,to, "圖片下載完成 正在更換頭貼")
                        cl.updateVideoAndPictureProfile('{}.jpg'.format(clMID),'{}.mp4'.format(clMID))
                        os.remove('{}.mp4'.format(clMID))
                        os.remove('{}.jpg'.format(clMID))
                        wait["mode7"] = False
                        cl.sendReplyMessage(msg_id,to, "更改完成")
                if msg.contentType == 2:
                    if wait["mode3"] == True:
                        cl.sendReplyMessage(msg_id,to, "正在下載影片")
                        image = cl.downloadObjectMsg(msg_id, saveAs="{}.mp4".format(clMID))
                        cl.sendReplyMessage(msg_id,to, "影片下載完成 正在更換頭貼")
                        cl.updateVideoAndPictureProfile('{}.jpg'.format(clMID),'{}.mp4'.format(clMID))
                        os.remove('{}.mp4'.format(clMID))
                        os.remove('{}.jpg'.format(clMID))
                        wait["mode3"] = False
                        cl.sendReplyMessage(msg_id,to, "更改完成")
                    elif wait["mode5"] == True:
                        cl.sendReplyMessage(msg_id,to, "正在下載影片")
                        image = cl.downloadObjectMsg(msg_id, saveAs="{}.mp4".format(clMID))
                        if os.path.isfile("{}.jpg".format(clMID)):
                            cl.sendReplyMessage(msg_id,to, "影片下載完成 正在更換頭貼")
                            cl.updateVideoAndPictureProfile('{}.jpg'.format(clMID),'{}.mp4'.format(clMID))
                            os.remove('{}.mp4'.format(clMID))
                            os.remove('{}.jpg'.format(clMID))
                            wait["mode5"] = False
                            cl.sendReplyMessage(msg_id,to, "更改完成")
                        else:
                            cl.sendReplyMessage(msg_id,to, "影片下載完成 請傳送圖片(請以圖片而非檔案形式傳送)")
                    elif wait["mode6"] == True:
                        cl.sendReplyMessage(msg_id,to, "正在下載影片")
                        image = cl.downloadObjectMsg(msg_id, saveAs="{}.mp4".format(clMID))
                        cl.sendReplyMessage(msg_id,to, "影片下載完成 正在更換頭貼")
                        cl.updateVideoAndPictureProfile('{}.jpg'.format(clMID),'{}.mp4'.format(clMID))
                        os.remove('{}.mp4'.format(clMID))
                        os.remove('{}.jpg'.format(clMID))
                        wait["mode6"] = False
                        cl.sendReplyMessage(msg_id,to, "更改完成")
                if msg.contentType == 0:
                    if sender in admin:
                        if text.lower() == '修復':
                            cl.sendReplyMessage(msg_id,to, "修復中")
                            os.system("pip3 install youtube_dl --upgrade")
                            os.system("youtube-dl --rm-cache-dir")
                            cl.sendReplyMessage(msg_id,to, "修復完畢")
                    if text.lower() in ["換頭影","指令","指令表","help","更換頭貼","cmdlist"]:
                        cl.sendReplyMessage(msg_id,to,"""[更換頭貼功能]\n請直接輸入數字\n[1]只換頭貼(傳圖)\n[2:圖片網址]只換頭貼(傳網址)\n[3]只換影片(傳影片)\n[4:影片網址]只換影片(傳網址)\n[5]兩個都換(傳圖和影片)\n[6:圖片網址]兩個都換(傳影片和圖片網址)\n[7:影片網址]兩個都換(傳圖片和影片網址)\n[8:圖片網址+影片網址]兩個都換(傳網址)\n[9]撤銷當前影片\n\n※影片網址僅限Youtube\n※登出請對我輸入"登出"指令""")
                    elif text.lower() in ["1","１"]:
                        if wait["mode1"] or wait["mode2"] or wait["mode3"] or wait["mode4"] or wait["mode5"] or wait["mode6"] or wait["mode7"] or wait["mode8"] or wait["mode9"]:
                            cl.sendReplyMessage(msg_id,to,"有模式還在運行")
                        else:
                            cl.sendReplyMessage(msg_id,to,"請傳送圖片(請以圖片而非檔案形式傳送)")
                            wait["mode1"] = True
                    elif text.lower() in ["2","２"]:
                        if wait["mode1"] or wait["mode2"] or wait["mode3"] or wait["mode4"] or wait["mode5"] or wait["mode6"] or wait["mode7"] or wait["mode8"] or wait["mode9"]:
                            cl.sendReplyMessage(msg_id,to,"有模式還在運行")
                        else:
                            cl.sendReplyMessage(msg_id,to,"[提示]\n形式範例\n2:圖片網址")
                    elif text.lower().startswith("2") or text.lower().startswith("２"):
                        if wait["mode1"] or wait["mode2"] or wait["mode3"] or wait["mode4"] or wait["mode5"] or wait["mode6"] or wait["mode7"] or wait["mode8"] or wait["mode9"]:
                            cl.sendReplyMessage(msg_id,to,"有模式還在運行")
                        else:
                            url = text[2:]
                            if url == "":
                                cl.sendReplyMessage(msg_id,to,"您沒有輸入網址")
                            else:
                                wait["mode2"] = True
                                cl.sendReplyMessage(msg_id,to, "正在下載圖片")
                                try:
                                    image = cl.downloadFileURL(url, saveAs="{}.jpg".format(clMID))
                                except:
                                    cl.sendReplyMessage(msg_id,to, "圖片下載失敗 請更換圖片網址")
                                    wait["mode2"] = False
                                    return
                                data = cl.getContact(clMID)
                                if data.videoProfile is None:
                                    cl.sendReplyMessage(msg_id,to, "圖片下載完成 正在更換頭貼")
                                    cl.updateProfilePicture('{}.jpg'.format(clMID))
                                else:
                                    cl.sendReplyMessage(msg_id,to, "圖片下載完成 正在下載影片")
                                    video = cl.downloadFileURL("http://dl.profile.line-cdn.net/" + data.pictureStatus + "/vp", saveAs="{}.mp4".format(clMID))
                                    cl.sendReplyMessage(msg_id,to, "影片下載完成 正在更換頭貼")
                                    cl.updateVideoAndPictureProfile('{}.jpg'.format(clMID),'{}.mp4'.format(clMID))
                                    os.remove('{}.mp4'.format(clMID))
                                os.remove('{}.jpg'.format(clMID))
                                wait["mode2"] = False
                                cl.sendReplyMessage(msg_id,to, "更改完成")
                    elif text.lower() in ["3","３"]:
                        if wait["mode1"] or wait["mode2"] or wait["mode3"] or wait["mode4"] or wait["mode5"] or wait["mode6"] or wait["mode7"] or wait["mode8"] or wait["mode9"]:
                            cl.sendReplyMessage(msg_id,to,"有模式還在運行")
                        else:
                            wait["mode3"] = True
                            data = cl.getContact(clMID)
                            if data.pictureStatus is None:
                                cl.sendReplyMessage(msg_id,to,"您沒有設定頭貼")
                                wait["mode3"] = False
                                return
                            else:
                                cl.sendReplyMessage(msg_id,to, "正在下載圖片")
                            image = cl.downloadFileURL("http://dl.profile.line-cdn.net/" + data.pictureStatus, saveAs="{}.jpg".format(clMID))
                            cl.sendReplyMessage(msg_id,to,"圖片下載完成 請傳送影片(請以影片而非檔案形式傳送)")
                    elif text.lower() in ["4","４"]:
                        if wait["mode1"] or wait["mode2"] or wait["mode3"] or wait["mode4"] or wait["mode5"] or wait["mode6"] or wait["mode7"] or wait["mode8"] or wait["mode9"]:
                            cl.sendReplyMessage(msg_id,to,"有模式還在運行")
                        else:
                            cl.sendReplyMessage(msg_id,to,"[提示]\n形式範例\n4:影片網址")
                    elif text.lower().startswith("4") or text.lower().startswith("４"):
                        if wait["mode1"] or wait["mode2"] or wait["mode3"] or wait["mode4"] or wait["mode5"] or wait["mode6"] or wait["mode7"] or wait["mode8"] or wait["mode9"]:
                            cl.sendReplyMessage(msg_id,to,"有模式還在運行")
                        else:
                            url = text[2:]
                            if url == "":
                                cl.sendReplyMessage(msg_id,to,"您沒有輸入網址")
                            else:
                                wait["mode4"] = True
                                data = cl.getContact(clMID)
                                if data.pictureStatus is None:
                                    cl.sendReplyMessage(msg_id,to,"您沒有設定頭貼")
                                    wait["mode4"] = False
                                    return
                                else:
                                    cl.sendReplyMessage(msg_id,to, "正在下載影片")
                                try:
                                    ytdl(url)
                                except:
                                    cl.sendReplyMessage(msg_id,to, "影片下載失敗 請更換影片網址")
                                    wait["mode4"] = False
                                    return
                                cl.sendReplyMessage(msg_id,to, "影片下載完成 正在下載圖片")
                                image = cl.downloadFileURL("http://dl.profile.line-cdn.net/" + data.pictureStatus, saveAs="{}.jpg".format(clMID))
                                cl.sendReplyMessage(msg_id,to, "圖片下載完成 正在更換頭貼")
                                cl.updateVideoAndPictureProfile('{}.jpg'.format(clMID),'{}.mp4'.format(clMID))
                                os.remove('{}.mp4'.format(clMID))
                                os.remove('{}.jpg'.format(clMID))
                                wait["mode4"] = False
                                cl.sendReplyMessage(msg_id,to, "更改完成")
                    elif text.lower() in ["5","５"]:
                        if wait["mode1"] or wait["mode2"] or wait["mode3"] or wait["mode4"] or wait["mode5"] or wait["mode6"] or wait["mode7"] or wait["mode8"] or wait["mode9"]:
                            cl.sendReplyMessage(msg_id,to,"有模式還在運行")
                        else:
                            cl.sendReplyMessage(msg_id,to,"請傳送影片和圖片(請以影片和圖片而非檔案形式傳送)")
                            wait["mode5"] = True
                    elif text.lower() in ["6","６"]:
                        if wait["mode1"] or wait["mode2"] or wait["mode3"] or wait["mode4"] or wait["mode5"] or wait["mode6"] or wait["mode7"] or wait["mode8"] or wait["mode9"]:
                            cl.sendReplyMessage(msg_id,to,"有模式還在運行")
                        else:
                            cl.sendReplyMessage(msg_id,to,"[提示]\n形式範例\n6:圖片網址")
                    elif text.lower().startswith("6") or text.lower().startswith("６"):
                        if wait["mode1"] or wait["mode2"] or wait["mode3"] or wait["mode4"] or wait["mode5"] or wait["mode6"] or wait["mode7"] or wait["mode8"] or wait["mode9"]:
                            cl.sendReplyMessage(msg_id,to,"有模式還在運行")
                        else:
                            url = text[2:]
                            if url == "":
                                cl.sendReplyMessage(msg_id,to,"您沒有輸入網址")
                            else:
                                wait["mode6"] = True
                                cl.sendReplyMessage(msg_id,to, "正在下載圖片")
                                try:
                                    image = cl.downloadFileURL(url, saveAs="{}.jpg".format(clMID))
                                except:
                                    cl.sendReplyMessage(msg_id,to, "圖片下載失敗 請更換圖片網址")
                                    wait["mode6"] = False
                                    return
                                cl.sendReplyMessage(msg_id,to, "圖片下載完成 請傳送影片(請以影片而非檔案形式傳送)")
                    elif text.lower() in ["7","７"]:
                        if wait["mode1"] or wait["mode2"] or wait["mode3"] or wait["mode4"] or wait["mode5"] or wait["mode6"] or wait["mode7"] or wait["mode8"] or wait["mode9"]:
                            cl.sendReplyMessage(msg_id,to,"有模式還在運行")
                        else:
                            cl.sendReplyMessage(msg_id,to,"[提示]\n形式範例\n7:影片網址")
                    elif text.lower().startswith("7") or text.lower().startswith("７"):
                        if wait["mode1"] or wait["mode2"] or wait["mode3"] or wait["mode4"] or wait["mode5"] or wait["mode6"] or wait["mode7"] or wait["mode8"] or wait["mode9"]:
                            cl.sendReplyMessage(msg_id,to,"有模式還在運行")
                        else:
                            url = text[2:]
                            if url == "":
                                cl.sendReplyMessage(msg_id,to,"您沒有輸入網址")
                            else:
                                wait["mode7"] = True
                                cl.sendReplyMessage(msg_id,to, "正在下載影片")
                                try:
                                    ytdl(url)
                                except:
                                    cl.sendReplyMessage(msg_id,to, "影片下載失敗 請更換影片網址")
                                    wait["mode7"] = False
                                    return
                                cl.sendReplyMessage(msg_id,to, "影片下載完成 請傳送圖片(請以圖片而非檔案形式傳送)")
                    elif text.lower() in ["8","８"]:
                        if wait["mode1"] or wait["mode2"] or wait["mode3"] or wait["mode4"] or wait["mode5"] or wait["mode6"] or wait["mode7"] or wait["mode8"] or wait["mode9"]:
                            cl.sendReplyMessage(msg_id,to,"有模式還在運行")
                        else:
                            cl.sendReplyMessage(msg_id,to,"[提示]\n形式範例\n8:圖片網址+影片網址")
                    elif text.lower().startswith("8") or text.lower().startswith("８"):
                        if wait["mode1"] or wait["mode2"] or wait["mode3"] or wait["mode4"] or wait["mode5"] or wait["mode6"] or wait["mode7"] or wait["mode8"] or wait["mode9"]:
                            cl.sendReplyMessage(msg_id,to,"有模式還在運行")
                        else:
                            if "+" in text:
                                url = text[2:].split('+')
                            elif "＋" in text:
                                url = text[2:].split('＋')
                            else:
                                cl.sendReplyMessage(msg_id,to,"[提示]\n形式範例\n8:圖片網址+影片網址")
                                return
                            if url[0] == "" and url[1] == "":
                                cl.sendReplyMessage(msg_id,to,"您沒有輸入任何網址")
                            elif url[0] == "":
                                cl.sendReplyMessage(msg_id,to,"您沒有輸入圖片網址")
                            elif url[1] == "":
                                cl.sendReplyMessage(msg_id,to,"您沒有輸入影片網址")
                            else:
                                wait["mode8"] = True
                            cl.sendReplyMessage(msg_id,to, "正在下載圖片")
                            try:
                                image = cl.downloadFileURL(url[0], saveAs="{}.jpg".format(clMID))
                            except:
                                cl.sendReplyMessage(msg_id,to, "圖片下載失敗 請更換圖片網址")
                                wait["mode8"] = False
                                return
                            cl.sendReplyMessage(msg_id,to, "圖片下載完成 正在下載影片")
                            try:
                                ytdl(url[1])
                            except:
                                cl.sendReplyMessage(msg_id,to, "影片下載失敗 請更換影片網址")
                                wait["mode8"] = False
                                return
                            cl.sendReplyMessage(msg_id,to, "影片下載完成 正在更換頭貼")
                            cl.updateVideoAndPictureProfile('{}.jpg'.format(clMID),'{}.mp4'.format(clMID))
                            os.remove('{}.mp4'.format(clMID))
                            os.remove('{}.jpg'.format(clMID))
                            wait["mode8"] = False
                            cl.sendReplyMessage(msg_id,to, "更改完成")
                    elif text.lower() in ["9","９"]:
                        data = cl.getContact(clMID)
                        if data.pictureStatus is None:
                            cl.sendReplyMessage(msg_id,to,"您沒有設定頭貼")
                        else:
                            wait["mode9"] = True
                            cl.sendReplyMessage(msg_id,to, "正在下載圖片")
                            image = cl.downloadFileURL("http://dl.profile.line-cdn.net/" + data.pictureStatus, saveAs="{}.jpg".format(clMID))
                            cl.sendReplyMessage(msg_id,to, "圖片下載完成 正在更換頭貼")
                            cl.updateProfilePicture('{}.jpg'.format(clMID))
                            os.remove('{}.jpg'.format(clMID))
                            wait["mode9"] = False
                            cl.sendReplyMessage(msg_id,to, "更改完成")
                    elif text.lower() == '取消':
                        if wait["mode1"] or wait["mode2"] or wait["mode3"] or wait["mode4"] or wait["mode5"] or wait["mode6"] or wait["mode7"] or wait["mode8"] or wait["mode9"]:
                            wait["mode1"] = False
                            wait["mode2"] = False
                            wait["mode3"] = False
                            wait["mode4"] = False
                            wait["mode5"] = False
                            wait["mode6"] = False
                            wait["mode7"] = False
                            wait["mode8"] = False
                            wait["mode9"] = False
                            try:
                                os.remove('{}.mp4'.format(clMID))
                                os.remove('{}.jpg'.format(clMID))
                                cl.sendReplyMessage(msg_id,to,"取消完成")
                            except:
                                cl.sendReplyMessage(msg_id,to,"取消完成")
                        else:
                            cl.sendReplyMessage(msg_id,to,"沒有正在執行的操作")
    except Exception as e:
        logError(e)
while True:
    try:
        ops = oepoll.singleTrace(count=50)
        if ops is not None:
            for op in ops:
                oepoll.setRevision(op.revision)
                #lineBot(op)
                thread = Thread(target=lineBot, args=(op,))
                thread.start()
    except Exception as e:
        logError(e)
