Skip to content

Commit

Permalink
Merge develop into master.v0.3.4-build(b7bc145)
Browse files Browse the repository at this point in the history
  • Loading branch information
xjbeta committed Sep 13, 2018
2 parents 914fad7 + b7bc145 commit 68e0593
Show file tree
Hide file tree
Showing 7 changed files with 147 additions and 18 deletions.
3 changes: 2 additions & 1 deletion Cartfile.resolved
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
github "1024jp/GzipSwift" "4.0.4"
github "DevMate/DevMateKit" "v1.9"
github "IBM-Swift/BlueSocket" "1.0.15"
github "IBM-Swift/BlueSocket" "1.0.16"
github "daltoniam/SwiftHTTP" "3.0.1"
github "facebook/SocketRocket" "0a023409b138039d1ab5ac5431fe61c5f334e86b"
github "utahiosmac/Marshal" "1.2.7"
2 changes: 1 addition & 1 deletion iina+/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
Logger.log("macOS " + ProcessInfo().operatingSystemVersionString)

HTTP.globalRequest { req in
req.timeoutInterval = 1.5
req.timeoutInterval = 3
req.allHTTPHeaderFields = ["User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1.2 Safari/605.1.15"]
}

Expand Down
1 change: 1 addition & 0 deletions iina+/DanmakuWeb/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,5 +101,6 @@ function bind() {

window.addEventListener("load", function() {
bind();
initDM();
});

2 changes: 1 addition & 1 deletion iina+/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>0.3.3</string>
<string>0.3.4</string>
<key>CFBundleVersion</key>
<string>0</string>
<key>LSApplicationCategoryType</key>
Expand Down
45 changes: 39 additions & 6 deletions iina+/Utils/Processes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -199,13 +199,28 @@ class Processes: NSObject {
}

var shouldKeepRunning = true
// var savedData = Data()
repeat {
var d = Data()
let _ = try socket.read(into: &d)
if d.count > 0 {
let json = try JSONParser.JSONObjectWithData(d)
let socketEvent = try MpvSocketEvent(object: json)
notice(socketEvent)
do {
try String(data: d, encoding: .utf8)?.components(separatedBy: "\n").filter {
$0 != ""
}.compactMap {
$0.data(using: .utf8)
}.forEach {
let json = try JSONParser.JSONObjectWithData($0)
let socketEvent = try MpvSocketEvent(object: json)
if socketEvent.event == nil, socketEvent.success == nil {
Logger.log("not find the mpv event: \(String(data: $0, encoding: .utf8) ?? "")")
}
notice(socketEvent)
}
} catch let error {
Logger.log(String(data: d, encoding: .utf8) ?? "")
Logger.log("mpv socket json decode error: \(error)")
}
} else {
shouldKeepRunning = false
}
Expand Down Expand Up @@ -264,10 +279,28 @@ private extension Processes {

struct MpvSocketEvent: Unmarshaling {
enum MpvEvent: String {
case propertyChange = "property-change"
case unpause
case pause
case startFile = "start-file"
case endFile = "end-file"
case fileLoaded = "file-loaded"
case seek
case playbackRestart = "playback-restart"
case idle
case tick
case shutdown
case logMessage = "log-message"
case getPropertyReply = "get-property-reply"
case setPropertyReply = "set-property-reply"
case commandReply = "command-reply"
case clientMessage = "client-message"
case videoReconfig = "video-reconfig"
case audioReconfig = "audio-reconfig"
case tracksChanged = "tracks-changed"
case trackSwitched = "track-switched"
case pause
case unpause
case metadataUpdate = "metadata-update"
case chapterChange = "chapter-change"
case propertyChange = "property-change"
}

var event: MpvEvent?
Expand Down
110 changes: 102 additions & 8 deletions iina+/Views/Danmaku/DanmakuViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import SwiftHTTP
import Marshal
import SocketRocket
import Gzip
import Socket

class DanmakuViewController: NSViewController {

Expand All @@ -25,6 +26,8 @@ class DanmakuViewController: NSViewController {
let biliLiveServer = URL(string: "wss://broadcastlv.chat.bilibili.com/sub")
var biliLiveRoomID = 0
var pandaInitStr = ""

var douyuSocket: Socket? = nil

override func viewDidLoad() {
super.viewDidLoad()
Expand All @@ -39,14 +42,14 @@ class DanmakuViewController: NSViewController {
}

func initDanmaku(_ site: LiveSupportList, _ url: String) {
webView.reload()
if let danmakuFilePath = danmakuFilePath {
try? FileManager.default.removeItem(atPath: danmakuFilePath)
}

socket?.close()
socket = nil

self.initDM()


liveSite = site
Expand Down Expand Up @@ -117,6 +120,9 @@ class DanmakuViewController: NSViewController {
Logger.log("can't find panda live room id \(error)")
}
}
case .douyu:
let roomID = URL(string: url)?.lastPathComponent ?? ""
initDouYuSocket(roomID)
default:
break
}
Expand Down Expand Up @@ -169,13 +175,21 @@ class DanmakuViewController: NSViewController {
if let timer = timer {
timer.schedule(deadline: .now(), repeating: .seconds(30))
timer.setEventHandler {
switch self.liveSite {
case .biliLive:
try? self.socket?.send(data: self.pack(format: "NnnNN", values: [16, 16, 1, 2, 1]) as Data)
case .panda:
try? self.socket?.send(data: self.pack(format: "nn", values: [6, 0]) as Data)
default:
break
do {
switch self.liveSite {
case .biliLive:
try self.socket?.send(data: self.pack(format: "NnnNN", values: [16, 16, 1, 2, 1]) as Data)
case .panda:
try self.socket?.send(data: self.pack(format: "nn", values: [6, 0]) as Data)
case .douyu:
// let keeplive = "type@=keeplive/tick@=\(Int(Date().timeIntervalSince1970))/"
let keeplive = "type@=mrkl/"
try self.douyuSocket?.write(from: self.douyuSocketFormatter(keeplive))
default:
break
}
} catch let error {
Logger.log("send keep live pack error: \(error)")
}
}
timer.resume()
Expand Down Expand Up @@ -219,13 +233,17 @@ class DanmakuViewController: NSViewController {
$0.window?.orderOut(nil)
}
Logger.log("iina idle")
default:
break
}
} else if let re = socketEvent.success {
Logger.log("iina event success? \(re)")
}
}) {
self.socket?.close()
self.socket = nil
self.douyuSocket?.close()
self.douyuSocket = nil
Logger.log("mpv socket disconnected")
}
}
Expand Down Expand Up @@ -276,6 +294,78 @@ window.cm.send({'text': "\(str)",'stime': 0,'mode': 1,'color': 0xffffff,'border'
}


func initDouYuSocket(_ roomID: String) {
DispatchQueue(label: "com.xjbeta.douyuSocket").async {
do {
self.douyuSocket = try Socket.create(family: .inet, type: .stream, proto: .tcp)

try self.douyuSocket?.connect(to: "openbarrage.douyutv.com", port: 8601)
Logger.log("douyu socket started: \(self.douyuSocket?.isConnected ?? false)")
let loginreq = "type@=loginreq/roomid@=\(roomID)/"
let joingroup = "type@=joingroup/rid@=\(roomID)/gid@=-9999/"

try self.douyuSocket?.write(from: self.douyuSocketFormatter(loginreq))
try self.douyuSocket?.write(from: self.douyuSocketFormatter(joingroup))
self.startTimer()

var savedData = Data()
repeat {

var d = Data()
let _ = try self.douyuSocket?.read(into: &d)
if d.count == 0 {
self.douyuSocket?.close()
}

if savedData.count != 0 {
savedData.append(d)
d = savedData
savedData = Data()
}

var msgDatas: [Data] = []

while d.count > 12 {
let head = d.subdata(in: 0..<4)
let endIndex = Int(CFSwapInt32LittleToHost(head.withUnsafeBytes { (ptr: UnsafePointer<UInt32>) in ptr.pointee }))
if d.count < endIndex+2 {
savedData.append(savedData)
d = Data()
} else {
let msg = d.subdata(in: 12..<endIndex+2)
msgDatas.append(msg)
d = d.subdata(in: endIndex+2..<d.endIndex)
}
}

msgDatas.compactMap {
String(data: $0, encoding: .utf8)
}.forEach {
if $0.starts(with: "type@=chatmsg") {
let dm = $0.subString(from: "txt@=", to: "/cid@=")
DispatchQueue.main.async {
self.sendDM(dm)
}
} else if $0.starts(with: "type@=error") {
Logger.log("douyu socket disconnected: \($0)")
self.douyuSocket?.close()
}
}
} while true
} catch let error {
Logger.log("Douyu socket error: \(error)")
}
}
}

func douyuSocketFormatter(_ str: String) -> Data {
let str = str + "\0"
let data = pack(format: "VVV", values: [str.count + 8, str.count + 8, 689])
data.append(str.data(using: .utf8) ?? Data())
return data as Data
}


}


Expand Down Expand Up @@ -458,6 +548,10 @@ extension DanmakuViewController: SRWebSocketDelegate {
let number: UInt32 = UInt32(value)
var convertedNumber = CFSwapInt32(number)
data.append(&convertedNumber, length: 4)
case "V":
let number: UInt32 = UInt32(value)
var convertedNumber = CFSwapInt32LittleToHost(number)
data.append(&convertedNumber, length: 4)
default:
print("Unrecognized character: \($0.element)")
}
Expand Down
2 changes: 1 addition & 1 deletion iina+/Views/MainWindow/MainViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ class MainViewController: NSViewController {
// init Danmaku
if Preferences.shared.enableDanmaku {
switch site {
case .bilibili, .biliLive, .panda:
case .bilibili, .biliLive, .panda, .douyu:
self.danmakuWindowController?.initDanmaku(site, title, searchField.stringValue)
default:
break
Expand Down

0 comments on commit 68e0593

Please sign in to comment.