PQStuckPointPublicController.swift 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. //
  2. // PQStuckPointPublicController.swift
  3. // PQSpeed
  4. //
  5. // Created by SanW on 2021/5/6.
  6. // Copyright © 2021 BytesFlow. All rights reserved.
  7. //
  8. import ObjectMapper
  9. import Photos
  10. import UIKit
  11. import WechatOpenSDK
  12. class PQStuckPointPublicController: PQBaseViewController {
  13. private var isShared: Bool = false // 是否在分享
  14. private var isExportSuccess: Bool = false // 是否导出完成
  15. private var isSaveDraftSuccess: Bool = false // 是否保存草稿完成
  16. private var isSaveProjectSuccess: Bool = false // 是否保存项目完成
  17. private var isUploadSuccess: Bool = false // 是否上传完成
  18. private var isPublicSuccess: Bool = false // 是否发布完成
  19. private var exportLocalURL: URL? // 导出的地址
  20. // 再创作数据
  21. private var reCreateData: PQReCreateModel?
  22. // 确定上传的数据
  23. private var uploadData: PQUploadModel?
  24. // 发布成功的视频数据
  25. private var videoData: PQVideoListModel?
  26. // 视频创作埋点数据
  27. private var eventTrackData: PQVideoMakeEventTrackModel?
  28. // 选中的总时长-统计使用
  29. var selectedTotalDuration: Float64 = 0
  30. // 选择的总数-统计使用
  31. var selectedDataCount: Int = 0
  32. // 选择的图片总数-统计使用
  33. var selectedImageDataCount: Int = 0
  34. // 最大的宽度
  35. private var maxWidth: CGFloat = cScreenWidth
  36. // 最大的高度
  37. private var maxHeight: CGFloat = cScreenHeigth - cDevice_iPhoneNavBarAndStatusBarHei - cSafeAreaHeight - cDefaultMargin * 5 - cDefaultMargin * 12 - cDefaultMargin * 5
  38. // 开始导出的时间
  39. private let startExportDate: Float64 = Date().timeIntervalSince1970
  40. // 导出结束的时间
  41. private var exportEndDate: Float64 = Date().timeIntervalSince1970
  42. // 取到的封面 给发布界面使用
  43. private var coverImage: UIImage?
  44. // 导出视频工具类
  45. private var exporter: PQCompositionExporter!
  46. // 导出进度
  47. private var exportProgrss = 0
  48. var mStickers: [PQEditVisionTrackMaterialsModel]?
  49. // 预览大小
  50. private var preViewSize: CGSize {
  51. switch aspectRatio {
  52. case let .origin(width, height):
  53. var tempHeight: CGFloat = 0
  54. var tempWidth: CGFloat = 0
  55. if width > height {
  56. tempWidth = maxWidth
  57. tempHeight = (maxWidth * height / width)
  58. if tempHeight > maxHeight {
  59. tempHeight = maxHeight
  60. tempWidth = (maxHeight * width / height)
  61. }
  62. } else {
  63. tempHeight = maxHeight
  64. tempWidth = (maxHeight * width / height)
  65. if tempWidth > maxWidth {
  66. tempWidth = maxWidth
  67. tempHeight = (maxWidth * height / width)
  68. }
  69. }
  70. if tempHeight.isNaN || tempWidth.isNaN {
  71. return CGSize.zero
  72. } else {
  73. return CGSize(width: tempWidth, height: tempHeight)
  74. }
  75. case .oneToOne:
  76. if maxWidth > maxHeight {
  77. return CGSize(width: maxHeight, height: maxHeight)
  78. } else {
  79. return CGSize(width: maxWidth, height: maxWidth)
  80. }
  81. case .sixteenToNine:
  82. return CGSize(width: maxWidth, height: maxWidth * 9.0 / 16.0)
  83. case .nineToSixteen:
  84. return CGSize(width: maxHeight * 9.0 / 16.0, height: maxHeight)
  85. default:
  86. break
  87. }
  88. return CGSize(width: maxHeight, height: maxHeight)
  89. }
  90. // 背景音乐
  91. var audioMixModel: PQVoiceModel?
  92. // 画面比例
  93. var aspectRatio: aspectRatio?
  94. // 导出的项目数据
  95. var editProjectModel: PQEditProjectModel? {
  96. didSet {
  97. aspectRatio = PQPlayerViewModel.videoCanvasTypeToAspectRatio(projectModel: editProjectModel)
  98. var totalDuration: Float64 = 0
  99. if editProjectModel?.sData?.sections.count ?? 0 > 0 {
  100. for section in (editProjectModel?.sData?.sections)! {
  101. totalDuration = totalDuration + section.sectionDuration
  102. }
  103. }
  104. editProjectModel?.sData?.videoMetaData?.duration = totalDuration
  105. if editProjectModel?.sData?.sections != nil, (editProjectModel?.sData?.sections.count ?? 0) > 0 {
  106. // 查找出背景图并设置
  107. var coverImageMaterialsModel: PQEditVisionTrackMaterialsModel?
  108. for section in (editProjectModel?.sData?.sections)! {
  109. if coverImageMaterialsModel != nil {
  110. break
  111. }
  112. coverImageMaterialsModel = section.sectionTimeline?.visionTrack?.getEnableVisionTrackMaterials().first
  113. }
  114. if coverImageMaterialsModel != nil {
  115. coverImage = coverImageMaterialsModel?.getCoverImage()
  116. playerHeaderView.image = coverImage
  117. playerHeaderView.contentMode = coverImageMaterialsModel!.canvasFillType == stickerContentMode.aspectFitStr.rawValue ? .scaleAspectFill : .scaleAspectFit
  118. }
  119. }
  120. }
  121. }
  122. /// 所有需要导出的filter
  123. var filters: Array = Array<ImageProcessingOperation>.init()
  124. /// 预览背景页
  125. lazy var bgTopView: UIView = {
  126. let bgTopView = UIView(frame: CGRect(x: 0, y: cDevice_iPhoneNavBarAndStatusBarHei, width: cScreenWidth, height: maxHeight))
  127. bgTopView.backgroundColor = PQBFConfig.shared.styleBackGroundColor
  128. return bgTopView
  129. }()
  130. // 预览界面
  131. var playerHeaderView: UIImageView = {
  132. let playerHeaderView = UIImageView(frame: CGRect(x: 0, y: cDevice_iPhoneNavBarAndStatusBarHei, width: cScreenWidth, height: 0))
  133. playerHeaderView.isUserInteractionEnabled = true
  134. playerHeaderView.contentMode = .scaleAspectFit
  135. playerHeaderView.clipsToBounds = true
  136. return playerHeaderView
  137. }()
  138. /// 播放器
  139. lazy var avPlayer: AVPlayer = {
  140. let avPlayer = AVPlayer()
  141. NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: avPlayer.currentItem, queue: .main) { [weak self] notify in
  142. BFLog(message: "AVPlayerItemDidPlayToEndTime = \(notify)")
  143. avPlayer.seek(to: CMTime.zero)
  144. self?.playBtn.isHidden = false
  145. }
  146. NotificationCenter.default.addObserver(forName: .AVPlayerItemNewErrorLogEntry, object: avPlayer.currentItem, queue: .main) { notify in
  147. BFLog(message: "AVPlayerItemNewErrorLogEntry = \(notify)")
  148. }
  149. NotificationCenter.default.addObserver(forName: .AVPlayerItemFailedToPlayToEndTime, object: avPlayer.currentItem, queue: .main) { notify in
  150. BFLog(message: "AVPlayerItemFailedToPlayToEndTime = \(notify)")
  151. }
  152. NotificationCenter.default.addObserver(forName: .AVPlayerItemPlaybackStalled, object: avPlayer.currentItem, queue: .main) { notify in
  153. BFLog(message: "AVPlayerItemPlaybackStalled = \(notify)")
  154. }
  155. avPlayer.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 1000), queue: .main) { [weak self] _ in
  156. let progress = CMTimeGetSeconds(avPlayer.currentItem?.currentTime() ?? CMTime.zero) / CMTimeGetSeconds(avPlayer.currentItem?.duration ?? CMTime.zero)
  157. if progress >= 1 {
  158. self?.playBtn.isHidden = false
  159. }
  160. }
  161. return avPlayer
  162. }()
  163. /// 预览layer
  164. lazy var playerLayer: AVPlayerLayer = {
  165. let playerLayer = AVPlayerLayer(player: avPlayer)
  166. playerLayer.frame = playerHeaderView.bounds
  167. return playerLayer
  168. }()
  169. /// 播放按钮
  170. lazy var playBtn: UIButton = {
  171. let playBtn = UIButton(type: .custom)
  172. playBtn.frame = CGRect(x: (preViewSize.width - cDefaultMargin * 5) / 2, y: (preViewSize.height - cDefaultMargin * 5) / 2, width: cDefaultMargin * 5, height: cDefaultMargin * 5)
  173. playBtn.setImage(UIImage().BF_Image(named: "icon_video_play"), for: .normal)
  174. playBtn.tag = 4
  175. playBtn.isHidden = true
  176. playBtn.isUserInteractionEnabled = false
  177. return playBtn
  178. }()
  179. // progressTipsLab
  180. lazy var progressTipsLab: UILabel = {
  181. let progressTipsLab = UILabel()
  182. progressTipsLab.textAlignment = .center
  183. progressTipsLab.font = UIFont.systemFont(ofSize: 16, weight: .medium)
  184. progressTipsLab.numberOfLines = 2
  185. progressTipsLab.textColor = UIColor.white
  186. let attributedText = NSMutableAttributedString(string: "0%\n视频正在处理中,请勿离开")
  187. attributedText.addAttributes([.font: UIFont.systemFont(ofSize: 34)], range: NSRange(location: 0, length: 2))
  188. progressTipsLab.attributedText = attributedText
  189. progressTipsLab.addShadow()
  190. return progressTipsLab
  191. }()
  192. // 进度条
  193. lazy var progressView: UIProgressView = {
  194. let progressView = UIProgressView(progressViewStyle: .default)
  195. progressView.trackTintColor = UIColor(white: 0, alpha: 0.5)
  196. progressView.progressTintColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
  197. progressView.transform = CGAffineTransform(scaleX: 1.0, y: playerHeaderView.frame.height / 3.0)
  198. return progressView
  199. }()
  200. lazy var remindLab: UILabel = {
  201. let remindLab = UILabel()
  202. remindLab.isHidden = true
  203. remindLab.font = UIFont.systemFont(ofSize: 14)
  204. remindLab.textColor = PQBFConfig.shared.styleTitleColor
  205. remindLab.textAlignment = .center
  206. remindLab.numberOfLines = 3
  207. let arr = NSMutableAttributedString(string: "制作完成啦🎉\n\n快分享秀一下")
  208. arr.addAttributes([.font: UIFont.systemFont(ofSize: 30, weight: .semibold)], range: NSRange(location: arr.length - 6, length: 6))
  209. remindLab.attributedText = arr
  210. return remindLab
  211. }()
  212. lazy var shareWechatBtn: UIButton = {
  213. let shareWechatBtn = UIButton(type: .custom)
  214. shareWechatBtn.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
  215. shareWechatBtn.setImage(UIImage().BF_Image(named: "reCreate_opration_wechat"), for: .normal)
  216. shareWechatBtn.backgroundColor = PQBFConfig.shared.styleBackGroundColor
  217. shareWechatBtn.addCorner(corner: 6)
  218. shareWechatBtn.tag = 1
  219. shareWechatBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
  220. return shareWechatBtn
  221. }()
  222. lazy var shareFriendBtn: UIButton = {
  223. let shareFriendBtn = UIButton(type: .custom)
  224. shareFriendBtn.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
  225. shareFriendBtn.setImage(UIImage().BF_Image(named: "reCreate_opration_friend"), for: .normal)
  226. shareFriendBtn.backgroundColor = PQBFConfig.shared.styleBackGroundColor
  227. shareFriendBtn.addCorner(corner: 6)
  228. shareFriendBtn.tag = 2
  229. shareFriendBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
  230. return shareFriendBtn
  231. }()
  232. lazy var finishedBtn: UIButton = {
  233. let finishedBtn = UIButton(type: .custom)
  234. finishedBtn.setTitle("完成", for: .normal)
  235. finishedBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#999999"), for: .normal)
  236. finishedBtn.setTitleColor(UIColor.white, for: .selected)
  237. finishedBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .medium)
  238. finishedBtn.backgroundColor = PQBFConfig.shared.otherTintColor
  239. finishedBtn.tag = 3
  240. finishedBtn.addCorner(corner: 3)
  241. finishedBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
  242. return finishedBtn
  243. }()
  244. /// 背景View
  245. lazy var oprationBgView: UIView = {
  246. let oprationBgView = UIView(frame: CGRect(x: 0, y: cDevice_iPhoneNavBarAndStatusBarHei, width: cScreenWidth, height: view.frame.height - cDevice_iPhoneNavBarAndStatusBarHei))
  247. oprationBgView.backgroundColor = cShadowColor
  248. return oprationBgView
  249. }()
  250. override func backBtnClick() {
  251. if isExportSuccess {
  252. navigationController?.popViewController(animated: true)
  253. } else {
  254. view.endEditing(true)
  255. let remindData = PQBaseModel()
  256. remindData.title = "编辑的内容,将不会被保存"
  257. let remindView = PQRemindView(frame: CGRect(x: 0, y: 0, width: cScreenWidth, height: cScreenHeigth))
  258. remindView.isBanned = true
  259. remindView.confirmBtn.setTitle("确认", for: .normal)
  260. remindView.cancelBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#333333"), for: .normal)
  261. remindView.confirmBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#EE0051"), for: .normal)
  262. UIApplication.shared.keyWindow?.addSubview(remindView)
  263. remindView.remindData = remindData
  264. remindView.remindBlock = { [weak self] item, _ in
  265. if item.tag == 2 {
  266. // 取消导出
  267. if self?.exporter != nil {
  268. self?.exporter.cancel()
  269. }
  270. self?.navigationController?.popViewController(animated: true)
  271. }
  272. }
  273. }
  274. }
  275. override func viewDidLoad() {
  276. super.viewDidLoad()
  277. // 注册上传成功的通知
  278. addNotification(self, selector: #selector(uploadSuccess(notify:)), name: cUploadSuccessKey, object: nil)
  279. PQNotification.addObserver(self, selector: #selector(didBecomeActiveNotification), name: UIApplication.didBecomeActiveNotification, object: nil)
  280. leftButton(image: "icon_detail_back", tintColor: PQBFConfig.shared.styleTitleColor)
  281. navHeadImageView?.backgroundColor = UIColor.clear
  282. lineView?.removeFromSuperview()
  283. view.addSubview(bgTopView)
  284. playerHeaderView.frame = CGRect(origin: CGPoint(x: (cScreenWidth - preViewSize.width) / 2, y: (maxHeight - preViewSize.height) / 2), size: preViewSize)
  285. let ges = UITapGestureRecognizer(target: self, action: #selector(playVideo))
  286. playerHeaderView.addGestureRecognizer(ges)
  287. // 添加导出view
  288. bgTopView.addSubview(playerHeaderView)
  289. if playerLayer.superlayer == nil {
  290. playerHeaderView.layer.insertSublayer(playerLayer, at: 0)
  291. }
  292. playerHeaderView.addSubview(playBtn)
  293. playerHeaderView.addSubview(progressView)
  294. view.addSubview(remindLab)
  295. view.addSubview(shareWechatBtn)
  296. view.addSubview(shareFriendBtn)
  297. navHeadImageView?.addSubview(finishedBtn)
  298. view.addSubview(oprationBgView)
  299. oprationBgView.addSubview(progressTipsLab)
  300. progressView.snp.makeConstraints { make in
  301. make.left.right.centerY.equalTo(playerHeaderView)
  302. make.height.equalTo(3)
  303. }
  304. progressTipsLab.snp.makeConstraints { make in
  305. make.centerX.equalToSuperview()
  306. make.top.equalToSuperview().offset(((preViewSize.height - 90) / 2) + ((maxHeight - preViewSize.height) / 2))
  307. make.width.equalToSuperview()
  308. make.height.equalTo(90)
  309. }
  310. finishedBtn.snp.makeConstraints { make in
  311. make.centerY.equalTo(backButton!)
  312. make.width.equalTo(cDefaultMargin * 5)
  313. make.height.equalTo(cDefaultMargin * 3)
  314. make.right.equalToSuperview().offset(-12)
  315. }
  316. shareWechatBtn.snp.makeConstraints { make in
  317. make.right.equalTo(view.snp_centerX).offset(-cDefaultMargin)
  318. make.width.equalTo(70)
  319. make.height.equalTo(cDefaultMargin * 7)
  320. make.bottom.equalToSuperview().offset(-(cSafeAreaHeight + 32))
  321. }
  322. shareFriendBtn.snp.makeConstraints { make in
  323. make.left.equalTo(view.snp_centerX).offset(cDefaultMargin)
  324. make.width.bottom.height.equalTo(shareWechatBtn)
  325. }
  326. remindLab.snp.makeConstraints { make in
  327. make.centerX.equalToSuperview()
  328. make.bottom.equalTo(shareWechatBtn.snp_top).offset(-cDefaultMargin * 2)
  329. }
  330. // 取消所有的导出
  331. PQSingletoMemoryUtil.shared.allExportSession.forEach { _, exportSession in
  332. exportSession.cancelExport()
  333. }
  334. // 开始导出
  335. beginExport()
  336. // 曝光上报:窗口曝光
  337. PQEventTrackViewModel.baseReportUpload(businessType: .bt_windowView, objectType: .ot_view_publishSyncedUp, pageSource: .sp_stuck_publishSyncedUp, extParams: nil, remindmsg: "卡点视频数据上报-(曝光上报:窗口曝光)")
  338. }
  339. override func viewWillAppear(_ animated: Bool) {
  340. super.viewWillAppear(animated)
  341. PQNotification.addObserver(self, selector: #selector(enterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
  342. PQNotification.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
  343. UIApplication.shared.isIdleTimerDisabled = true
  344. #if swift(>=4.2)
  345. let memoryNotification = UIApplication.didReceiveMemoryWarningNotification
  346. _ = UIApplication.willTerminateNotification
  347. _ = UIApplication.didEnterBackgroundNotification
  348. #else
  349. let memoryNotification = NSNotification.Name.UIApplicationDidReceiveMemoryWarning
  350. let terminateNotification = NSNotification.Name.UIApplicationWillTerminate
  351. let enterbackgroundNotification = NSNotification.Name.UIApplicationDidEnterBackground
  352. #endif
  353. NotificationCenter.default.addObserver(
  354. self, selector: #selector(clearMemoryCache), name: memoryNotification, object: nil
  355. )
  356. }
  357. @objc public func clearMemoryCache() {
  358. BFLog(message: "收到内存警告")
  359. }
  360. override func viewWillDisappear(_ animated: Bool) {
  361. super.viewWillDisappear(animated)
  362. UIApplication.shared.isIdleTimerDisabled = false
  363. PQNotification.removeObserver(self)
  364. }
  365. deinit {
  366. view.endEditing(true)
  367. PQNotification.removeObserver(self)
  368. // 取消导出
  369. if exporter != nil {
  370. exporter.cancel()
  371. }
  372. avPlayer.pause()
  373. avPlayer.replaceCurrentItem(with: nil)
  374. // 点击上报:返回按钮
  375. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_click_back, pageSource: .sp_stuck_publishSyncedUp, extParams: nil, remindmsg: "卡点视频数据上报-(点击上报:返回按钮)")
  376. }
  377. }
  378. // MARK: - 导出/上传/下载及其他方法
  379. /// 导出/上传/下载及其他方法
  380. extension PQStuckPointPublicController {
  381. /// fp1 - 导出视频
  382. /// 开始导出视频
  383. func beginExport() {
  384. if !(editProjectModel?.sData?.sections != nil && (editProjectModel?.sData?.sections.count ?? 0) > 0) {
  385. BFLog(message: "项目段落错误❌")
  386. return
  387. }
  388. // 输出视频地址
  389. var outPutMP4Path = exportVideosDirectory
  390. if !directoryIsExists(dicPath: outPutMP4Path) {
  391. BFLog(message: "文件夹不存在")
  392. createDirectory(path: outPutMP4Path)
  393. }
  394. outPutMP4Path.append("video_\(String.qe.timestamp()).mp4")
  395. let outPutMP4URL = URL(fileURLWithPath: outPutMP4Path)
  396. BFLog(message: "导出视频地址 \(outPutMP4URL)")
  397. let inputAsset = AVURLAsset(url: URL(fileURLWithPath: documensDirectory + (audioMixModel?.localPath ?? "")), options: avAssertOptions)
  398. // 每次初始化的时候设置初始值 为 nIl
  399. exporter = PQCompositionExporter(asset: inputAsset, videoComposition: nil, audioMix: nil, filters: nil, stickers: mStickers, animationTool: nil, exportURL: outPutMP4URL)
  400. exporter.showGaussianBlur = true
  401. if exporter.prepare(videoSize: CGSize(width: editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0, height: editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0)) {
  402. let playeTimeRange: CMTimeRange = CMTimeRange(start: CMTime(value: CMTimeValue(Int((audioMixModel?.startTime ?? 0) * 600)), timescale: 600), end: CMTime(value: CMTimeValue(Int((audioMixModel?.endTime ?? 0) * 600)), timescale: 600))
  403. BFLog(message: "开始导出 \(String(describing: audioMixModel?.startTime)) 结束 \(String(describing: audioMixModel?.endTime))")
  404. exporter.start(playeTimeRange: playeTimeRange)
  405. BFLog(message: "开始导出")
  406. }
  407. exporter.progressClosure = { [weak self] _, _, progress in
  408. BFLog(message: "合成进度 \(progress)")
  409. let useProgress = progress > 1 ? 1 : progress
  410. if progress > 0, Int(useProgress * 100) > (self?.exportProgrss ?? 0) {
  411. self?.exportProgrss = Int(useProgress * 100)
  412. if (self?.exportProgrss ?? 0) >= 100 {
  413. self?.exportProgrss = 99
  414. }
  415. self?.progressView.setProgress(useProgress, animated: true)
  416. let attributedText = NSMutableAttributedString(string: "\(self?.exportProgrss ?? 0)%\n视频正在处理中,请勿离开")
  417. attributedText.addAttributes([.font: UIFont.systemFont(ofSize: 34)], range: NSRange(location: 0, length: "\(self?.exportProgrss ?? 0)%".count))
  418. self?.progressTipsLab.attributedText = attributedText
  419. }
  420. }
  421. exporter.completion = { [weak self] url in
  422. BFLog(message: "导了完成: \(url)")
  423. // 导出完成后取消导出
  424. if self?.exporter != nil {
  425. self?.exporter.cancel()
  426. }
  427. if !(self?.isExportSuccess ?? false) {
  428. self?.isExportSuccess = true
  429. self?.exportEndDate = Date().timeIntervalSince1970
  430. BFLog(message: "视频导出完成-开始去发布视频")
  431. self?.exportLocalURL = url
  432. /// fp2-1-1 - 请求权限
  433. // self?.authorizationStatus()
  434. /// fp2-2 - 保存草稿
  435. self?.saveDraftbox()
  436. }
  437. }
  438. }
  439. /// fp2-1-1 - 请求权限
  440. func authorizationStatus() {
  441. let authStatus = PHPhotoLibrary.authorizationStatus()
  442. if authStatus == .notDetermined {
  443. // 第一次触发授权 alert
  444. PHPhotoLibrary.requestAuthorization { [weak self] (status: PHAuthorizationStatus) -> Void in
  445. if status != .authorized {
  446. cShowHUB(superView: nil, msg: "您尚未打开相册权限,请到设置页打开相册权限")
  447. } else {
  448. /// fp2-1-2 - 保存视频到相册
  449. self?.saveStuckPointVideo()
  450. }
  451. }
  452. } else if authStatus == .authorized {
  453. /// fp2-1-2 - 保存视频到相册
  454. saveStuckPointVideo()
  455. } else {
  456. // cShowHUB(superView: nil, msg: "您尚未打开相册权限,请到设置页打开相册权限")
  457. }
  458. }
  459. /// fp2-1-2 - 保存视频到相册
  460. /// - Parameter localPath: localPath description
  461. /// - Returns: <#description#>
  462. func saveStuckPointVideo() {
  463. let authStatus = PHPhotoLibrary.authorizationStatus()
  464. if authStatus == .authorized {
  465. let photoLibrary = PHPhotoLibrary.shared()
  466. photoLibrary.performChanges({ [weak self] in
  467. PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: (self?.exportLocalURL)!)
  468. }) { [weak self] isFinished, _ in
  469. DispatchQueue.main.async { [weak self] in
  470. if self?.view != nil {
  471. if isFinished {
  472. // cShowHUB(superView: self!.view, msg: "视频已保存至相册")
  473. } else {
  474. // cShowHUB(superView: self!.view, msg: "视频保存失败")
  475. }
  476. }
  477. }
  478. }
  479. } else {
  480. // cShowHUB(superView: nil, msg: "您尚未打开相册权限,请到设置页打开相册权限")
  481. }
  482. }
  483. /// fp2-2 - 保存草稿
  484. /// - Returns: <#description#>
  485. @objc func saveDraftbox() {
  486. let sdata = editProjectModel?.sData?.toJSONString(prettyPrint: false)
  487. if sdata != nil, (sdata?.count ?? 0) > 0 {
  488. DispatchQueue.global().async { [weak self] in
  489. PQBaseViewModel.saveDraftbox(draftboxId: self?.editProjectModel?.draftboxId, title: self?.editProjectModel?.sData?.videoMetaData?.title, coverUrl: self?.editProjectModel?.sData?.videoMetaData?.coverUrl, sdata: sdata!, videoFromScene: .stuckPoint, copyType: (self?.audioMixModel != nil && self?.audioMixModel?.originProjectId != nil && (self?.audioMixModel?.originProjectId?.count ?? 0) > 0) ? 3 : nil, originProjectId: self?.audioMixModel?.originProjectId) { [weak self] draftboxInfo, _ in
  490. if draftboxInfo != nil {
  491. self?.editProjectModel?.draftboxId = draftboxInfo?["draftboxId"] as? String ?? ""
  492. self?.editProjectModel?.sData?.videoMetaData?.title = draftboxInfo?["title"] as? String ?? ""
  493. self?.editProjectModel?.sData?.videoMetaData?.coverUrl = draftboxInfo?["coverUrl"] as? String ?? ""
  494. self?.editProjectModel?.dataVersionCode = draftboxInfo?["dataVersionCode"] as? Int ?? 0
  495. BFLog(message: "保存远程的草稿成功")
  496. self?.isSaveDraftSuccess = true
  497. /// fp3 - 保存项目
  498. self?.saveProject()
  499. } else {
  500. // 保存草稿失败-播放视频
  501. self?.publicEnd(isError: true)
  502. }
  503. }
  504. }
  505. } else {
  506. cShowHUB(superView: nil, msg: "您尚未打开相册权限,请到设置页打开相册权限")
  507. // 保存草稿失败-播放视频
  508. publicEnd(isError: true)
  509. }
  510. }
  511. /// fp3 - 保存项目
  512. /// - Returns: description
  513. func saveProject() {
  514. if isSaveDraftSuccess, isExportSuccess, exportLocalURL != nil {
  515. let sdata = editProjectModel?.sData?.toJSONString(prettyPrint: false) ?? ""
  516. let draftboxId: String? = editProjectModel?.draftboxId
  517. PQBaseViewModel.saveProject(draftboxId: draftboxId, sdata: sdata, videoFromScene: .stuckPoint) { [weak self] projectId, msg in
  518. BFLog(message: "生成的项目id1111 :\(projectId ?? ""),msg = \(msg ?? "")")
  519. if projectId == nil || (projectId?.count ?? 0) <= 0 {
  520. PQBaseViewModel.saveProject(draftboxId: draftboxId, sdata: sdata, videoFromScene: .stuckPoint) { [weak self] projectId, msg in
  521. BFLog(message: "生成的项目id222 :\(projectId ?? ""),msg = \(msg ?? "")")
  522. if projectId == nil || (projectId?.count ?? 0) <= 0 {
  523. PQBaseViewModel.saveProject(draftboxId: draftboxId, sdata: sdata, videoFromScene: .stuckPoint) { [weak self] projectId, msg in
  524. BFLog(message: "生成的项目id 3333:\(projectId ?? ""),msg = \(msg ?? "")")
  525. if projectId != nil, (projectId?.count ?? 0) > 0 {
  526. self?.editProjectModel?.projectId = projectId ?? ""
  527. }
  528. /// fp4 - 处理视频数据
  529. self?.dealWithVideoData()
  530. }
  531. } else {
  532. self?.editProjectModel?.projectId = projectId ?? ""
  533. /// fp4 - 处理视频数据
  534. self?.dealWithVideoData()
  535. }
  536. }
  537. } else {
  538. self?.editProjectModel?.projectId = projectId ?? ""
  539. /// fp4 - 处理视频数据
  540. self?.dealWithVideoData()
  541. }
  542. }
  543. }
  544. }
  545. /// fp4 - 处理视频数据
  546. /// - Returns: description
  547. @objc func dealWithVideoData() {
  548. BFLog(message: "开始去发布视频12")
  549. isSaveProjectSuccess = true
  550. if isExportSuccess && exportLocalURL != nil {
  551. BFLog(message: "素材上传完成同时视频导出完成开始发布视频")
  552. // 更新项目
  553. PQBaseViewModel.updateProject(projectId: editProjectModel?.projectId ?? "", produceStatus: "5") { repseon, _ in
  554. BFLog(message: "updateProject 结果 is \(String(describing: repseon))")
  555. }
  556. let asset = AVURLAsset(url: exportLocalURL!, options: avAssertOptions)
  557. let tempUploadData = PQUploadModel()
  558. tempUploadData.duration = CMTimeGetSeconds(asset.duration)
  559. tempUploadData.localPath = exportLocalURL?.absoluteString
  560. tempUploadData.videoWidth = CGFloat(editProjectModel?.sData?.videoMetaData?.videoWidth ?? 0)
  561. tempUploadData.videoHeight = CGFloat(editProjectModel?.sData?.videoMetaData?.videoHeight ?? 0)
  562. tempUploadData.image = PQVideoSnapshotUtil.videoSnapshot(videoURL: exportLocalURL!, time: 0)
  563. if tempUploadData.image == nil {
  564. tempUploadData.image = coverImage
  565. }
  566. tempUploadData.videoFromScene = .stuckPoint
  567. eventTrackData = getExportEventTrackData()
  568. eventTrackData?.projectId = editProjectModel?.projectId ?? ""
  569. uploadData = tempUploadData
  570. if uploadData?.image == nil {
  571. uploadData?.image = PQVideoSnapshotUtil.videoSnapshot(videoURL: exportLocalURL!, time: 0)
  572. }
  573. if uploadData?.image != nil {
  574. playerHeaderView.image = uploadData?.image
  575. }
  576. if isExportSuccess, exportLocalURL != nil {
  577. let size = try! exportLocalURL?.resourceValues(forKeys: [.fileSizeKey])
  578. BFLog(message: "size = \(String(describing: size))")
  579. if Float64(size?.fileSize ?? 0) <= maxUploadSize {
  580. /// fp5 - 上传视频
  581. reUploadVideo()
  582. }
  583. }
  584. }
  585. }
  586. /// fp5 - 上传视频
  587. /// - Returns: <#description#>
  588. @objc func reUploadVideo() {
  589. if uploadData?.stsToken != nil {
  590. multipartUpload(response: uploadData?.stsToken)
  591. } else {
  592. uploadVideo()
  593. }
  594. }
  595. /// fp5-1 - 开始上传视频
  596. /// - Returns: <#description#>
  597. func uploadVideo() {
  598. let uploadRequest: OSSMultipartUploadRequest? = PQAliOssUtil.shared.allTasks[uploadData?.videoBucketKey ?? ""]
  599. if uploadRequest != nil, "\(uploadRequest?.callbackParam["code"] ?? "0")" == "1" {
  600. return
  601. }
  602. DispatchQueue.global().async {
  603. PQBaseViewModel.getStsToken { [weak self] response, _ in
  604. if response == nil {
  605. self?.showUploadRemindView(isNetCollected: false, msg: "获取数据失败了哦~")
  606. return
  607. }
  608. BFLog(message: "取我方服务器STS 返回数据 \(String(describing: response))")
  609. self?.multipartUpload(response: response)
  610. }
  611. }
  612. }
  613. /// fp5-2 - 继续上传视频
  614. /// - Parameter response: <#response description#>
  615. func multipartUpload(response: [String: Any]?) {
  616. let FileName: String = "\(response?["FileName"] ?? "")"
  617. let uploadID: String = "\(response?["Upload"] ?? "")"
  618. uploadData?.stsToken = response
  619. uploadData?.videoBucketKey = FileName
  620. uploadData?.uploadID = uploadID
  621. if uploadData?.asset != nil && isValidURL(url: uploadData?.localPath) {
  622. PQPHAssetVideoParaseUtil.exportPHAssetToMP4(phAsset: (uploadData?.asset)!, isCancelCurrentExport: true) { [weak self] _, _, filePath, _ in
  623. if filePath != nil, (filePath?.count ?? 0) > 0 {
  624. self?.uploadData?.localPath = filePath
  625. PQAliOssUtil.multipartUpload(localPath: self?.uploadData?.localPath ?? "", response: response)
  626. }
  627. }
  628. } else {
  629. PQAliOssUtil.multipartUpload(localPath: uploadData?.localPath ?? "", response: response)
  630. }
  631. PQAliOssUtil.shared.aliOssHander = { [weak self] isMatarialUpload, materialType, _, code, objectkey, _, _, _, _, _, _, _, _, _ in
  632. if !isMatarialUpload, materialType == .VIDEO, self?.uploadData?.videoBucketKey == objectkey {
  633. if code == 6 { // 无网
  634. let uploadRequest: OSSMultipartUploadRequest? = PQAliOssUtil.shared.allTasks[self?.uploadData?.videoBucketKey ?? ""]
  635. if !(uploadRequest != nil && "\(uploadRequest?.callbackParam["code"] ?? "0")" == "1") {
  636. self?.showUploadRemindView()
  637. }
  638. } else if code == 260 {
  639. self?.showUploadRemindView(isNetCollected: false)
  640. } else if code != 1 {
  641. // 上传失败-播放视频
  642. self?.publicEnd(isError: true)
  643. }
  644. }
  645. }
  646. }
  647. /// fp6 - 视频上传成功,处理要发布视频数据
  648. /// - Parameter notify: <#notify description#>
  649. @objc func uploadSuccess(notify: NSNotification) {
  650. let objectKey: String = "\(notify.userInfo?["objectKey"] ?? "")"
  651. BFLog(message: "收到上传成功请求==\(notify.userInfo ?? [:])")
  652. if uploadData?.videoBucketKey == objectKey {
  653. // 上传成功
  654. isUploadSuccess = true
  655. /// fp7 - 处理要发布视频数据
  656. dealWithPublicData()
  657. }
  658. }
  659. /// fp7 - 处理要发布视频数据
  660. /// - Returns: <#description#>
  661. func dealWithPublicData() {
  662. if uploadData?.localPath != nil {
  663. let size = try! URL(string: uploadData?.localPath ?? "")?.resourceValues(forKeys: [.fileSizeKey])
  664. BFLog(message: "size = \(String(describing: size))")
  665. if Float64(size?.fileSize ?? 0) > maxUploadSize {
  666. cShowHUB(superView: nil, msg: "无法发布大于10G的视频,请重新选择/合成发布")
  667. // 上传失败-播放视频
  668. publicEnd(isError: true)
  669. return
  670. }
  671. }
  672. let projectId: String? = editProjectModel?.projectId
  673. let uploadRequest: OSSMultipartUploadRequest? = PQAliOssUtil.shared.allTasks[uploadData?.videoBucketKey ?? ""]
  674. if uploadRequest == nil {
  675. reUploadVideo()
  676. return
  677. }
  678. let tempModel = PQVideoListModel()
  679. tempModel.title = ""
  680. tempModel.summary = ""
  681. tempModel.duration = CGFloat(uploadData?.duration ?? 0)
  682. tempModel.uplpadImage = uploadData?.image
  683. tempModel.uplpadBucketKey = uploadRequest?.objectKey
  684. tempModel.localPath = uploadData?.localPath
  685. tempModel.reCreateVideoData = reCreateData
  686. tempModel.eventTrackData = eventTrackData
  687. tempModel.uplpadStatus = 1
  688. tempModel.videoFromScene = .stuckPoint
  689. tempModel.uid = Int(BFLoginUserInfo.shared.uid) ?? 0
  690. tempModel.uplpadRequest = PQAliOssUtil.shared.allTasks[uploadData?.videoBucketKey ?? ""]
  691. tempModel.stsToken = uploadData?.stsToken
  692. tempModel.projectId = projectId
  693. // let tempTitleH: CGFloat = sizeWithText(text: title, font: UIFont.systemFont(ofSize: 16), size: CGSize(width: (cScreenWidth - cDefaultMargin * 3) / 2, height: cDefaultMargin * 4)).height
  694. // let rate: CGFloat = ((uploadData?.image?.size.height ?? 1) / (uploadData?.image?.size.width ?? 1))
  695. // tempModel.itemHeight = (cScreenWidth - cDefaultMargin * 3) / 2 * rate + tempTitleH + cDefaultMargin * 4.5
  696. // let isContains = PQSingletoMemoryUtil.shared.uploadDatas.contains { (item) -> Bool in
  697. // item.uplpadBucketKey == tempModel.uplpadBucketKey
  698. // }
  699. // if !isContains {
  700. // BFLog(message: "添加正在上传数据===\(tempModel)")
  701. // PQSingletoMemoryUtil.shared.uploadDatas.insert(tempModel, at: 0)
  702. // }
  703. // currentController().dismiss(animated: false) {
  704. // currentController().navigationController?.viewControllers = [currentController().navigationController?.viewControllers.first ?? PQBaseViewController()]
  705. // rootViewController()?.selectedIndex = 4
  706. // if !isContains {
  707. // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
  708. // postNotification(name: cPublishSuccessKey)
  709. // }
  710. // }
  711. // }
  712. /// fp8 - 发布视频
  713. publicVideo(videoData: tempModel)
  714. }
  715. /// fp8 - 发布视频
  716. /// - Parameter videoData: <#videoData description#>
  717. func publicVideo(videoData: PQVideoListModel) {
  718. if videoData.uplpadBucketKey == nil {
  719. BFLog(message: "发布视频:视频uplpadBucketKey为空-\(String(describing: videoData.uplpadBucketKey))")
  720. // 上传失败-播放视频
  721. publicEnd(isError: true)
  722. return
  723. }
  724. BFLog(message: "开始发布")
  725. if (videoData.eventTrackData?.endUploadDate ?? 0) <= 0 {
  726. // 结束上传时间
  727. videoData.eventTrackData?.endUploadDate = Date().timeIntervalSince1970
  728. }
  729. DispatchQueue.global().async {
  730. PQBaseViewModel.ossTempToken { [weak self] response, _ in
  731. let image: UIImage = videoData.uplpadImage ?? UIImage()
  732. let data = image.jpegData(compressionQuality: 1)
  733. let accessKeyId: String = "\(response?["accessKeyId"] ?? "")"
  734. let secretKeyId: String = "\(response?["accessKeySecret"] ?? "")"
  735. let securityToken: String = "\(response?["securityToken"] ?? "")"
  736. let endpoint: String = "\(response?["endPoint"] ?? "")"
  737. let bucketName: String = "\(response?["bucketName"] ?? "")"
  738. let objectKey: String = "\(response?["objectKey"] ?? "")"
  739. BFLog(message: "开始上传视频图片==\(videoData.title ?? ""),uplpadBucketKey = \(videoData.uplpadBucketKey ?? ""),objectKey =\(objectKey)")
  740. PQAliOssUtil.shared
  741. .startClient(
  742. accessKeyId: accessKeyId,
  743. secretKeyId: secretKeyId,
  744. securityToken: securityToken,
  745. endpoint: endpoint
  746. )
  747. .uploadObjectAsync(bucketName: bucketName, objectKey: objectKey, data: data!, fileExtensions: "png", imageUploadBlock: { _, code, ossObjectKey, _ in
  748. BFLog(message: "图片上传完成==\(videoData.title ?? ""),uplpadBucketKey = \(videoData.uplpadBucketKey ?? ""),objectKey =\(objectKey),ossObjectKey = \(ossObjectKey)")
  749. if code == 1 && ossObjectKey == objectKey && objectKey.count > 0 {
  750. BFLog(message: "开始发布==\(videoData.title ?? ""),uplpadBucketKey = \(videoData.uplpadBucketKey ?? ""),objectKey =\(objectKey),ossObjectKey = \(ossObjectKey)")
  751. PQUploadViewModel.publishVideo(projectId: videoData.projectId, fileExtensions: videoData.localPath?.pathExtension, title: videoData.title ?? "", videoPath: videoData.uplpadBucketKey ?? "", coverImgPath: objectKey, descr: videoData.summary ?? "", videoFromScene: .stuckPoint, reCreateData: videoData.reCreateVideoData, eventTrackData: videoData.eventTrackData) { [weak self] newVideoData, _, _ in
  752. postNotification(name: cPublishStuckPointSuccessKey, userInfo: ["newVideoData": newVideoData!])
  753. BFLog(message: "发布成功==\(videoData.title ?? ""),uplpadBucketKey = \(videoData.uplpadBucketKey ?? ""),objectKey =\(objectKey),ossObjectKey = \(ossObjectKey)")
  754. // cShowHUB(superView: nil, msg: "视频发布成功")
  755. self?.videoData = newVideoData
  756. // 发布成功后续操作
  757. self?.publicEnd()
  758. PQEventTrackViewModel.publishReportUpload(projectId: videoData.projectId, businessType: .bt_publish_success, ossInfo: videoData.stsToken ?? [:], params: ["title": videoData.title ?? "", "videoPath": videoData.uplpadBucketKey ?? "", "coverImgPath": objectKey, "descr": videoData.summary ?? ""])
  759. }
  760. } else {
  761. // 图片上传失败
  762. BFLog(message: "图片上传失败重新发布视频==\(videoData.title ?? ""),\(videoData.uplpadBucketKey ?? "")")
  763. self?.publicVideo(videoData: videoData)
  764. }
  765. })
  766. }
  767. }
  768. }
  769. /// 发布结束操作
  770. /// - Parameter isError: <#isError description#>
  771. /// - Returns: <#description#>
  772. func publicEnd(isError: Bool = false) {
  773. UIApplication.shared.keyWindow?.viewWithTag(100_100)?.removeFromSuperview()
  774. isPublicSuccess = true
  775. progressView.removeFromSuperview()
  776. progressTipsLab.removeFromSuperview()
  777. oprationBgView.removeFromSuperview()
  778. playBtn.isHidden = true
  779. finishedBtn.isSelected = true
  780. finishedBtn.backgroundColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
  781. avPlayer.replaceCurrentItem(with: AVPlayerItem(url: URL(fileURLWithPath: (exportLocalURL?.absoluteString ?? "").replacingOccurrences(of: "file:///", with: ""))))
  782. avPlayer.play()
  783. if isError {
  784. cShowHUB(superView: nil, msg: "视频发布失败,请重新合成")
  785. } else {
  786. remindLab.isHidden = false
  787. /// fp2-1-1 - 请求权限
  788. authorizationStatus()
  789. }
  790. }
  791. /// 生成创作工具埋点数据
  792. /// - Returns: <#description#>
  793. func getExportEventTrackData() -> PQVideoMakeEventTrackModel? {
  794. let eventTrackData = PQVideoMakeEventTrackModel(projectModel: editProjectModel, reCreateData: reCreateData)
  795. eventTrackData.entrance = .entranceStuckPointPublic
  796. eventTrackData.editTimeCost = 0
  797. eventTrackData.composeTimeCost = (exportEndDate - startExportDate) * 1000
  798. eventTrackData.musicName = audioMixModel?.musicName ?? ""
  799. eventTrackData.syncedUpMusicName = audioMixModel?.musicName ?? ""
  800. eventTrackData.musicId = audioMixModel?.musicId ?? ""
  801. eventTrackData.syncedUpMusicId = audioMixModel?.musicId ?? ""
  802. eventTrackData.musicUrl = audioMixModel?.selectVoiceType == 1 ? (audioMixModel?.musicPath ?? "") : (audioMixModel?.accompanimentPath ?? "")
  803. eventTrackData.musicType = audioMixModel != nil ? (audioMixModel?.selectVoiceType == 1 ? "original" : "accompaniment") : ""
  804. eventTrackData.isMusicClip = (audioMixModel?.startTime ?? 0) > 0
  805. if editProjectModel?.sData?.videoMetaData?.canvasType == videoCanvasType.origin.rawValue {
  806. eventTrackData.canvasRatio = "original"
  807. } else if editProjectModel?.sData?.videoMetaData?.canvasType == videoCanvasType.nineToSixteen.rawValue {
  808. eventTrackData.canvasRatio = "9:16"
  809. } else if editProjectModel?.sData?.videoMetaData?.canvasType == videoCanvasType.oneToOne.rawValue {
  810. eventTrackData.canvasRatio = "1:1"
  811. } else if editProjectModel?.sData?.videoMetaData?.canvasType == videoCanvasType.sixteenToNine.rawValue {
  812. eventTrackData.canvasRatio = "16:9"
  813. }
  814. eventTrackData.syncedUpVideoNumber = selectedDataCount - selectedImageDataCount
  815. eventTrackData.syncedUpImageNumber = selectedImageDataCount
  816. eventTrackData.syncedUpOriginalMaterialDuration = selectedTotalDuration * 1000
  817. eventTrackData.syncedUpRhythmNumber = audioMixModel?.speed ?? 2
  818. eventTrackData.syncedUpVideoDuration = ((audioMixModel?.endTime ?? 0) - (audioMixModel?.startTime ?? 0)) * 1000
  819. return eventTrackData
  820. }
  821. /// 播放视频
  822. /// - Returns: <#description#>
  823. @objc func playVideo() {
  824. playBtn.isHidden = !playBtn.isHidden
  825. if playBtn.isHidden {
  826. avPlayer.play()
  827. } else {
  828. avPlayer.pause()
  829. }
  830. }
  831. /// 按钮点击事件
  832. /// - Parameter sender: <#sender description#>
  833. /// - Returns: <#description#>
  834. @objc func btnClick(sender: UIButton) {
  835. switch sender.tag {
  836. case 1:
  837. if !(isExportSuccess && isSaveProjectSuccess && isUploadSuccess && isPublicSuccess) {
  838. cShowHUB(superView: nil, msg: "视频发布失败,请重新合成")
  839. return
  840. }
  841. if !PQSingletoWXApiUtil.shared.isInstallWX() {
  842. cShowHUB(superView: nil, msg: "您还未安装微信客户端!")
  843. return
  844. }
  845. cShowHUB(superView: nil, msg: nil)
  846. let shareId = getUniqueId(desc: "\(videoData?.uniqueId ?? "")shareId")
  847. PQBaseViewModel.wxFriendShareInfo(videoId: (videoData?.uniqueId)!) { [weak self] imagePath, title, shareWeappRawId, msg in
  848. if msg != nil {
  849. cShowHUB(superView: nil, msg: "网络不佳哦")
  850. return
  851. }
  852. self?.isShared = true
  853. PQSingletoWXApiUtil.shared.share(type: 3, scene: Int32(WXSceneSession.rawValue), shareWeappRawId: shareWeappRawId, title: title, description: title, imageUrl: imagePath, path: self?.videoData?.videoPath, videoId: (self?.videoData?.uniqueId)!, pageSource: self?.videoData?.pageSource ?? .sp_category, shareId: shareId).wxApiUtilHander = { _, _ in
  854. }
  855. cHiddenHUB(superView: nil)
  856. }
  857. // 点击上报:分享微信
  858. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_click_shareWechat, pageSource: .sp_stuck_publishSyncedUp, extParams: ["videoId": videoData?.uniqueId ?? ""], remindmsg: "卡点视频数据上报-(点击上报:分享微信)")
  859. case 2:
  860. if !(isExportSuccess && isSaveProjectSuccess && isUploadSuccess && isPublicSuccess) {
  861. cShowHUB(superView: nil, msg: "视频发布失败,请重新合成")
  862. return
  863. }
  864. if !PQSingletoWXApiUtil.shared.isInstallWX() {
  865. cShowHUB(superView: nil, msg: "您还未安装微信客户端!")
  866. return
  867. }
  868. let shareId = getUniqueId(desc: "\(videoData?.uniqueId ?? "")shareId")
  869. PQBaseViewModel.h5ShareLinkInfo(videoId: videoData?.uniqueId ?? "", pageSource: videoData?.pageSource ?? .sp_category) { [weak self] path, _ in
  870. cHiddenHUB(superView: nil)
  871. if path != nil {
  872. self?.isShared = true
  873. PQSingletoWXApiUtil.shared.share(type: 1, scene: Int32(WXSceneTimeline.rawValue), title: BFLoginUserInfo.shared.isLogin() ? "\(BFLoginUserInfo.shared.nickName)made a music video for you" : "Music Video for U", description: "", imageUrl: self?.videoData?.shareImgPath, path: path, videoId: (self?.videoData?.uniqueId)!, pageSource: self?.videoData?.pageSource ?? .sp_category, shareId: shareId).wxApiUtilHander = { _, _ in
  874. }
  875. } else {
  876. cShowHUB(superView: nil, msg: "网络不佳哦")
  877. }
  878. }
  879. // 点击上报:分享朋友圈
  880. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_click_shareWechatMoment, pageSource: .sp_stuck_publishSyncedUp, extParams: ["videoId": videoData?.uniqueId ?? ""], remindmsg: "卡点视频数据上报-(点击上报:分享朋友圈)")
  881. case 3:
  882. if sender.isSelected {
  883. // 点击上报:完成
  884. PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_click_finished, pageSource: .sp_stuck_publishSyncedUp, extParams: ["videoId": videoData?.uniqueId ?? ""], remindmsg: "卡点视频数据上报-(点击上报:完成)")
  885. navigationController?.viewControllers = [(navigationController?.viewControllers.first)!]
  886. // 发送通知
  887. postNotification(name: cFinishedPublishedNotiKey)
  888. }
  889. default:
  890. break
  891. }
  892. }
  893. /// 添加提示视图
  894. /// - Parameters:
  895. /// - isNetCollected: <#isNetCollected description#>
  896. /// - msg: <#msg description#>
  897. func showUploadRemindView(isNetCollected _: Bool = true, msg _: String? = nil) {
  898. view.endEditing(true)
  899. // PQUploadRemindView.showUploadRemindView(title: isNetCollected ? "上传中断" : "上传失败", summary: (isNetCollected ? "似乎已断开与互联网的连接" : (msg != nil ? msg : "视频文件已丢失"))!, confirmTitle: isNetCollected ? "重新连接网络" : "重新上传") { [weak self] _, _ in
  900. // if isNetCollected {
  901. // openAppSetting()
  902. // } else {
  903. // self?.navigationController?.popToViewController((self?.navigationController?.viewControllers[1])!, animated: true)
  904. // }
  905. // }
  906. }
  907. @objc func enterBackground() {
  908. BFLog(message: "进入到后台")
  909. // 取消导出
  910. if exporter != nil {
  911. exporter.cancel()
  912. }
  913. playBtn.isHidden = false
  914. avPlayer.pause()
  915. }
  916. @objc func willEnterForeground() {
  917. BFLog(message: "进入到前台")
  918. if !isExportSuccess {
  919. beginExport()
  920. }
  921. playBtn.isHidden = true
  922. avPlayer.play()
  923. }
  924. @objc func didBecomeActiveNotification() {
  925. if isShared {
  926. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) { [weak self] in
  927. self?.isShared = false
  928. cShowHUB(superView: nil, msg: "分享成功")
  929. }
  930. }
  931. }
  932. }