Skip to content
This repository has been archived by the owner on Dec 18, 2024. It is now read-only.

Commit

Permalink
no
Browse files Browse the repository at this point in the history
  • Loading branch information
cranci1 committed Sep 12, 2024
1 parent 963331c commit debd54c
Show file tree
Hide file tree
Showing 7 changed files with 47 additions and 107 deletions.
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,6 @@ FrameWorks:
- [SwiftSoup](https://github.com/scinfu/SwiftSoup) - MIT License
- [KingFisher](https://github.com/onevcat/Kingfisher) - MIT License
- [Alamofire](https://github.com/Alamofire/Alamofire) - MIT License
- [GCDWebServer](https://github.com/readium/GCDWebServer) - [Custom License](https://github.com/readium/GCDWebServer/blob/master/LICENSE)
- [GoogleCastSDK-ios-no-bluetooth](https://github.com/SRGSSR/GoogleCastSDK-ios-no-bluetooth) - Google Developer Terms

APIs:
Expand Down
17 changes: 0 additions & 17 deletions Ryu.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@
13A888B22C7A305500D6C597 /* CustomPlayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13A888B12C7A305500D6C597 /* CustomPlayer.swift */; };
13A888B42C7A322600D6C597 /* CustomPlayerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13A888B32C7A322600D6C597 /* CustomPlayerView.swift */; };
13E7F8182C9031A7007550B9 /* SettingsViewTranslation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13E7F8172C9031A7007550B9 /* SettingsViewTranslation.swift */; };
13F3EA0A2C92EF1E0098B1C8 /* GCDWebServer in Frameworks */ = {isa = PBXBuildFile; productRef = 13F3EA092C92EF1E0098B1C8 /* GCDWebServer */; };
13F3EA0D2C92F1300098B1C8 /* LocalServerViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13F3EA0C2C92F1300098B1C8 /* LocalServerViewModel.swift */; };
/* End PBXBuildFile section */

Expand Down Expand Up @@ -184,7 +183,6 @@
files = (
131546D82C6DE6D9002DC3CC /* Kingfisher in Frameworks */,
131546E12C6DE71D002DC3CC /* SwiftSoup in Frameworks */,
13F3EA0A2C92EF1E0098B1C8 /* GCDWebServer in Frameworks */,
131546DE2C6DE6F2002DC3CC /* Alamofire in Frameworks */,
131546D52C6DE6CC002DC3CC /* GoogleCastSDK-ios-no-bluetooth in Frameworks */,
);
Expand Down Expand Up @@ -606,7 +604,6 @@
131546D72C6DE6D9002DC3CC /* Kingfisher */,
131546DD2C6DE6F2002DC3CC /* Alamofire */,
131546E02C6DE71D002DC3CC /* SwiftSoup */,
13F3EA092C92EF1E0098B1C8 /* GCDWebServer */,
);
productName = Ryu;
productReference = 1365249C2C6B5B2F00210A98 /* Ryu.app */;
Expand Down Expand Up @@ -641,7 +638,6 @@
131546D62C6DE6D9002DC3CC /* XCRemoteSwiftPackageReference "Kingfisher" */,
131546DC2C6DE6F2002DC3CC /* XCRemoteSwiftPackageReference "Alamofire" */,
131546DF2C6DE71D002DC3CC /* XCRemoteSwiftPackageReference "SwiftSoup" */,
13F3EA082C92EF1E0098B1C8 /* XCRemoteSwiftPackageReference "GCDWebServer" */,
);
productRefGroup = 1365249D2C6B5B2F00210A98 /* Products */;
projectDirPath = "";
Expand Down Expand Up @@ -1021,14 +1017,6 @@
version = 2.4.0;
};
};
13F3EA082C92EF1E0098B1C8 /* XCRemoteSwiftPackageReference "GCDWebServer" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/readium/GCDWebServer";
requirement = {
kind = exactVersion;
version = 3.7.5;
};
};
/* End XCRemoteSwiftPackageReference section */

