PQStuckPointPublicController.swift 49 KB

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