Skip to content

Commit

Permalink
[update] コンテンツスクリプトで一定間隔での監視からイベントリスナーに乗り換える
Browse files Browse the repository at this point in the history
  • Loading branch information
okaits committed Dec 16, 2022
1 parent 12693b7 commit 34009cb
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 42 deletions.
6 changes: 0 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,5 @@ Discord Rich Presenceは変更にDiscordクライアントのRPCを使用する
(server.pyを実行した後に別端末などで実行してください。)

## Contributing
### ToDo
* コンテンツスクリプトにて、現在は一定間隔で再生状態を監視しているが、本来はイベントリスナーに関数を登録する必要がある。
* サーバープログラムにて、現在はプログラム本体に認証情報を書いていて、あまり望ましくない。
* コンテンツスクリプトにて、コードが奇跡的に動作している状態で、安定していない。
* コンテンツスクリプトにて、コードが非常に読みにくく、バグ解消や新機能追加が困難。

### Contributer
* [okaits#7534](https://info.okaits7534.mydns.jp)
70 changes: 37 additions & 33 deletions browser-addon/main.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,47 @@
function beforeunload() {
// navigator.sendBeacon("http://localhost:5000/video", JSON.stringify({"status": "closed"}));
body = JSON.stringify({"status": "closed"});
function senddata() {
var player = this;
var ispaused = player.paused;
var time = player.currentTime;
var hour = Math.floor(time / 3600);
var min = Math.floor(time % 3600 / 60);
var sec = time % 60;
console.debug("Playing: " + !ispaused);
var videoid = window.location.pathname.split("/").pop();
$.ajax({
type: "POST",
url: "http://localhost:5000/video",
data: JSON.stringify({'status': 'opened', 'videoid': videoid, 'playing': !ispaused, 'ended': false, 'hour': hour, 'min': min, 'sec': sec}),
contentType: "application/json; charset=UTF-8"
});
};

function end() {
var videoid = window.location.pathname.split("/").pop();
$.ajax({
type: "POST",
url: "http://localhost:5000/video",
data: JSON.stringify({'status': 'opened', 'videoid': videoid, 'playing': false, 'ended': true}),
contentType: "application/json; charset=UTF-8"
});
};

function close() {
fetch("http://localhost:5000/video", {
method: 'POST',
body: JSON.stringify({"status": "closed"}),
body: JSON.stringify({'status': 'closed'}),
headers: {
"Content-type": "application/json"
"Content-type": "application/json; charset=UTF-8"
},
keepalive: true
});
};

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
function onload() {
var player = document.getElementById("MainVideoPlayer").firstElementChild;
player.addEventListener("play", senddata);
player.addEventListener("pause", senddata);
player.addEventListener("ended", end);
};

async function loop() {
var beforepaused = true;
while (true) {
await sleep(500);
var player = document.getElementById("MainVideoPlayer").firstElementChild;
var ispaused = player.paused;
var time = player.currentTime;
var hour = Math.floor(time / 3600);
var min = Math.floor(time % 3600 / 60);
var sec = time % 60;
if (ispaused == beforepaused) {
continue;
};
console.debug("Playing: " + !ispaused);
var videoid = window.location.pathname.split("/").pop();
$.ajax({
type: "POST",
url: "http://localhost:5000/video",
data: JSON.stringify({'status': 'opened', 'videoid': videoid, 'playing': !ispaused, 'hour': hour, 'min': min, 'sec': sec}),
contentType: "application/json; charset=UTF-8"
});
beforepaused = ispaused;
};
};
console.debug("start")
loop();
window.addEventListener("load", onload);
window.addEventListener("beforeunload", close)
7 changes: 5 additions & 2 deletions client.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,17 @@
videolength = datetime.timedelta(minutes=int(videolength[0]), seconds=int(videolength[1]))
elif len(videolength) == 3:
videolength = datetime.timedelta(hours=int(videolength[0]), minutes=int(videolength[1]), seconds=int(videolength[2]))
playingtime = datetime.timedelta(hours=int(videodata["hour"]), minutes=int(videodata["min"]), seconds=int(videodata["sec"]))
startedtime = datetime.datetime.now().replace(microsecond=0) - playingtime
if videodata["ended"] is False:
playingtime = datetime.timedelta(hours=int(videodata["hour"]), minutes=int(videodata["min"]), seconds=int(videodata["sec"]))
startedtime = datetime.datetime.now().replace(microsecond=0) - playingtime
try:
author = video["user_nickname"]
except KeyError:
author = video["ch_name"]
if videodata["playing"] is True:
statemsg = f'{video["title"]}'
elif videodata["ended"] is True:
statemsg = f'{video["title"]} (再生終了)'
else:
statemsg = f'{video["title"]} (一時停止中)'
detailsmsg = f'投稿者: {author}'
Expand Down
5 changes: 4 additions & 1 deletion server.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ def video():
if data["status"] == "closed":
Data.status = {"status": data["status"]}
return jsonify({"msg": "success"}), "201 Created"
Data.status = {"status": data["status"],"id": data["videoid"], "playing": data["playing"], "hour": data["hour"], "min": data["min"], "sec": str(math.floor(int(data["sec"])))}
elif data["ended"] is True:
Data.status = {"status": data["status"], "id": data["videoid"], "ended": data["ended"], "playing": data["playing"]}
return jsonify({"msg": "success"}), "201 Created"
Data.status = {"status": data["status"],"id": data["videoid"], "ended": data["ended"], "playing": data["playing"], "hour": data["hour"], "min": data["min"], "sec": str(math.floor(int(data["sec"])))}
except KeyError:
print(data)
return jsonify({"msg": "missing value"}), "400 Bad Request"
Expand Down

0 comments on commit 34009cb

Please sign in to comment.