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

More features and bug fixes #18

Merged
merged 9 commits into from
Aug 30, 2023
Merged
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
17 changes: 11 additions & 6 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,22 @@

if __name__ == "__main__":
try:
global settings
if platform.system() != "Windows":
Logger.write(message="Sorry! only supports Windows.", level="ERROR")
exit()
with open('settings.json') as json_file:
raw_settings = json.load(json_file)
if raw_settings["firstRun"] == True:
clientId = input(" App | Enter your ClientId: ")
profile = input(" App | Enter your Profile Name (default): ")
clientId = input(" App | Enter your ClientId (number): ")
profile = input(" App | Enter your Profile Name (Default): ")
refreshRate = input(" App | Refresh rate in seconds (number): ")
useTimeLeft = input(" App | Display time remaining instead of elapsed time? (yes/no): ")
newSettings = json.dumps({
"firstRun": False,
"client_id": clientId or "1145497578583105596",
"profile_name": profile or "Default"
"client_id": clientId or raw_settings["client_id"],
"profile_name": profile or "Default",
"RefreshRate": int(refreshRate) or 1,
"DisplayTimeLeft": useTimeLeft.lower() or "yes"
})
with open('settings.json', 'w') as outfile:
outfile.write(newSettings)
Expand All @@ -28,7 +31,9 @@
client_id= settings["client_id"],
version=__version__,
title=__title__,
profileName= settings["profile_name"]
profileName= settings["profile_name"],
refreshRate= settings["RefreshRate"],
useTimeLeft= settings["DisplayTimeLeft"]
)
app.sync()
app.run()
Expand Down
2 changes: 1 addition & 1 deletion settings.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"firstRun": false, "client_id": "1145497578583105596", "profile_name": "Profile 1"}
{"firstRun": true, "client_id": "1145497578583105596", "profile_name": "Default", "RefreshRate": 1, "DisplayTimeLeft": "yes"}
2 changes: 1 addition & 1 deletion src/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@

__all__ = ["App", "Logger"]
__title__ = "Youtube Music RPC"
__version__ = "0.5.2"
__version__ = "0.5.3"
__author__ = "Manuel Cabral"
__license__ = "MIT"
54 changes: 44 additions & 10 deletions src/app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import time
import os
import math
from .presence import Presence
from .logger import Logger
from .tab import Tab
Expand All @@ -24,16 +25,19 @@ class App:
"connected",
"version",
"title",
"__profileName"
"__profileName",
"refreshRate",
"useTimeLeft"
)

def __init__(
self,
client_id: str = "1145497578583105596",
client_id: str = "",
version: str = None,
title: str = None,
profileName: str = "Default",

refreshRate: int = 1,
useTimeLeft: str = "yes"
):
os.system("title " + title + " v" + version)
Logger.write(message=f"{title} v{version}", level="INFO", origin=self)
Expand All @@ -44,7 +48,9 @@ def __init__(
self.last_tab = None
self.connected = False
self.__browser = None
self.__profileName = profileName or "Default"
self.refreshRate = refreshRate
self.useTimeLeft = useTimeLeft
self.__profileName = profileName

def __handle_exception(self, exc: Exception) -> None:
Logger.write(message=exc, level="ERROR", origin=self)
Expand Down Expand Up @@ -92,6 +98,13 @@ def current_playing_tab(self, tabs: list) -> dict:

def run(self) -> None:
global lastUpdated
global compareTab
compareTab = {
"title": "",
"artist": "",
"artwork": "",
"lastTime": 0
}
lastUpdated = 1
try:
if not self.connected:
Expand Down Expand Up @@ -123,6 +136,7 @@ def run(self) -> None:
Logger.write(message="Starting presence loop..", origin=self)
time.sleep(3)
while self.connected:
#time.sleep(self.refreshRate)
tabs = self.update_tabs()
tab = [tab for tab in tabs if tab.playing] or [
tab for tab in tabs if tab.pause
Expand All @@ -141,16 +155,30 @@ def run(self) -> None:
},
],
)
time.sleep(15)
time.sleep(DISCORD_STATUS_LIMIT)
continue
tab = tab[0]
compareTab["title"] = tab.title
compareTab["artwork"] = tab.artwork
compareTab["artist"] = tab.artist
compareTab["lastTime"] = tab.start
if tab.ad:
Logger.write(message="Ad detected.", origin=self)
time.sleep(DISCORD_STATUS_LIMIT)
continue
if self.last_tab == tab:
time.sleep(2)
continue
#fixed problem where it didn't detect the page change (appears to happen sometimes in playlists)
if (compareTab["title"] == self.last_tab.title and compareTab["artist"] == self.last_tab.artist):
time.sleep(self.refreshRate)
continue
if self.last_tab:
if (compareTab["title"] == self.last_tab.title and compareTab["artist"] == self.last_tab.artist):
time.sleep(self.refreshRate)
continue
if self.last_tab.start == compareTab["lastTime"]:
time.sleep(self.refreshRate)
continue