/* Begin XCSwiftPackageProductDependency section */
Expand All @@ -1052,11 +1040,6 @@
package = 131546DF2C6DE71D002DC3CC /* XCRemoteSwiftPackageReference "SwiftSoup" */;
productName = SwiftSoup;
};
13F3EA092C92EF1E0098B1C8 /* GCDWebServer */ = {
isa = XCSwiftPackageProductDependency;
package = 13F3EA082C92EF1E0098B1C8 /* XCRemoteSwiftPackageReference "GCDWebServer" */;
productName = GCDWebServer;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = 136524942C6B5B2F00210A98 /* Project object */;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,6 @@
"version": "5.8.0"
}
},
{
"package": "GCDWebServer",
"repositoryURL": "https://github.com/readium/GCDWebServer",
"state": {
"branch": null,
"revision": "50caf05df2c70edadce143747c96fcd877fe05bb",
"version": "3.7.5"
}
},
{
"package": "GoogleCastSDK-ios-no-bluetooth",
"repositoryURL": "https://github.com/SRGSSR/GoogleCastSDK-ios-no-bluetooth.git",
Expand Down
Binary file not shown.
23 changes: 11 additions & 12 deletions Ryu/Swift - Views/Settings/SubPages/SettingsViewTranslation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -94,48 +94,47 @@ class SettingsViewTranslation: UITableViewController {
UserDefaults.standard.set(sender.isOn, forKey: "selfHostEnabled")

if sender.isOn {
startSelfHostingServer() // Start server process when switch is on
startSelfHostingServer()
}
}

private func startSelfHostingServer() {
// Show alert and start the server
showProgressAlert()
viewModel.selectedRepository = viewModel.repositories.first // Select a repository to start
viewModel.startProcess() // Trigger the process
viewModel.selectedRepository = viewModel.repository
viewModel.startProcess()
}

private func showProgressAlert() {
progressAlert = UIAlertController(title: "Starting Self-Host", message: "Initializing...", preferredStyle: .alert)
if let alert = progressAlert {
present(alert, animated: true)
}
}

private func updateProgressAlert(message: String) {
progressAlert?.message = message
}

private func setupViewModel() {
// Observer to update the alert when server progress updates
viewModel.onUpdate = { [weak self] statusMessage in
DispatchQueue.main.async {
self?.updateProgressAlert(message: statusMessage)
}
}

// Observer to close the alert once the process is finished
viewModel.onProcessFinished = { [weak self] in
DispatchQueue.main.async {
self?.dismissProgressAlert()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self?.dismissProgressAlert()
}
}
}
}

private func dismissProgressAlert() {
if let alert = progressAlert {
alert.dismiss(animated: true, completion: nil)
progressAlert = nil // Reset the alert after dismissing
progressAlert = nil
}
}
}
63 changes: 3 additions & 60 deletions Ryu/Utils/LocalHost/LocalServerViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
// Created by Francesco on 12/09/24.
//

import UIKit
import GCDWebServer
import Foundation

struct Repository: Identifiable, Hashable {
let id = UUID()
Expand Down Expand Up @@ -43,15 +42,11 @@ struct TranslationResponse: Codable {
}

class LocalServerViewModel {
var repositories: [Repository] = [
Repository(name: "DeepLX vercel", url: "https://github.com/bropines/Deeplx-vercel.git", port: 9000)
]
let repository = Repository(name: "DeepLX vercel", url: "https://github.com/bropines/Deeplx-vercel.git", port: 9000)
var selectedRepository: Repository?
var isProcessing = false
var serverResponse: String = ""

private var webServer: GCDWebServer?

var onUpdate: ((String) -> Void)?
var onProcessFinished: (() -> Void)?

Expand All @@ -62,59 +57,7 @@ class LocalServerViewModel {
onUpdate?(serverResponse)

DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
self?.cloneRepository(repository)
}
}

private func cloneRepository(_ repository: Repository) {
serverResponse += "\nCloning repository: \(repository.name)..."
onUpdate?(serverResponse)
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
self?.startServer(repository)
}
}

