Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat Add download support for Non-DRM videos #50

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Example/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ struct ContentView: View {
TPStreamPlayerView(player: player)
.frame(height: 240)
Spacer()
Button(action: {
TPStreamsDownloadManager.shared.startDownloadWithPlayer(player: player)
print("Button tapped!")
}) {
Text("Download")
.padding()
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(10)
}
}
}
}
Expand Down
47 changes: 47 additions & 0 deletions Source/Offline/Model/OfflineAsset.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//
// OfflineAsset.swift
// TPStreamsSDK
//
// Created by Prithuvi on 03/01/24.
//

import Foundation

public struct OfflineAsset {
var id: String
var created_at = Date()
var title: String = ""
var srcURL: String = ""
var downloadedPath: String = ""
var downloadedAt = Date()
var status:String = Status.notStarted.rawValue
var percentageCompleted: Double = 0.0
}

enum Status: String {
case notStarted = "notStarted"
case inProgress = "inProgress"
case paused = "paused"
case finished = "finished"
case failed = "failed"
}

extension OfflineAsset {

mutating func updateDownloadPath(downloadedPath: String) {
self.downloadedPath = downloadedPath
}

mutating func updateStatus(status: String) {
self.status = status
}

mutating func updatePercentageCompleted(percentageCompleted: Double) {
self.percentageCompleted = percentageCompleted
}

mutating func updateDownloadAt(downloadedAt: Date) {
self.downloadedAt = downloadedAt
}

}
146 changes: 146 additions & 0 deletions Source/Offline/TPStreamsDatabase.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
//
// TPStreamsDatabase.swift
// TPStreamsSDK
//
// Created by Prithuvi on 04/01/24.
//
// This class implements a local database using SQLite.swift library (https://github.com/stephencelis/SQLite.swift).
// All operations in this class are based on the documentation of the SQLite.swift library.
// Documentation (https://github.com/stephencelis/SQLite.swift/blob/master/Documentation/Index.md)

import Foundation
import SQLite

internal class TPStreamsDatabase {

private var offlineAssetDatabasePath: String?
private var offlineAssetDatabase: Connection?
private var offlineAssetTable: Table?
// Columns in Table
private let id = Expression<String>("id")
private let created_at = Expression<Date>("created_at")
private let title = Expression<String>("title")
private let srcURL = Expression<String>("srcURL")
private let downloadedPath = Expression<String>("downloadedPath")
private let downloadedAt = Expression<Date>("downloadedAt")
private let status = Expression<String>("status")
private let percentageCompleted = Expression<Double>("percentageCompleted")

func initialize() {
do {
offlineAssetDatabasePath = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first!

// Create Database
offlineAssetDatabase = try Connection("\(offlineAssetDatabasePath!)/db.sqlite3")

// Initialize Table
offlineAssetTable = Table("OfflineAsset")

// Create Table
try offlineAssetDatabase!.run(offlineAssetTable!.create { offlineAsset in
offlineAsset.column(id, primaryKey: true)
offlineAsset.column(created_at)
offlineAsset.column(title)
offlineAsset.column(srcURL, unique: true)
offlineAsset.column(downloadedPath, unique: true)
offlineAsset.column(downloadedAt)
offlineAsset.column(status)
offlineAsset.column(percentageCompleted)
})
} catch {
print (error)
}
}

func insert( _ offlineAssets: OfflineAsset) {
do {
try offlineAssetDatabase!.run(
offlineAssetTable!.insert(
id <- offlineAssets.id,
created_at <- offlineAssets.created_at,
title <- offlineAssets.title,
srcURL <- offlineAssets.srcURL,
downloadedPath <- offlineAssets.downloadedPath,
downloadedAt <- offlineAssets.downloadedAt,
status <- offlineAssets.status,
percentageCompleted <- offlineAssets.percentageCompleted
)
)
} catch {
print("insertion failed: \(error)")
}
}

func update( _ offlineAssets: OfflineAsset) {
let tempOfflineAsset = offlineAssetTable!.filter(id == offlineAssets.id)
do {
try offlineAssetDatabase!.run(
tempOfflineAsset.update(
downloadedPath <- offlineAssets.downloadedPath,
downloadedAt <- offlineAssets.downloadedAt,
status <- offlineAssets.status,
percentageCompleted <- offlineAssets.percentageCompleted
)
)
} catch {
print("updation failed: \(error)")
}
}

func get(id: String) -> OfflineAsset? {
do {
let query = offlineAssetTable!.filter(self.id == id)
if let offlineAsset = try offlineAssetDatabase!.pluck(query) {
let result = OfflineAsset(
id: offlineAsset[self.id],
created_at: offlineAsset[self.created_at],
title: offlineAsset[self.title],
srcURL: offlineAsset[self.srcURL],
downloadedPath: offlineAsset[self.downloadedPath],
downloadedAt: offlineAsset[self.downloadedAt],
status: offlineAsset[self.status],
percentageCompleted: offlineAsset[self.percentageCompleted]
)
return result
}
} catch {
print("Error fetching offline asset with id \(id): \(error)")
}
return nil
}

func get(srcURL: String) -> OfflineAsset? {
do {
let query = offlineAssetTable!.filter(self.srcURL == srcURL)
if let offlineAsset = try offlineAssetDatabase!.pluck(query) {
let result = OfflineAsset(
id: offlineAsset[self.id],
created_at: offlineAsset[self.created_at],
title: offlineAsset[self.title],
srcURL: offlineAsset[self.srcURL],
downloadedPath: offlineAsset[self.downloadedPath],
downloadedAt: offlineAsset[self.downloadedAt],
status: offlineAsset[self.status],
percentageCompleted: offlineAsset[self.percentageCompleted]
)
return result
}
} catch {
print("Error fetching offline asset with srcURL \(id): \(error)")
}
return nil
}

func delete(id: String) {
do {
let tempOfflineAsset = offlineAssetTable!.filter(self.id == id)
try offlineAssetDatabase!.run(tempOfflineAsset.delete())
} catch {
print("deletion failed: \(error)")
}
}


}
92 changes: 92 additions & 0 deletions Source/Offline/TPStreamsDownloadManager.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
//
// TPStreamsDownloadManager.swift
// TPStreamsSDK
//
// Created by Prithuvi on 03/01/24.
//

