This repository has been archived by the owner on May 6, 2024. It is now read-only.
/
VideoBlockViewController.swift
692 lines (596 loc) · 27.7 KB
/
VideoBlockViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//
// VideoBlockViewController.swift
// edX
//
// Created by Akiva Leffert on 5/6/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
import MediaPlayer
import UIKit
class VideoBlockViewController : OfflineSupportViewController, CourseBlockViewController, StatusBarOverriding, InterfaceOrientationOverriding, VideoTranscriptDelegate, RatingViewControllerDelegate, VideoPlayerDelegate, ScrollableDelegateProvider {
typealias Environment = DataManagerProvider & OEXInterfaceProvider & ReachabilityProvider & OEXConfigProvider & OEXRouterProvider & OEXAnalyticsProvider & OEXStylesProvider & OEXSessionProvider & NetworkManagerProvider
let environment : Environment
let blockID : CourseBlockID?
let courseQuerier : CourseOutlineQuerier
let videoPlayer: VideoPlayer
let loader = BackedStream<CourseBlock>()
var videoTranscriptView : VideoTranscript?
var subtitleTimer = Timer()
var contentView : UIView?
let loadController : LoadStateViewController
private var VOEnabledOnScreen = false
var rotateDeviceMessageView : IconMessageView?
private var video: OEXHelperVideoDownload?
private let chromeCastManager = ChromeCastManager.shared
private var chromeCastMiniPlayer: ChromeCastMiniPlayer?
private var playOverlayButton: UIButton?
private var overlayLabel: UILabel?
var shouldCelebrationAppear: Bool
weak var scrollableDelegate: ScrollableDelegate? {
didSet {
videoTranscriptView?.scrollableDelegate = scrollableDelegate
}
}
init(environment : Environment, blockID : CourseBlockID?, courseID: String, shouldCelebrationAppear: Bool = false) {
self.blockID = blockID
self.environment = environment
self.shouldCelebrationAppear = shouldCelebrationAppear
courseQuerier = environment.dataManager.courseDataManager.querierForCourseWithID(courseID: courseID, environment: environment)
loadController = LoadStateViewController()
let block = courseQuerier.blockWithID(id: blockID)
// highest priority givin to youtube video if requested by the server
// video prority depends on the wafle flag videos.deprecate_youtube
// if a video is downloaded give prority to the downloaded video
var videoDownloaded = false
if let video = environment.interface?.stateForVideo(withID: blockID, courseID : courseID) {
let path = "\(video.filePath).mp4"
videoDownloaded = FileManager.default.fileExists(atPath: path)
}
if environment.config.youtubeVideoConfig.enabled && block.value?.type.asVideo?.isYoutubeVideo ?? false && !videoDownloaded {
videoPlayer = YoutubeVideoPlayer(environment: environment)
}
else {
videoPlayer = VideoPlayer(environment: environment)
}
super.init(env: environment)
addChild(videoPlayer)
videoPlayer.didMove(toParent: self)
videoPlayer.playerDelegate = self
videoPlayer.shouldCelebrationAppear = shouldCelebrationAppear
addLoadListener()
}
var courseID : String {
return courseQuerier.courseID
}
var block: CourseBlock? {
return courseQuerier.blockWithID(id: blockID).firstSuccess().value
}
required init?(coder aDecoder: NSCoder) {
// required by the compiler because UIViewController implements NSCoding,
// but we don't actually want to serialize these things
fatalError("init(coder:) has not been implemented")
}
func addLoadListener() {
loader.listen (self,
success : { [weak self] block in
guard let video = self?.environment.interface?.stateForVideo(withID: self?.blockID, courseID : self?.courseID) else {
self?.showError(error: nil)
return
}
if video.summary?.isYoutubeVideo ?? false {
if self?.environment.config.youtubeVideoConfig.enabled ?? false {
self?.showLoadedBlock(block: block, forVideo: video)
}
else {
if let url = block.blockURL {
self?.showYoutubeMessage(url: url as URL)
}
}
}
else if block.type.asVideo?.preferredEncoding != nil {
self?.showLoadedBlock(block: block, forVideo: video)
}
else {
self?.showError(error: nil)
}
}, failure : {[weak self] error in
self?.showError(error: error)
}
)
}
override func viewDidLoad() {
super.viewDidLoad()
contentView = UIView(frame: CGRect.zero)
view.addSubview(contentView!)
loadController.setupInController(controller: self, contentView : contentView!)
contentView?.addSubview(videoPlayer.view)
videoPlayer.view.translatesAutoresizingMaskIntoConstraints = false
rotateDeviceMessageView = IconMessageView(icon: .RotateDevice, message: Strings.rotateDevice)
contentView?.addSubview(rotateDeviceMessageView!)
let tapGesture = UITapGestureRecognizer()
tapGesture.addAction {[weak self] _ in
self?.videoPlayer.hideAndShowControls(isHidden: true)
}
rotateDeviceMessageView?.addGestureRecognizer(tapGesture)
if environment.config.isVideoTranscriptEnabled {
videoTranscriptView = VideoTranscript(environment: environment)
videoTranscriptView?.delegate = self
contentView?.addSubview(videoTranscriptView!.transcriptTableView)
}
view.backgroundColor = OEXStyles.shared().standardBackgroundColor()
view.setNeedsUpdateConstraints()
NotificationCenter.default.oex_addObserver(observer: self, name: UIAccessibility.voiceOverStatusDidChangeNotification.rawValue) { (_, observer, _) in
observer.setAccessibility()
}
chromeCastManager.viewExpanded = false
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
}
private func configureChromecast() {
guard let video = video else { return }
if !chromeCastManager.isConnected || chromeCastMiniPlayer != nil { return }
chromeCastMiniPlayer = ChromeCastMiniPlayer(environment: environment)
let isYoutubeVideo = (video.summary?.isYoutubeVideo ?? true)
guard let chromeCastMiniPlayer = chromeCastMiniPlayer, !isYoutubeVideo else { return }
addChild(chromeCastMiniPlayer)
contentView?.addSubview(chromeCastMiniPlayer.view)
chromeCastMiniPlayer.didMove(toParent: self)
}
private func resetChromeCast() {
for controller in children {
if controller == chromeCastMiniPlayer {
controller.willMove(toParent: nil)
controller.view.removeFromSuperview()
controller.removeFromParent()
}
}
chromeCastManager.remove(delegate: self)
removeOverlayMessage()
removeChromeCastButton()
chromeCastMiniPlayer = nil
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if !chromeCastManager.viewExpanded {
resetChromeCast()
}
}
override func viewDidAppear(_ animated : Bool) {
// There's a weird OS bug where the bottom layout guide doesn't get set properly until
// the layout cycle after viewDidAppear so cause a layout cycle
view.setNeedsUpdateConstraints()
view.updateConstraintsIfNeeded()
view.setNeedsLayout()
view.layoutIfNeeded()
super.viewDidAppear(animated)
if !chromeCastManager.viewExpanded {
loadVideoIfNecessary()
}
chromeCastManager.add(delegate: self)
chromeCastManager.viewExpanded = false
if !chromeCastManager.isConnected && videoTranscriptView?.transcripts.count ?? 0 > 0 {
validateSubtitleTimer()
}
if !(video?.summary?.isYoutubeVideo ?? true) {
addChromeCastButton()
showChromeCastOverlay()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
subtitleTimer.invalidate()
}
private func addChromeCastButton() {
guard let parent = parent else { return }
chromeCastManager.addChromeCastButton(over: parent)
}
private func removeChromeCastButton() {
guard let parent = parent else { return }
chromeCastManager.removeChromeCastButton(from: parent, force: true)
}
func setAccessibility() {
if let ratingController = presentedViewController as? RatingViewController, UIAccessibility.isVoiceOverRunning {
// If Timely App Reviews popup is showing then set popup elements as accessibilityElements
view.accessibilityElements = [ratingController.ratingContainerView.subviews]
setParentAccessibility(ratingController: ratingController)
VOEnabledOnScreen = true
}
else {
view.accessibilityElements = [view.subviews]
setParentAccessibility()
}
}
func setParentAccessibility(ratingController: RatingViewController? = nil) {
if let parentController = parent as? CourseContentPageViewController {
if let ratingController = ratingController {
parentController.setAccessibility(elements: ratingController.ratingContainerView.subviews, isShowingRating: true)
}
else {
parentController.setAccessibility(elements: parentController.view.subviews)
}
}
}
private func loadVideoIfNecessary() {
if let video = environment.interface?.stateForVideo(withID: blockID, courseID : courseID), loader.hasBacking {
self.video = video
play(video: video)
}
else if !loader.hasBacking {
loader.backWithStream(courseQuerier.blockWithID(id: blockID).firstSuccess())
}
}
private func updateControlsVisibility(hide: Bool) {
rotateDeviceMessageView?.isHidden = hide
videoTranscriptView?.transcriptTableView.isHidden = hide
chromeCastManager.isMiniPlayerAdded = hide
chromeCastMiniPlayer?.view.isHidden = !hide
}
private func cast(video: OEXHelperVideoDownload, time: TimeInterval? = nil) {
addOverly(with: Strings.chromecastMessage)
updateControlsVisibility(hide: true)
videoPlayer.loadingIndicatorView.stopAnimating()
videoPlayer.removeControls()
configureChromecast()
var playedTime: TimeInterval = 0.0
if let time = time {
playedTime = time
}
else {
playedTime = TimeInterval(environment.interface?.lastPlayedInterval(forVideo: video) ?? 0)
}
chromeCastMiniPlayer?.play(video: video, time: playedTime)
}
private func playLocally(video: OEXHelperVideoDownload, time: TimeInterval? = nil) {
updateControlsVisibility(hide: false)
videoPlayer.play(video: video, time: time)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updateViewConstraints()
}
override func updateViewConstraints() {
if isVerticallyCompact() {
applyLandscapeConstraints()
}
else{
applyPortraitConstraints()
}
super.updateViewConstraints()
}
private func applyPortraitConstraints() {
guard let contentView = contentView else { return }
contentView.snp.remakeConstraints { make in
make.edges.equalTo(safeEdges)
}
videoPlayer.view.snp.remakeConstraints { make in
make.leading.equalTo(contentView)
make.trailing.equalTo(contentView)
make.top.equalTo(safeTop)
make.height.equalTo(view.bounds.size.width * CGFloat(STANDARD_VIDEO_ASPECT_RATIO))
}
rotateDeviceMessageView?.snp.remakeConstraints { make in
make.top.equalTo(videoPlayer.view.snp.bottom)
make.leading.equalTo(contentView)
make.trailing.equalTo(contentView)
make.bottom.equalTo(safeBottom)
}
videoTranscriptView?.transcriptTableView.snp.remakeConstraints { make in
make.top.equalTo(videoPlayer.view.snp.bottom)
make.leading.equalTo(contentView)
make.trailing.equalTo(contentView)
let barHeight = navigationController?.toolbar.frame.size.height ?? 0.0
make.bottom.equalTo(view.snp.bottom).offset(-barHeight)
}
setChromeCastPlayerConstraints()
}
private func applyLandscapeConstraints() {
guard let contentView = contentView else { return }
contentView.snp.remakeConstraints { make in
make.edges.equalTo(safeEdges)
}
var playerHeight = view.bounds.size.height - (navigationController?.toolbar.bounds.height ?? 0)
if chromeCastManager.isMiniPlayerAdded {
playerHeight -= ChromeCastMiniPlayerHeight
}
videoPlayer.view.snp.remakeConstraints { make in
make.leading.equalTo(contentView)
make.trailing.equalTo(contentView)
make.top.equalTo(safeTop)
make.height.equalTo(playerHeight)
}
videoTranscriptView?.transcriptTableView.snp.remakeConstraints { make in
make.top.equalTo(videoPlayer.view.snp.bottom)
make.leading.equalTo(contentView)
make.trailing.equalTo(contentView)
make.bottom.equalTo(safeBottom)
}
rotateDeviceMessageView?.snp.remakeConstraints { make in
make.height.equalTo(0.0)
}
setChromeCastPlayerConstraints()
}
private func setChromeCastPlayerConstraints() {
chromeCastMiniPlayer?.view.snp.remakeConstraints { make in
make.leading.equalTo(safeLeading)
make.trailing.equalTo(safeTrailing)
make.height.equalTo(ChromeCastMiniPlayerHeight)
make.bottom.equalTo(safeBottom)
}
}
private func showError(error : NSError?) {
loadController.state = LoadState.failed(error: error, icon: .UnknownError, message: Strings.videoContentNotAvailable)
}
private func showYoutubeMessage(url: URL) {
let buttonInfo = MessageButtonInfo(title: Strings.Video.viewOnYoutube) {
if UIApplication.shared.canOpenURL(url){
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
loadController.state = LoadState.empty(icon: .CourseVideos, message: Strings.Video.onlyOnYoutube, attributedMessage: nil, accessibilityMessage: nil, buttonInfo: buttonInfo)
}
private func showLoadedBlock(block : CourseBlock, forVideo video: OEXHelperVideoDownload) {
self.video = video
navigationItem.title = block.displayName
videoPlayer.videoTitle = block.displayName
DispatchQueue.main.async { [weak self] in
self?.loadController.state = .Loaded
}
if !shouldCelebrationAppear {
DispatchQueue.main.async { [weak self] in
self?.play(video: video)
}
}
}
private func play(video: OEXHelperVideoDownload) {
if chromeCastManager.isConnected && !(video.summary?.isYoutubeVideo ?? true) {
cast(video: video)
} else {
playLocally(video: video)
}
environment.interface?.insertVideoData(video)
}
override var childForStatusBarStyle: UIViewController? {
return videoPlayer
}
override var childForStatusBarHidden: UIViewController? {
return videoPlayer
}
private func validateSubtitleTimer() {
if !subtitleTimer.isValid {
subtitleTimer = Timer.scheduledTimer(timeInterval: 1.0,
target: self,
selector: #selector(highlightSubtitle),
userInfo: nil,
repeats: true)
}
}
@objc private func highlightSubtitle() {
videoTranscriptView?.highlightSubtitle(for: videoPlayer.currentTime)
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
DispatchQueue.main.async {[weak self] in
if let weakSelf = self {
if weakSelf.chromeCastManager.isMiniPlayerAdded { return }
if weakSelf.videoPlayer.isFullScreen {
if newCollection.verticalSizeClass == .regular {
weakSelf.videoPlayer.setFullscreen(fullscreen: false, animated: true, with: weakSelf.currentOrientation(), forceRotate: false)
}
else {
weakSelf.videoPlayer.setFullscreen(fullscreen: true, animated: true, with: weakSelf.currentOrientation(), forceRotate: false)
}
}
else if newCollection.verticalSizeClass == .compact && !weakSelf.shouldCelebrationAppear {
weakSelf.videoPlayer.setFullscreen(fullscreen: true, animated: true, with: weakSelf.currentOrientation(), forceRotate: false)
}
}
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.userInterfaceIdiom == .pad {
if videoPlayer.isFullScreen {
videoPlayer.setFullscreen(fullscreen: !UIDevice.current.orientation.isPortrait, animated: true, with: currentOrientation(), forceRotate: false)
} else if UIDevice.current.orientation.isLandscape {
videoPlayer.setFullscreen(fullscreen: true, animated: true, with: currentOrientation(), forceRotate: false)
}
} else {
DispatchQueue.main.async { [weak self] in
if let weakSelf = self {
if weakSelf.chromeCastManager.isMiniPlayerAdded { return }
if weakSelf.videoPlayer.isFullScreen {
if UITraitCollection.current.verticalSizeClass == .regular {
weakSelf.videoPlayer.setFullscreen(fullscreen: false, animated: true, with: weakSelf.currentOrientation(), forceRotate: false)
} else {
weakSelf.videoPlayer.setFullscreen(fullscreen: true, animated: true, with: weakSelf.currentOrientation(), forceRotate: false)
}
} else if UITraitCollection.current.verticalSizeClass == .compact && !weakSelf.shouldCelebrationAppear {
weakSelf.videoPlayer.setFullscreen(fullscreen: true, animated: true, with: weakSelf.currentOrientation(), forceRotate: false)
}
}
}
}
}
//MARK: - VideoTranscriptDelegate methods
func didSelectSubtitleAtInterval(time: TimeInterval) {
videoPlayer.seek(to: time)
}
//MARK: - RatingDelegate
func didDismissRatingViewController() {
let after = DispatchTime.now() + Double(Int64(1.2 * TimeInterval(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: after) { [weak self] in
self?.setAccessibility()
//VO behave weirdly. If Rating view appears while VO is on then then VO consider it as screen otherwise it will treat as layout
// Will revisit this logic when VO behaves same in all cases.
self?.VOEnabledOnScreen ?? false ? UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: self?.navigationItem.backBarButtonItem) : UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: self?.navigationItem.backBarButtonItem)
self?.VOEnabledOnScreen = false
}
}
override public var shouldAutorotate: Bool {
return true
}
override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .allButUpsideDown
}
func playerDidFinishLoad(videoPlayer: VideoPlayer) {
if let frame = videoPlayer.controlsBottomBarFrame, let contentView = parent as? CourseContentPageViewController {
contentView.restrictedPaginationAreaStart = frame.origin.y
contentView.restrictedPaginationAreaEnd = (frame.origin.y) + (frame.size.height)
}
}
func playerWillMoveFromWindow(videoPlayer: VideoPlayer) {
videoPlayer.view.snp.remakeConstraints { make in
make.top.equalTo(safeTop)
make.width.equalTo(view.bounds.size.width)
make.height.equalTo(view.bounds.size.width * CGFloat(STANDARD_VIDEO_ASPECT_RATIO))
}
}
func playerDidStopPlaying(videoPlayer: VideoPlayer, duration: Double, currentTime: Double) {
if let video = environment.interface?.stateForVideo(withID: blockID, courseID : courseID) {
environment.interface?.markLastPlayedInterval(Float(currentTime), forVideo: video)
let state = doublesWithinEpsilon(left: duration, right: currentTime) ? OEXPlayedState.watched : OEXPlayedState.partiallyWatched
environment.interface?.markVideoState(state, forVideo: video)
}
}
func playerDidLoadTranscripts(videoPlayer:VideoPlayer, transcripts: [TranscriptObject]) {
videoTranscriptView?.updateTranscript(transcript: transcripts)
validateSubtitleTimer()
}
func playerDidFinishPlaying(videoPlayer: VideoPlayer) {
environment.router?.showAppReviewIfNeeded(fromController: self)
markBlockAsComplete()
}
func playerDidTimeout(videoPlayer: VideoPlayer) {
if videoPlayer.isFullScreen {
UIAlertController().showAlert(withTitle: Strings.timeoutCheckInternetConnection, message: "", cancelButtonTitle: Strings.close, onViewController: self)
}
else {
addOverly(with: Strings.timeoutCheckInternetConnection)
}
}
func playerDidFailedPlaying(videoPlayer: VideoPlayer, errorMessage: String) {
if videoPlayer.isFullScreen {
UIAlertController().showAlert(withTitle: errorMessage, message: "", cancelButtonTitle: Strings.close, onViewController: self)
}
else {
addOverly(with: errorMessage)
}
}
//MARK:- ChromeCastHelper
private func showChromeCastOverlay() {
// Introductory overlay needs reference to castButton which is available in CourseContentPageViewController,
// This function calls before the castButton is initialized so we get x, y as 0 in its container,
// We put a delay of 2 sec to get castButton from navigationbar item then decouple it and assgin to call.
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
guard let parentController = self?.parent as? CourseContentPageViewController,
let items = parentController.navigationItem.rightBarButtonItems else { return }
self?.chromeCastManager.showIntroductoryOverlay(items: items)
}
}
private func addOverly(with message: String) {
if overlayLabel != nil { return }
removeOverlayPlayButton()
overlayLabel = UILabel()
overlayLabel?.numberOfLines = 0
guard let overlayLabel = overlayLabel else { return }
view.addSubview(overlayLabel)
let style = OEXTextStyle(weight: .normal, size: .large, color: .white)
overlayLabel.attributedText = style.attributedString(withText: message)
overlayLabel.snp.makeConstraints({ (make) in
make.center.equalTo(videoPlayer.view)
})
}
private func removeOverlayMessage() {
chromeCastMiniPlayer?.view.isHidden = true
overlayLabel?.text = ""
overlayLabel?.isHidden = true
overlayLabel?.removeFromSuperview()
overlayLabel = nil
}
func createOverlayPlayButton() {
if playOverlayButton != nil { return }
chromeCastManager.isMiniPlayerAdded = false
removeOverlayMessage()
playOverlayButton = UIButton()
playOverlayButton?.tintColor = .white
playOverlayButton?.setImage(UIImage.PlayIcon(), for: .normal)
playOverlayButton?.oex_addAction({ [weak self] _ in
self?.playButtonAction()
}, for: .touchUpInside)
guard let playOverlayButton = playOverlayButton else { return }
view.addSubview(playOverlayButton)
playOverlayButton.snp.makeConstraints { make in
make.center.equalTo(videoPlayer.view)
make.height.equalTo(26)
make.width.equalTo(26)
}
}
@objc func playButtonAction() {
removeOverlayPlayButton()
loadVideoIfNecessary()
}
private func removeOverlayPlayButton() {
playOverlayButton?.isHidden = true
playOverlayButton?.removeFromSuperview()
playOverlayButton = nil
}
@objc override func reloadViewData() {
removeOverlayMessage()
loadVideoIfNecessary()
}
}
extension VideoBlockViewController {
func markBlockAsComplete() {
if let block = block {
if !block.isCompleted {
block.isCompleted = true
}
}
guard let username = environment.session.currentUser?.username, let blockID = blockID else { return }
let networkRequest = BlockCompletionApi.blockCompletionRequest(username: username, courseID: courseID, blockID: blockID)
environment.networkManager.taskForRequest(networkRequest) { _ in }
}
}
//MARK:- ChromeCastPlayerStatusDelegate
extension VideoBlockViewController: ChromeCastPlayerStatusDelegate {
func chromeCastDidConnect() {
if videoPlayer.isFullScreen {
videoPlayer.setFullscreen(fullscreen: false, animated: true, with: currentOrientation(), forceRotate: false)
}
let time = videoPlayer.currentTime
videoPlayer.resetPlayer()
guard let video = video else {
loadVideoIfNecessary()
return
}
cast(video: video, time: time)
}
func chromeCastDidDisconnect(playedTime: TimeInterval) {
removeOverlayMessage()
removeOverlayPlayButton()
guard let video = video else {
loadVideoIfNecessary()
return
}
playLocally(video: video, time: playedTime)
}
func chromeCastVideoPlaying() {
}
func chromeCastDidFinishPlaying() {
createOverlayPlayButton()
videoPlayer.savePlayedTime(time: .zero)
}
}
extension VideoBlockViewController: CelebratoryModalViewControllerDelegate {
func modalDidDismiss() {
shouldCelebrationAppear = false
if let video = self.video {
DispatchQueue.main.async { [weak self] in
if let weakSelf = self {
weakSelf.play(video: video)
if weakSelf.isVerticallyCompact() {
weakSelf.videoPlayer.setFullscreen(fullscreen: true, animated: true, with: .portrait, forceRotate: false)
}
}
}
}
}
}