-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathNotepadRPC.py
159 lines (142 loc) · 5.3 KB
/
NotepadRPC.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
VERSION = "0.7"
print("Starting NotepadRPC " + VERSION)
import os
import sys
import time
import ctypes
import calendar
from datetime import datetime
lib = []
try:
import pypresence
except ModuleNotFoundError:
lib.append("pypresence")
try:
from ruamel.yaml import YAML
except ModuleNotFoundError:
lib.append("ruamel.yaml")
if len(lib) > 0:
print("Couldn't find required libraries. Trying to install them...")
for each in lib:
response = os.system('"{}" -m pip install -U '.format(sys.executable) + each + " -q")
if response != 0:
sys.exit("Couldn't install " + each)
print("Successfully installed libraries.")
import pypresence
from ruamel.yaml import YAML
yaml = YAML()
if os.path.exists("config.yml"):
if not os.path.isfile("config.yml"):
sys.exit("Config.yml is not a file.")
else:
open("config.yml", "w+")
print("Generated config.")
with open("config.yml", "r", encoding='utf8') as stream:
config = yaml.load(stream.read()) or {}
def gen_yaml(key, value):
global config
if key not in config:
config[key] = value
return True
re = list()
re.append(gen_yaml("clientId", 529306098646122516))
re.append(gen_yaml("sleep", 1))
re.append(gen_yaml("fileSwitchResetsTimer", True))
re.append(gen_yaml("details", "Editing {}"))
re.append(gen_yaml("large_image", "image_large"))
re.append(gen_yaml("small_image", "image_{}"))
re.append(gen_yaml("bytes", "bytes"))
re.append(gen_yaml("kilobytes", "kilobytes"))
re.append(gen_yaml("megabytes", "megabytes"))
re.append(gen_yaml("gigabytes", "gigabytes"))
if True in re:
yaml.dump(config, open("config.yml", "w", encoding='utf8'))
if os.path.exists("extensions.yml"):
if not os.path.isfile("extensions.yml"):
sys.exit("Extensions.yml is not a file.")
else:
open("extensions.yml", "w+")
print("Generated extensions file.")
with open("extensions.yml", "r", encoding='utf8') as stream:
ext = yaml.load(stream.read()) or {}
EnumWindows = ctypes.windll.user32.EnumWindows
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
GetWindowText = ctypes.windll.user32.GetWindowTextW
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
IsWindowVisible = ctypes.windll.user32.IsWindowVisible
def get_np():
titles = []
def foreach_window(hwnd, lParam):
if IsWindowVisible(hwnd):
length = GetWindowTextLength(hwnd)
buff = ctypes.create_unicode_buffer(length + 1)
GetWindowText(hwnd, buff, length + 1)
titles.append(buff.value)
return True
EnumWindows(EnumWindowsProc(foreach_window), 0)
for each in titles:
if each[-12:] == " - Notepad++":
return each[:-12]
def float_format(number):
number = str(number)
if number.split(".")[1] == "0":
return number.split(".")[0]
number_split = number.split(".")
return number_split[0] + "." + number_split[1][:2]
connected = False
def presence():
global rpc
global config
global started
global connected
file = get_np()
if file is not None:
if not connected:
rpc = pypresence.Presence(config["clientId"])
rpc.connect()
connected = True
started = calendar.timegm(datetime.utcnow().utctimetuple())
if file.startswith("*"):
file = file[1:]
name = file.split("\\")[-1]
if not name.startswith("new ") and "." in name:
extension = name.split(".")[-1]
else:
extension = None
if config["fileSwitchResetsTimer"]:
global old_file
if "old_file" in globals() and old_file != file:
started = calendar.timegm(datetime.utcnow().utctimetuple())
old_file = file
try:
if name.startswith("*new ") or name.startswith("new "):
raise Exception
size = os.path.getsize(file) if file[0] != "*" else os.path.getsize(file[1:])
if size <= 1024:
size_text = str(size) + " " + config["bytes"]
elif size < 1024 * 1024:
size_text = float_format(size/1024) + " " + config["kilobytes"]
elif size < 1024 * 1024 * 1024:
size_text = float_format(size/(1024*1024)) + " " + config["megabytes"]
elif size < 1024 * 1024 * 1024:
size_text = float_format(size/(1024*1024*1024)) + " " + config["gigabytes"]
except:
size_text = None
rpc.update(details=config["details"].replace("{}", name),
state=size_text,
large_image=config["large_image"],
small_image=config["small_image"].replace("{}", extension) if extension is not None else None,
small_text=ext[extension] if extension is not None and extension in ext else None,
start=started)
elif connected:
rpc.close()
connected = False
try:
presence()
except pypresence.exceptions.InvalidID:
sys.exit("Invalid ClientID")
else:
print("NotepadRPC has started successfully!")
while True:
time.sleep(float(config["sleep"]))
presence()