Python脚本实现iOS打包并上传蒲公英、钉钉群通知
该方法可以快速实现iOS版本构建,发布测试;
注意:构建的版本有可能不完整,一些本地资源文件会丢失;发布App Store的版本不要使用该方法!!!
实现步骤:
1、搭建Python运行环境;
- 自行搭建环境,找到安装的路径:/usr/local/bin/python3.9
2、准备配置脚本;
- 见附脚本文件
3、创建目录用于存放脚本文件与IPA文件;
4、将工程的编译设备选成 Gemeric iOS Device
5、command + B编译
6、打开终端执行脚本文件
- Python安装的路径
/usr/local/bin/python3.9
- 脚本存放的路径
/Users/gleen/Desktop/DCBPgerLoad/AutoPage.py
- 终端执行:
附:脚本文件
#!/usr/bin/env /usr/local/bin/python3
#coding=utf-8
import os
import requests
import json
import webbrowser
import subprocess
import shutil
import time
import hmac
import hashlib
import base64
import urllib.parse
from simplejson import JSONDecoder
from dingtalkchatbot.chatbot import DingtalkChatbot, is_not_null_and_blank_str, ActionCard, FeedLink, CardItem
'''
使用注意事项:该脚本基于python3.9
1、将工程的编译设备选成 Gemeric iOS Device
2、command + B编译
3、执行脚本文件 /usr/local/bin/python3.9 /Users/gleen/Desktop/DCBPgerLoad/AutoPage.py
'''
# APP的路径
appFileFullPath = '/Users/gleen/Library/Developer/Xcode/DerivedData/DcbDemo-duchqiccmxxxxxxxxxeomcswadkhe/Build/Products/Debug-iphoneos/DcbDemo.app'
PayLoadPath = '/Users/gleen/Desktop/DCBPgerLoad/Payload'
packBagPath = '/Users/gleen/Desktop/DCBPgerLoad/DebugPage'
# 安装密码 自定义
buildPassword = "123456"
# 构建用户 自定义
buildUser = "老司机"
#安全设置 签名计算 具体步骤:
#https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
timestamp = str(round(time.time() * 1000))
#secret需要更改
secret = 'SExxxxxxxxxxxxxxxxxxxxxx553079ac55cb5'
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
print(timestamp)
print(sign)
# WebHook地址
dingtalkAccessToken = '62022f96bc05f400xxxxxxxxxxxxxxxxx7a9d11c8275fa5706e117'
webhook = 'https://oapi.dingtalk.com/robot/send?access_token={}×tamp={}&sign={}'.format(dingtalkAccessToken,timestamp,sign)
print('webhook:' + webhook)
# 初始化机器人小丁
xiaoding = DingtalkChatbot(webhook)
isSendDingtalk = False #是否发送到钉钉群
#上传蒲公英 账号
openUrlPath = 'https://www.pgyer.com/manager/dashboard/app/8ee0368xxxxxxxxxxxxxxxxx767db365a7'
messageUrl = 'https://www.pgyer.com'
USER_KEY = "4ab6ba60fxxxxxxxxxxxxxxxxxb5d53b4f2d"
API_KEY = "0f27a7807fxxxxxxxxxxxxxxxxxd1fdf1ab"
APP_KEY = "8ee03687xxxxxxxxxxxxxxxxxeb3767db365a7"
#这个是把时间戳转换成格式化好的实际,如果不传时间戳,那么就返回当前的时间
def timestamp_to_str(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
if timestamp:
return time.strftime(format,time.localtime(timestamp))
else:
return time.strftime(format,time.localtime())
# 获取蒲公英的APP构建版本信息
def getPgyerData():
url = "https://www.pgyer.com/apiv2/app/view"
headers = {"content-type": "application/x-www-form-urlencoded;charset=utf-8"}
body = {"appKey": APP_KEY,"_api_key":API_KEY}
payload = keyValFromDict(body)
ret = requests.post(url = url, headers = headers, data = payload)
if ret.status_code == 200:
return json.loads(ret.text)
else:
print("请求出错")
# 将字典转为键值对的格式a=1&b=2&c=3 字符串
def keyValFromDict(dict):
array = []
for key,val in dict.items():
array.append(key + "=" + str(val))
return "&".join(array)
#上传蒲公英
def uploadIPA(IPAPath):
if(IPAPath==''):
print("\n*************** 没有找到对应上传的IPA包 *********************\n")
return
else:
endTime = time.time()
print("\n*************** 开始上传到蒲公英 用时:%.2f秒 *********************\n"%(endTime-startTime))
url='https://www.pgyer.com/apiv2/app/upload'
data={
'uKey':USER_KEY,
'_api_key':API_KEY,
'buildInstallType':'2',
'buildPassword':buildPassword,
'buildUpdateDescription':decs
}
files={'file':open(IPAPath,'rb')}
r=requests.post(url,data=data,files=files)
# 发布到钉钉
def openDownloadUrl():
webbrowser.open(openUrlPath,new=1,autoraise=True)
# 上传到蒲公英的版本信息
PgyerInfo = getPgyerData()
dataDict = PgyerInfo["data"]
# APP名字
appFileName = dataDict["buildName"]
# 下载二维码
buildQRCodeURL = dataDict["buildQRCodeURL"]
# 版本号
buildVersion = dataDict["buildVersion"]
# 构建版本号
buildVersionNo = dataDict["buildVersionNo"]
# 更新时间
buildUpdated = dataDict["buildUpdated"]
# 下载地址
ipaDownloadUrl = messageUrl + "/" + dataDict["buildShortcutUrl"]
if isSendDingtalk:
# Text消息@所有人
# xiaoding.send_link(title='[%s]构建iOS测试版本:\nipa文件上传成功,点击链接下载'%(appFileName), text='完成时间[%s]\n%s'%(timestamp_to_str(),decs), message_url=messageUrl,pic_url=picUrl)
xiaoding.send_markdown(title='iOS构建', text='## %s\n'
'版本构建成功\n\n'
'安装密码: %s\n\n'
'![](%s)\n\n'
'构建用户: %s\n\n'
'构建平台: iOS\n\n'
'构建版本: %s(Build:%s)\n\n'
'构建时间: %s \n\n'
'[点击下载](%s) \n\n'%(appFileName,buildPassword,buildQRCodeURL,buildUser,buildVersion,buildVersionNo,buildUpdated,ipaDownloadUrl),
is_at_all=True)
xiaoding.send_text(msg='%s\n版本构建成功!\n请扫描二维码或点击下载安装测试\n\n'%(appFileName), is_at_all=True)
endTime = time.time()
print ("\n*************** 更新成功 用时:%.2f秒 *********************\n"%(endTime-startTime))
#编译打包流程
def bulidIPA():
#删除之前打包的ProgramBag文件夹
subprocess.call(["rm","-rf",packBagPath])
#创建PayLoad文件夹
mkdir(PayLoadPath)
#将app拷贝到PayLoadPath路径下
subprocess.call(["cp","-r",appFileFullPath,PayLoadPath])
#在桌面上创建packBagPath的文件夹
subprocess.call(["mkdir","-p",packBagPath])
#将PayLoadPath文件夹拷贝到packBagPath文件夹下
subprocess.call(["cp","-r",PayLoadPath,packBagPath])
#删除桌面的PayLoadPath文件夹
subprocess.call(["rm","-rf",PayLoadPath])
#切换到当前目录
os.chdir(packBagPath)
#压缩packBagPath文件夹下的PayLoadPath文件夹夹
subprocess.call(["zip","-r","./Payload.zip","."])
endTime = time.time()
print ("\n*************** 打包成功 用时:%.2f秒 *********************\n"%(endTime-startTime))
#将zip文件改名为ipa
subprocess.call(["mv","payload.zip","Payload.ipa"])
#删除payLoad文件夹
subprocess.call(["rm","-rf","./Payload"])
#创建PayLoad文件夹
def mkdir(PayLoadPath):
isExists = os.path.exists(PayLoadPath)
if not isExists:
os.makedirs(PayLoadPath)
print(PayLoadPath + '创建成功')
return True
else:
print (PayLoadPath + '目录已经存在')
return False
if __name__ == '__main__':
decs = input("请输入更新的日志描述:")
startTime = time.time()
bulidIPA()
uploadIPA('%s/Payload.ipa'%packBagPath)
openDownloadUrl()