main.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import os
  2. import requests
  3. import json
  4. import subprocess
  5. import time
  6. from flask import Flask,request,redirect
  7. from flask_cors import CORS
  8. app = Flask(__name__,static_folder="static")
  9. CORS(app, resources=r'/*')
  10. # 操作文件,读取本地
  11. def set_local_file_json(obj):
  12. with open("local.json","w",encoding="utf-8") as f:
  13. f.write(json.dumps(obj,ensure_ascii=False))
  14. f.close()
  15. def get_local_file_json():
  16. try:
  17. with open("local.json","r",encoding="utf-8") as f:
  18. return json.loads(f.read())
  19. except:
  20. return {"status":0,"project":[]}
  21. # current_path
  22. current_path = os.getcwd()
  23. res_json = {"code":0,"msg":"成功"}
  24. global_params ={
  25. "token":"",
  26. }
  27. # 1.小程序打包
  28. def build_mini_program(branch):
  29. command_str = (
  30. "cd "+current_path+ ";"
  31. "cd longVideoFactory;"
  32. "rm -rf dist;"
  33. "git checkout "+branch+";"
  34. "git fetch --all;"
  35. "git reset --hard origin/"+branch+";"
  36. "git pull;"
  37. "cnpm install && npm install ;"
  38. "npm run build;"
  39. )
  40. ret = subprocess.run(command_str,shell=True)
  41. if ret.returncode == 0:
  42. res_json["code"] = 0
  43. res_json["msg"] = "打包成功"
  44. else:
  45. res_json["code"] = 1
  46. res_json["msg"] = "打包失败"
  47. # # 3.微信编译图片
  48. def create_preview(project,page):
  49. # 小程序 cli path for mac
  50. wx_cli ="/Applications/wechatwebdevtools.app/Contents/MacOS/cli "
  51. dist_path = os.path.join(current_path,'longVideoFactory/dist/'+project)
  52. code_img_path = os.path.join(current_path,'1.png')
  53. path = """ '{"pathName":"%s"}' """ % page
  54. os.system(wx_cli+ " open ")
  55. os.system(wx_cli+ " open --project " + dist_path)
  56. os.system(wx_cli+ " reset-fileutils --project " + dist_path)
  57. f_read = os.popen(wx_cli+" preview --project "+dist_path+" --compile-condition "+path+" --qr-output "+code_img_path+" --qr-format image").read()
  58. print(f_read)
  59. os.system(wx_cli+ " cache --clean all --project " + dist_path)
  60. os.system(wx_cli+ " quit")
  61. if "[error]" in f_read:
  62. res_json["code"] = 3
  63. res_json["msg"] = f_read
  64. else:
  65. res_json["code"] = 0
  66. res_json["msg"] = "微信小程序编译成功"
  67. # 修改环境文件
  68. def edit_mode_by_file(project,mode):
  69. path = os.path.join(current_path,"longVideoFactory/dist/"+project+"/network/volatileConfig.js")
  70. file_lines = []
  71. with open(path,"r") as f:
  72. for item in f.readlines():
  73. if "export const currentMode" in item:
  74. item = "export const currentMode = MODE."+mode+" \n"
  75. file_lines.append(item)
  76. f.close()
  77. with open(path,"w") as f2:
  78. f2.writelines(file_lines)
  79. f2.close()
  80. res_json["code"] = 0
  81. res_json["msg"] = "文件修改成功"
  82. def upload_img_by_feishu():
  83. token = global_params["token"]
  84. key = ""
  85. url = "https://open.feishu.cn/open-apis/im/v1/images"
  86. files = {
  87. "image_type":(None,"message"),
  88. "image":('1.png',open(os.path.join(current_path,"1.png"),"rb"),"image/png")
  89. }
  90. headers = {
  91. "Authorization":"Bearer "+token,
  92. }
  93. res = requests.post(url,headers=headers,files=files,verify=False).json()
  94. if res["code"] == 0:
  95. global_params["img_key"] = res["data"]["image_key"]
  96. res_json["code"] = 0
  97. else:
  98. res_json["code"] = 4
  99. res_json["msg"] = "飞书上传图片失败"
  100. def tenant_access_token_by_feishu():
  101. url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
  102. params = {
  103. "app_id":"cli_a1ec07458838d00c",
  104. "app_secret":"Ngm0kfaLkZnpM2T2DH7L8cM5hdAqY0hI"
  105. }
  106. res = requests.post(url,data=params,verify=False).json()
  107. print(res)
  108. if res["code"] == 0:
  109. global_params["token"] = res["tenant_access_token"]
  110. res_json["msg"] = "获取飞书签名成功"
  111. res_json["code"] = 0
  112. else:
  113. res_json["code"] = 4
  114. res_json["msg"] = "获取飞书签名失败"
  115. def send_msg_by_feishu(chat_id,project_name,mode_name,branch):
  116. token = global_params["token"]
  117. img_key = global_params["img_key"]
  118. url ="https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id"
  119. headers = {
  120. "Authorization":"Bearer "+token,
  121. "Content-Type": "application/json;charset=UTF-8"
  122. }
  123. params = {
  124. "receive_id":chat_id,
  125. "msg_type": "post",
  126. "content": json.dumps({
  127. "zh_cn": {
  128. "title": "小程序预览码",
  129. "content": [
  130. [{
  131. "tag":"text",
  132. "text":"项目:"+project_name
  133. }],
  134. [{
  135. "tag":"text",
  136. "text":"环境:"+mode_name
  137. }],
  138. [{
  139. "tag":"text",
  140. "text":"分支:"+branch
  141. }],
  142. [{
  143. "tag": "img",
  144. "image_key": img_key,
  145. "width": 500,
  146. "height": 500
  147. }
  148. ]]
  149. }
  150. })
  151. }
  152. res = requests.post(url,headers=headers,data=json.dumps(params),verify=False).json()
  153. if res["code"] == 0:
  154. res_json["code"] = 0
  155. res_json["msg"] = "飞书消息发送成功"
  156. else:
  157. res_json["code"] = 5
  158. res_json["msg"] = "飞书消息发送失败"
  159. # 获取群
  160. def get_group_by_feishu():
  161. token = global_params["token"]
  162. headers = {
  163. "Authorization":"Bearer "+token,
  164. "Content-Type": "application/json;charset=UTF-8"
  165. }
  166. url = "https://open.feishu.cn/open-apis/im/v1/chats"
  167. res = requests.get(url,headers=headers,verify=False).json()
  168. data = []
  169. for item in res["data"]["items"]:
  170. if item["name"] != '':
  171. data.append(item)
  172. return data
  173. @app.route('/')
  174. def func():
  175. # return 'Welcome to auto-mini-program-build-preview server. only can run on MacOS.'
  176. return redirect("static/dist/index.html")
  177. @app.route('/getProject')
  178. def getProject():
  179. local_data = get_local_file_json()
  180. res_json["code"] = 0
  181. res_json["data"] = local_data["project"]
  182. return res_json
  183. @app.route('/getGroup')
  184. def getGroup():
  185. tenant_access_token_by_feishu()
  186. res_json["code"] = 0
  187. res_json["data"] = get_group_by_feishu()
  188. return res_json
  189. @app.route('/send',methods=['POST'])
  190. def send():
  191. local_data = get_local_file_json()
  192. try:
  193. if local_data["status"] == "1":
  194. res_json["code"] = 9
  195. res_json["msg"] = "当前有人打包,请稍后尝试"
  196. return res_json
  197. local_data["status"] = '1'
  198. set_local_file_json(local_data)
  199. res_json["code"] = 0
  200. res_json["msg"] = "成功"
  201. # 接受参数
  202. chat_id = request.json["chat_id"]
  203. branch = request.json["branch"]
  204. page = request.json["page"]
  205. project = request.json["project"]
  206. mode = request.json["mode"]
  207. project_name = request.json["project_name"]
  208. mode_name = request.json["mode_name"]
  209. func_arr = [
  210. # ------- 微信打包 ------
  211. # 1.小程序打包
  212. build_mini_program(branch),
  213. # 2.修改环境
  214. edit_mode_by_file(project,mode),
  215. time.sleep(1),
  216. create_preview(project,page),
  217. # -------- 飞书 --------
  218. # 1.获取签名
  219. tenant_access_token_by_feishu(),
  220. upload_img_by_feishu(),
  221. send_msg_by_feishu(chat_id,project_name,mode_name,branch)
  222. ]
  223. # 循环方法判断
  224. for item in func_arr:
  225. item
  226. if res_json["code"] != 0:
  227. local_data["status"] = '0'
  228. set_local_file_json(local_data)
  229. return res_json
  230. # 正常执行完
  231. local_data["status"] = '0'
  232. set_local_file_json(local_data)
  233. except Exception as ex:
  234. local_data["status"] = '0'
  235. set_local_file_json(local_data)
  236. res_json["code"] = 9
  237. print(ex)
  238. res_json["msg"] = ex.args
  239. return res_json
  240. @app.route("/getBranch")
  241. def get_branch():
  242. # 查看所有分支
  243. command_str= (
  244. "cd "+current_path+ ";"
  245. "git clone https://git.yishihui.com/weapp/longVideoFactory.git;"
  246. "cd longVideoFactory;"
  247. "git pull;"
  248. )
  249. os.system(command_str)
  250. command_str= (
  251. "cd "+current_path+ ";"
  252. "cd longVideoFactory;"
  253. "git branch -r;"
  254. )
  255. f_read = os.popen(command_str).read()
  256. branch_list = []
  257. for item in f_read.split():
  258. if "->" not in item and "HEAD" not in item and "*" not in item:
  259. branch_list.append(item.replace("origin/",""))
  260. res = {"code":0,"data":branch_list}
  261. return res
  262. if __name__ == '__main__':
  263. app.run(host='0.0.0.0', port=7777, debug=True)