import Foundation
import AVFoundation


public final class TPStreamsDownloadManager: NSObject {

static public let shared = TPStreamsDownloadManager()
private var assetDownloadURLSession: AVAssetDownloadURLSession!
private var activeDownloadsMap = [AVAssetDownloadTask: OfflineAsset]()
private var tpStreamsDatabase: TPStreamsDatabase?
private var player: TPAVPlayer?

private override init() {
super.init()
tpStreamsDatabase = TPStreamsDatabase()
tpStreamsDatabase?.initialize()
let backgroundConfiguration = URLSessionConfiguration.background(withIdentifier: "com.tpstreams.downloadSession")
assetDownloadURLSession = AVAssetDownloadURLSession(
configuration: backgroundConfiguration,
assetDownloadDelegate: self,
delegateQueue: OperationQueue.main
)
}

public func startDownloadWithPlayer(player: TPAVPlayer) {
startDownload(asset: player.asset!, bitRate: 100_000)
}

internal func startDownload(asset: Asset, bitRate: Int) {
let avUrlAsset = AVURLAsset(url: URL(string: asset.video.playbackURL)!)

guard let task = assetDownloadURLSession.makeAssetDownloadTask(
asset: avUrlAsset,
assetTitle: asset.title,
assetArtworkData: nil,
options: [AVAssetDownloadTaskMinimumRequiredMediaBitrateKey: bitRate]
) else {
return
}

let offlineAsset = OfflineAsset(id: asset.id, title: asset.title, srcURL: asset.video.playbackURL)
tpStreamsDatabase?.insert(offlineAsset)
activeDownloadsMap[task] = offlineAsset
task.resume()
}

}

extension TPStreamsDownloadManager: AVAssetDownloadDelegate {

public func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didFinishDownloadingTo location: URL) {
guard var offlineAsset = activeDownloadsMap[assetDownloadTask] else { return }
offlineAsset.updateDownloadPath(downloadedPath: location.relativePath)
activeDownloadsMap[assetDownloadTask] = offlineAsset
tpStreamsDatabase?.update(offlineAsset)
}

public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let assetDownloadTask = task as? AVAssetDownloadTask,
var offlineAsset = activeDownloadsMap[assetDownloadTask] else { return }

if let error = error {
offlineAsset.updateStatus(status: Status.failed.rawValue)
} else {
offlineAsset.updateStatus(status: Status.finished.rawValue)
}

offlineAsset.updateDownloadAt(downloadedAt: Date())
tpStreamsDatabase?.update(offlineAsset)
activeDownloadsMap.removeValue(forKey: assetDownloadTask)
}

public func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didLoad timeRange: CMTimeRange, totalTimeRangesLoaded loadedTimeRanges: [NSValue], timeRangeExpectedToLoad: CMTimeRange) {
guard var offlineAsset = activeDownloadsMap[assetDownloadTask] else { return }
var percentageComplete = 0.0
for value in loadedTimeRanges {
let loadedTimeRange = value.timeRangeValue
percentageComplete += loadedTimeRange.duration.seconds / timeRangeExpectedToLoad.duration.seconds
}
offlineAsset.updatePercentageCompleted(percentageCompleted: percentageComplete * 100)
offlineAsset.updateStatus(status: Status.inProgress.rawValue)
activeDownloadsMap[assetDownloadTask] = offlineAsset
tpStreamsDatabase?.update(offlineAsset)
}
}
2 changes: 2 additions & 0 deletions Source/TPAVPlayer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public class TPAVPlayer: AVPlayer {
private var resourceLoaderDelegate: ResourceLoaderDelegate
public var onError: ((Error) -> Void)?
internal var initializationError: Error?
internal var asset: Asset? = nil

public var availableVideoQualities: [VideoQuality] = [VideoQuality(resolution:"Auto", bitrate: 0)]

Expand All @@ -49,6 +50,7 @@ public class TPAVPlayer: AVPlayer {

if let asset = asset {
self.setup(withAsset: asset)
self.asset = asset
self.setupCompletion?(nil)
} else if let error = error{
SentrySDK.capture(error: error)
Expand Down
Loading