Skip to content

Commit

Permalink
some improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
cranci1 committed Jun 6, 2024
1 parent a18b834 commit c1d9b94
Show file tree
Hide file tree
Showing 7 changed files with 286 additions and 173 deletions.
38 changes: 37 additions & 1 deletion Osmium.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
13177F4F2C0645FF00E4CECA /* Video.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13177F4C2C0645FF00E4CECA /* Video.swift */; };
13177F512C06460500E4CECA /* AboutPage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13177F502C06460500E4CECA /* AboutPage.swift */; };
13177F542C07547900E4CECA /* VideoPlayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13177F532C07547900E4CECA /* VideoPlayer.swift */; };
135C0FAB2C10E0E300177744 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 135C0FAA2C10E0E300177744 /* Request.swift */; };
135C0FAE2C10E17B00177744 /* GallerySaver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 135C0FAD2C10E17B00177744 /* GallerySaver.swift */; };
135C0FB02C10E18300177744 /* URLSaver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 135C0FAF2C10E18300177744 /* URLSaver.swift */; };
1369A3C32C08ACE700C7E7B7 /* Save-Debug.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1369A3C22C08ACE700C7E7B7 /* Save-Debug.swift */; };
1369A3C52C08AD7800C7E7B7 /* PlayerExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1369A3C42C08AD7800C7E7B7 /* PlayerExtension.swift */; };
/* End PBXBuildFile section */
Expand All @@ -36,6 +39,9 @@
13177F4C2C0645FF00E4CECA /* Video.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Video.swift; sourceTree = "<group>"; };
13177F502C06460500E4CECA /* AboutPage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AboutPage.swift; sourceTree = "<group>"; };
13177F532C07547900E4CECA /* VideoPlayer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VideoPlayer.swift; sourceTree = "<group>"; };
135C0FAA2C10E0E300177744 /* Request.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Request.swift; sourceTree = "<group>"; };
135C0FAD2C10E17B00177744 /* GallerySaver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GallerySaver.swift; sourceTree = "<group>"; };
135C0FAF2C10E18300177744 /* URLSaver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = URLSaver.swift; sourceTree = "<group>"; };
1369A3C22C08ACE700C7E7B7 /* Save-Debug.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Save-Debug.swift"; sourceTree = "<group>"; };
1369A3C42C08AD7800C7E7B7 /* PlayerExtension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerExtension.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
Expand Down Expand Up @@ -74,9 +80,10 @@
1369A3C02C08ACCA00C7E7B7 /* Extensions */,
13177F522C07546D00E4CECA /* Player */,
13177F482C0645ED00E4CECA /* Settings */,
135C0FA92C10E0D300177744 /* Functions */,
13177F322C0645A900E4CECA /* AppDelegate.swift */,
13177F342C0645A900E4CECA /* SceneDelegate.swift */,
13177F362C0645A900E4CECA /* ViewController.swift */,
13177F342C0645A900E4CECA /* SceneDelegate.swift */,
13177F462C0645D600E4CECA /* Main.storyboard */,
13177F3B2C0645AA00E4CECA /* Assets.xcassets */,
13177F3D2C0645AA00E4CECA /* LaunchScreen.storyboard */,
Expand Down Expand Up @@ -112,6 +119,32 @@
path = Player;
sourceTree = "<group>";
};
135C0FA92C10E0D300177744 /* Functions */ = {
isa = PBXGroup;
children = (
135C0FB12C10E22700177744 /* Request */,
135C0FAC2C10E16B00177744 /* Saving Methods */,
);
path = Functions;
sourceTree = "<group>";
};
135C0FAC2C10E16B00177744 /* Saving Methods */ = {
isa = PBXGroup;
children = (
135C0FAD2C10E17B00177744 /* GallerySaver.swift */,
135C0FAF2C10E18300177744 /* URLSaver.swift */,
);
path = "Saving Methods";
sourceTree = "<group>";
};
135C0FB12C10E22700177744 /* Request */ = {
isa = PBXGroup;
children = (
135C0FAA2C10E0E300177744 /* Request.swift */,
);
path = Request;
sourceTree = "<group>";
};
1369A3C02C08ACCA00C7E7B7 /* Extensions */ = {
isa = PBXGroup;
children = (
Expand Down Expand Up @@ -202,12 +235,15 @@
13177F4D2C0645FF00E4CECA /* Audio.swift in Sources */,
13177F542C07547900E4CECA /* VideoPlayer.swift in Sources */,
1369A3C52C08AD7800C7E7B7 /* PlayerExtension.swift in Sources */,
135C0FB02C10E18300177744 /* URLSaver.swift in Sources */,
13177F4F2C0645FF00E4CECA /* Video.swift in Sources */,
13177F372C0645A900E4CECA /* ViewController.swift in Sources */,
135C0FAE2C10E17B00177744 /* GallerySaver.swift in Sources */,
1369A3C32C08ACE700C7E7B7 /* Save-Debug.swift in Sources */,
13177F332C0645A900E4CECA /* AppDelegate.swift in Sources */,
13177F512C06460500E4CECA /* AboutPage.swift in Sources */,
13177F4E2C0645FF00E4CECA /* Other.swift in Sources */,
135C0FAB2C10E0E300177744 /* Request.swift in Sources */,
13177F352C0645A900E4CECA /* SceneDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
Expand Down
123 changes: 123 additions & 0 deletions Osmium/Functions/Request/Request.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
//
// Request.swift
// Osmium
//
// Created by Francesco on 05/06/24.
//

import UIKit

extension ViewController {

func getUserDefaultsValue<T>(key: String, defaultValue: T) -> T {
return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
}

func sendPostRequest() {
guard let urlText = urlTextField.text, !urlText.isEmpty else {
writeToConsole("URL text field is empty")
showAlert(title: "Error", message: "Please enter a valid URL")
return
}

self.writeToConsole("Starting process...")

UserDefaults.standard.set(urlText, forKey: "url")

guard let url = URL(string: "https://api.cobalt.tools/api/json") else {
writeToConsole("Invalid API URL")
showAlert(title: "Error", message: "Invalid API URL")
return
}

let requestBody: [String: Any] = [
"url": getUserDefaultsValue(key: "url", defaultValue: "https://example.com/video"),
"vCodec": getUserDefaultsValue(key: "vCodec", defaultValue: "h264"),
"vQuality": getUserDefaultsValue(key: "vQuality", defaultValue: "720"),
"aFormat": getUserDefaultsValue(key: "aFormat", defaultValue: "mp3"),
"filenamePattern": getUserDefaultsValue(key: "filenamePattern", defaultValue: "classic"),
"isAudioOnly": getUserDefaultsValue(key: "isAudioOnly", defaultValue: false),
"isTTFullAudio": getUserDefaultsValue(key: "isTTFullAudio", defaultValue: false),
"isAudioMuted": getUserDefaultsValue(key: "isAudioMuted", defaultValue: false),
"dubLang": getUserDefaultsValue(key: "dubLang", defaultValue: false),
"disableMetadata": getUserDefaultsValue(key: "disableMetadata", defaultValue: false),
"twitterGif": getUserDefaultsValue(key: "twitterGif", defaultValue: false),
"tiktokH265": getUserDefaultsValue(key: "tiktokH265", defaultValue: false)
]

if debug {
writeToConsole("Request Body:")
requestBody.forEach { key, value in
writeToConsole("\(key): \(value)")
}
}

guard let jsonData = try? JSONSerialization.data(withJSONObject: requestBody) else {
writeToConsole("Failed to serialize JSON data")
showAlert(title: "Error", message: "Failed to process request")
return
}

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData

let task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
guard let self = self else { return }

if let error = error {
self.writeToConsole("Error: \(error)")
self.showAlert(title: "Error", message: "Failed to process request")
return
}

guard let data = data else {
self.writeToConsole("No data")
self.showAlert(title: "Error", message: "No data received")
return
}

if self.debug {
if let responseString = String(data: data, encoding: .utf8) {
self.writeToConsole("Response: \(responseString)")
} else {
self.writeToConsole("Unable to convert response data to string")
}
}

do {
guard let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
throw NSError(domain: "ParsingError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to parse JSON"])
}

guard let status = jsonObject["status"] as? String, let mediaURLString = jsonObject["url"] as? String else {
throw NSError(domain: "ParsingError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to extract required data from JSON"])
}

switch status {
case "redirect":
if self.saveMedia {
self.saveMediaToGallery(urlString: mediaURLString)
} else {
self.openURLInSafari(urlString: mediaURLString)
}
self.writeToConsole("Saving media...")

case "stream":
self.openURLInSafari(urlString: mediaURLString)
self.writeToConsole("Opening link...")

default:
self.writeToConsole("Unexpected status in response")
self.showAlert(title: "Error", message: "Unexpected status in response")
}
} catch {
self.writeToConsole("Error: \(error.localizedDescription)")
self.showAlert(title: "Error", message: "Failed to parse response")
}
}
task.resume()
}
}
80 changes: 80 additions & 0 deletions Osmium/Functions/Saving Methods/GallerySaver.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
//
// GallerySaver.swift
// Osmium
//
// Created by Francesco on 05/06/24.
//

import UIKit

extension ViewController {

func saveMediaToGallery(urlString: String) {
guard let url = URL(string: urlString) else {
writeToConsole("Invalid URL")
return
}

let session = URLSession.shared
let task = session.dataTask(with: url) { [weak self] (data, response, error) in
guard let self = self else { return }

if let error = error {
self.handleMediaSavingError(error)
return
}

guard let data = data else {
self.handleMediaSavingError("No data received")
return
}

guard let contentType = response?.mimeType else {
self.handleMediaSavingError("Unknown content type")
return
}

switch contentType {
case _ where contentType.hasPrefix("image"):
self.saveImageToGallery(data)
case _ where contentType.hasPrefix("video"):
self.saveVideoToGallery(data)
default:
self.handleMediaSavingError("Unsupported content type: \(contentType)")
}
}
task.resume()
}

private func saveImageToGallery(_ imageData: Data) {
guard let image = UIImage(data: imageData) else {
handleMediaSavingError("Unable to create image from data")
return
}

UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
writeToConsole("Image saved to gallery successfully")
showAlert(title: "Success", message: "Media saved to gallery successfully")
}

private func saveVideoToGallery(_ videoData: Data) {
let tempURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("video.mp4")
do {
try videoData.write(to: tempURL)
UISaveVideoAtPathToSavedPhotosAlbum(tempURL.path, nil, nil, nil)
writeToConsole("Video saved to gallery successfully")
showAlert(title: "Success", message: "Media saved to gallery successfully")
} catch {
handleMediaSavingError("Error saving video to gallery: \(error)")
}
}

private func handleMediaSavingError(_ errorMessage: String) {
writeToConsole("Error: \(errorMessage)")
showAlert(title: "Error", message: errorMessage)
}

private func handleMediaSavingError(_ error: Error) {
handleMediaSavingError(error.localizedDescription)
}
}
22 changes: 22 additions & 0 deletions Osmium/Functions/Saving Methods/URLSaver.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//
// URLSaver.swift
// Osmium
//
// Created by Francesco on 05/06/24.
//

import UIKit

extension ViewController {

func openURLInSafari(urlString: String) {
guard let url = URL(string: urlString) else {
writeToConsole("Invalid URL")
return
}
DispatchQueue.main.async {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
self.writeToConsole("Done!")
}
}
}
1 change: 1 addition & 0 deletions Osmium/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
</dict>
<key>UIBackgroundModes</key>
<array>
<string>processing</string>
<string>audio</string>
<string>remote-notification</string>
</array>
Expand Down
Loading

0 comments on commit c1d9b94

Please sign in to comment.