PQStuckPointPublicController.swift 49 KB

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