private func startServer(_ repository: Repository) {
serverResponse += "\nStarting local server on port \(repository.port)..."
onUpdate?(serverResponse)

webServer = GCDWebServer()

webServer?.addHandler(forMethod: "POST", path: "/api/translate", request: GCDWebServerDataRequest.self) { [weak self] (request, completion) in
guard let dataRequest = request as? GCDWebServerDataRequest else {
completion(GCDWebServerDataResponse(statusCode: 400))
return
}

do {
let translationRequest = try JSONDecoder().decode(TranslationRequest.self, from: dataRequest.data)
let translatedText = "Ciao amico mio"
let response = TranslationResponse(code: 200, data: translatedText, sourceLang: "auto", targetLang: "it")
let jsonData = try JSONEncoder().encode(response)

let dataResponse = GCDWebServerDataResponse(data: jsonData, contentType: "application/json")
completion(dataResponse)

DispatchQueue.main.async {
self?.serverResponse += "\nReceived translation request: \(translationRequest.text)"
self?.serverResponse += "\nResponded with: \(translatedText)"
self?.onUpdate?(self?.serverResponse ?? "")
}
} catch {
completion(GCDWebServerDataResponse(statusCode: 400))
}
}

do {
try webServer?.start(options: [GCDWebServerOption_Port: repository.port])
serverResponse += "\nServer started successfully"
onUpdate?(serverResponse)
makeTranslationRequest(repository)
} catch {
serverResponse += "\nFailed to start server: \(error.localizedDescription)"
isProcessing = false
onUpdate?(serverResponse)
onProcessFinished?()
self?.makeTranslationRequest(repository)
}
}

Expand Down
41 changes: 33 additions & 8 deletions Ryu/Utils/Player/Custom Player/Subtitles/SubtitlesLoader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -111,14 +111,16 @@ class SubtitlesLoader {

private static func translateText(_ text: String, targetLang: String, completion: @escaping (String) -> Void) {
guard UserDefaults.standard.bool(forKey: "googleTranslation") else {
print("Translation is disabled.")
completion(text)
return
}

let urlString = Bool.random() ? "https://translate-api-first.vercel.app/api/translate" : "https://translate-api-second.vercel.app/api/translate"
let urlString = "http://localhost:9000/api/translate" // Local server URL
print("Preparing to send translation request to \(urlString)")

guard let url = URL(string: urlString) else {
print("Invalid URL")
print("Invalid URL: \(urlString)")
completion(text)
return
}
Expand All @@ -133,26 +135,49 @@ class SubtitlesLoader {
"target_lang": targetLang
]

request.httpBody = try? JSONSerialization.data(withJSONObject: payload)
do {
request.httpBody = try JSONSerialization.data(withJSONObject: payload)
print("Request payload: \(String(data: request.httpBody!, encoding: .utf8) ?? "nil")")
} catch {
print("Error serializing JSON payload: \(error.localizedDescription)")
completion(text)
return
}

let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
print("Error: \(error!.localizedDescription)")
if let error = error {
print("Network error: \(error.localizedDescription)")
completion(text)
return
}

guard let httpResponse = response as? HTTPURLResponse else {
print("Invalid response.")
completion(text)
return
}

print("HTTP status code: \(httpResponse.statusCode)")

guard let data = data else {
print("No data received.")
completion(text)
return
}

print("Response data: \(String(data: data, encoding: .utf8) ?? "nil")")

do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
let translatedText = json["data"] as? String {
completion(translatedText)
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
print("Response JSON: \(json)")
if let translatedText = json["data"] as? String {
completion(translatedText)
} else {
print("Invalid JSON format: missing 'data' field")
completion(text)
}
} else {
print("Invalid JSON format.")
completion(text)
}
} catch {
Expand Down

0 comments on commit debd54c

Please sign in to comment.