PQStuckPointPublicController.swift 48 KB

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