from celery import shared_task

from middleware.rpc import rpc_invoker
from utils.channel_package_tools import ChannelPackage
from utils.logger import log_error


@shared_task
def version_release_task(packed_channels):  # 一键发布，发布完成邮件通知
    rpc = rpc_invoker
    channels = []
    for vtc in packed_channels:
        version = vtc['version']
        channel = vtc['channel']
        vtc_id = vtc['id']
        try:
            ChannelPackage.publish_apk(channel, version)
            rpc['endpoint'](version_id=vtc_id).unwrap()
            channels.append(channel)
        except:
            log_error()
            raise
    # send email
    rpc.origin['hera/channelbuild/version_release_notify'](
        version=version,
        channels=channels,
    ).unwrap()