if lastUpdated + 15 > time.time():
remaining = time.time() - (lastUpdated + 15)
if remaining < 0:
Expand All @@ -163,6 +191,11 @@ def run(self) -> None:
message=f"Playing {self.last_tab.title} by {self.last_tab.artist}",
origin=self,
)
def useTimeLeft(answer):
if answer == "yes":
return self.last_tab.end + self.refreshRate
return None

self.__presence.update(
details=self.last_tab.title,
state=self.last_tab.artist,
Expand All @@ -177,10 +210,11 @@ def run(self) -> None:
"url": "https://manucabral.github.io/YoutubeMusicRPC/",
},
],
# TODO: enhance time left
start=time.time(),
# TODO: enhance time left -> Done! --Nelly
start= self.last_tab.start,
end = useTimeLeft(self.useTimeLeft)
)
time.sleep(2)
#time.sleep(self.refreshRate)
except Exception as exc:
self.__handle_exception(exc)
if exc.__class__.__name__ == "URLError":
Expand Down
58 changes: 56 additions & 2 deletions src/tab.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import json
import datetime
import time
from .client import Client

import math

class Tab:

def __init__(self, **kwargs):
self.__dict__.update(kwargs)
self.connected = False
Expand All @@ -25,6 +27,48 @@ def connect(self):
self.connected = True

def sync(self):
global LastTime
LastTime = 4
def filterZeros(string: str):
if string.startswith("0") and len(string) > 1:
return int(string[1:])
return int(string)
def checkForUpdate(eclapsedTime):
if returnTimeInUnix(eclapsedTime) == LastTime:
startUnixTime = time.time()
return startUnixTime
return

def returnTimeInUnix(dict: dict):
global TimeInUnix
global timeType
timeType = "Minutes"
TimeInUnix = 0
if len(dict) == 3:
timeType = "Hours"
elif len(dict) == 2:
timeType = "Minutes"

if timeType == "Hours":
for x in range(0, len(dict), 1):
filteredNumber = filterZeros(dict[x])
if x == 0 :
TimeInUnix = TimeInUnix + (filteredNumber*3600)
elif x == 1:
TimeInUnix = TimeInUnix + (filteredNumber*60)
elif x == 2:
TimeInUnix = TimeInUnix + filteredNumber
return TimeInUnix
if timeType == "Minutes":
for x in range(0, len(dict), 1):
filteredNumber = filterZeros(dict[x])
if x == 0:
TimeInUnix = TimeInUnix + (filteredNumber*60)
elif x == 1:
TimeInUnix = TimeInUnix + filteredNumber
return TimeInUnix


if not self.connected:
raise Exception("Tab is not connected")
self.metadata = self.__parse_response(
Expand Down Expand Up @@ -57,8 +101,18 @@ def sync(self):
self.start = self.end = 1
self.artist = "Advertisement"
return
# TODO: parse times to unix epoch
# TODO: parse times to unix epoch -> Done! --Nelly

times = self.metadata[5].split(" / ")
eclapsedTime = times[0].split(":")
timeLeft = times[1].split(":")
startUnixTime = time.time() - returnTimeInUnix(eclapsedTime)
EndUnixTime = time.time() + returnTimeInUnix(timeLeft)
LastTime = math.trunc(returnTimeInUnix(eclapsedTime))
self.start = math.trunc(startUnixTime)
self.end = math.trunc(EndUnixTime - returnTimeInUnix(eclapsedTime))
#print(eclapsedTime, returnTimeInUnix(eclapsedTime))
#print(times)

def close(self):
if self.connected:
Expand Down