1+ # -*- coding:utf-8 -*-
2+
3+ """
4+ _ _ _____ _ _ _____ _____ _____
5+ /\ | | | | | __ \(_) | | | __ \| __ \ / ____|
6+ / \ __| | ___ | |__ ___ | | | |_ ___ ___ ___ _ __ __| | | |__) | |__) | |
7+ / /\ \ / _` |/ _ \| '_ \ / _ \ | | | | / __|/ __/ _ \| '__/ _` | | _ /| ___/| |
8+ / ____ \ (_| | (_) | |_) | __/ | |__| | \__ \ (_| (_) | | | (_| | | | \ \| | | |____
9+ /_/ \_\__,_|\___/|_.__/ \___| |_____/|_|___/\___\___/|_| \__,_| |_| \_\_| \_____|
10+
11+ Ver. 3.4
12+ © 2017-2020 화향.
13+ Follow GPL-3.0
14+ Gtihub || https://github.com/hwahyang1/Adobe-Discord-RPC
15+
16+ :: Program Core ::
17+ """
18+
19+ if __name__ == "__main__" :
20+ def log (tpe , inf , datetime = None ):
21+ if not os .path .isfile ('./log.log' ):
22+ open ('./log.log' , 'w' ).close ()
23+ if datetime == None :
24+ prnt = "시간정보 없음 | %s | %s" % (tpe , inf )
25+ else :
26+ now = datetime .datetime .now ()
27+ prnt = "%s-%02d-%02d %02d:%02d:%02d | %s | %s" % (now .year , now .month , now .day , now .hour , now .minute , now .second , tpe , inf )
28+ f = open ("./log.log" , 'a' , encoding = 'utf8' )
29+ f .write (prnt + "\n " )
30+ f .close ()
31+ print (prnt )
32+ try :
33+ from pypresence import Presence
34+ import datetime , os , requests , sys , psutil , json , win32gui , win32process , time , pandas , plyer , re , win32ui , win32con , platform
35+ except ModuleNotFoundError as e :
36+ if not (str (e ) in 'plyer' ):
37+ plyer .notification .notify (
38+ title = 'Adobe Discord RPC' ,
39+ message = '모듈 불러오기에 실패했습니다.\n 로그를 확인하세요.' ,
40+ app_name = 'Adobe Discord RPC' ,
41+ app_icon = 'icon_alpha.ico'
42+ )
43+ log ("ERROR" , "%s 모듈이 존재하지 않습니다." % (str (e ).replace ('No module named ' , '' )))
44+ goout ()
45+
46+
47+ try :
48+ os .remove ('./stop.req' )
49+ except FileNotFoundError :
50+ pass
51+
52+ def goout (datetime = None ):
53+ log ("INFO" , "Adobe Discord RPC가 종료됩니다." , datetime )
54+ #time.sleep(30)
55+ #os.system('adoberpc.exe')
56+ #exit()
57+ sys .exit ()
58+
59+ def checkver ():
60+ # 20-03-23 방식 변경
61+ # 새 버전 알림 -> 새 버전 알림 후 업데이트 수락하면 업데이터 가동
62+ with open ('programver.json' , encoding = 'utf8' ) as f :
63+ data = json .load (f )
64+ nowver = data ['ver' ]
65+ r = requests .get ("https://cdn.adoberpc.hwahyang.space/adoberpc_ver.json" )
66+ if r .status_code != 200 :
67+ r = requests .get ("https://cdn.hwahyang.space/adoberpc_ver.json" )
68+ r = r .text
69+ data = json .loads (r )
70+ latest = float (data ["ver" ]) # 바보야 int 아니라고,,
71+ if latest > nowver : # 만약에 최신이 더 높다면,
72+ log ("DEBUG" , "새 버전 알림 발신. || 현재 : %s || 최신 : %s" % (nowver , latest ), datetime )
73+ plyer .notification .notify (
74+ title = 'Adobe Discord RPC' ,
75+ message = 'Adobe Discord RPC가 가동되었습니다.\n 새 버전이 있습니다.\n V%s (현재) -> V%s (최신)' % (nowver , latest ),
76+ app_name = 'Adobe Discord RPC' ,
77+ app_icon = 'icon_alpha.ico'
78+ )
79+ res = win32ui .MessageBox ("새 버전이 있습니다.\n V%s (현재) -> V%s (최신)\n 업데이트를 진행할까요?" % (nowver , latest ), "Adobe Discord RPC" , win32con .MB_YESNO )
80+ if res == win32con .IDYES :
81+ os .system ('start adoberpc_updater.exe' )
82+ open ("stop.req" , 'w' ).close ()
83+ goout ()
84+ else :
85+ log ("DEBUG" , "버전 변동 없음. || 현재 : %s || 최신 : %s" % (nowver , latest ), datetime )
86+ #notification.notify(
87+ # title='Adobe Discord RPC',
88+ # message='Adobe Discord RPC가 가동되었습니다.\n새 버전이 존재하지 않습니다.',
89+ # app_name='Adobe Discord RPC',
90+ # app_icon='icon_alpha.ico'
91+ #)
92+
93+ with open ('pinfo.json' , encoding = 'utf8' ) as f :
94+ data = json .load (f )
95+
96+ def get_title (pid ):
97+ def callback (hwnd , hwnds ):
98+ if win32gui .IsWindowVisible (hwnd ) and win32gui .IsWindowEnabled (hwnd ):
99+ _ , found_pid = win32process .GetWindowThreadProcessId (hwnd )
100+ if found_pid == pid :
101+ hwnds .append (hwnd )
102+ hwnds = []
103+ win32gui .EnumWindows (callback , hwnds )
104+ window_title = win32gui .GetWindowText (hwnds [- 1 ])
105+ return window_title
106+
107+ def get_info (programname ):
108+ getp = lambda process : (list (p .info for p in filter ((lambda p : p .info ['name' ] and p .info ['name' ] == process ),list (psutil .process_iter (['pid' ,'name' ,'exe' ,'status' ])))))
109+ returns = getp (programname )
110+
111+ if not returns : # 미친 이거 왜됨
112+ return [False ]
113+
114+ returns = returns [0 ]
115+
116+ try :
117+ windowname = get_title (returns ['pid' ])
118+ except Exception as e :
119+ print (e )
120+ return [False ]
121+
122+ return [True , returns ['name' ], returns ['pid' ], windowname , returns ['status' ], returns ['exe' ]]
123+
124+ def get_process_info ():
125+ for now_json in data :
126+ def_returned = get_info (now_json ['processName' ])
127+ if def_returned [0 ]:
128+ return def_returned + [now_json ]
129+ else :
130+ continue
131+
132+ return [False ]
133+
134+ def get_window_title (pid ):
135+ def callback (hwnd , hwnds ):
136+ if win32gui .IsWindowVisible (hwnd ) and win32gui .IsWindowEnabled (hwnd ):
137+ _ , found_pid = win32process .GetWindowThreadProcessId (hwnd )
138+ if found_pid == pid :
139+ hwnds .append (hwnd )
140+ hwnds = []
141+ win32gui .EnumWindows (callback , hwnds )
142+ window_title = win32gui .GetWindowText (hwnds [- 1 ])
143+ return window_title
144+
145+ if not (sys .platform in ['Windows' , 'win32' , 'cygwin' ]):
146+ # 않이 근데 왠만해선 타 OS에서 돌릴 일은 없지 않나
147+ log ("ERROR" , "지원하지 않는 OS : %s" % (sys .platform ))
148+ goout (datetime )
149+
150+ if int (platform .release ()) < 7 :
151+ log ("ERROR" , "지원하지 않는 Windows 버전 : %s" % (platform .release ()))
152+ goout (datetime )
153+
154+ checkver ()
155+
156+ try : # 애러나면 로그는 해야죠
157+ while True :
158+ # 죽을때까지 실행 검증 루프
159+ a = True
160+ while a : # 실행 없으면 15초 쉬었다 루프 다시. --> 30초로 변경.
161+ try :
162+ pinfo = get_process_info ()
163+ if not pinfo [0 ]:
164+ log ("DEBUG" , "발견된 프로세스 없음" , datetime )
165+ log ("DEBUG" , "30초 후 다시 시도.." , datetime )
166+ time .sleep (30 )
167+ continue
168+ window_title = pinfo [3 ]
169+ a = False # 루프 종료
170+ except IndexError as e :
171+ log ("ERROR" , "정의 애러.. 10초 후 다시 시도 : %s" % (e ), datetime )
172+ time .sleep (10 )
173+
174+ RPC = Presence (pinfo [len (pinfo )- 1 ]['appid' ])
175+
176+ try :
177+ RPC .connect ()
178+ except Exception as e :
179+ log ("ERROR" , "디스코드와 연결하지 못했습니다." , datetime )
180+ log ("ERROR" , "디스코드가 켜져 있는지 확인 해 주세요." , datetime )
181+ log ("DEBUG" , "ERRINFO :: %s" % (e ), datetime )
182+ plyer .notification .notify (
183+ title = 'Adobe Discord RPC' ,
184+ message = '디스코드와 연결하지 못하였습니다.\n 디스코드가 켜져 있는지 다시 한번 확인 해 주세요.\n 30초 후 연결을 다시 시도합니다.' ,
185+ app_name = 'Adobe Discord RPC' ,
186+ app_icon = 'icon_alpha.ico'
187+ )
188+ goout (datetime )
189+ log ("INFO" , "성공적으로 디스코드와 연결 하였습니다!" , datetime )
190+
191+ dt = pandas .to_datetime (datetime .datetime .now ())
192+ # -1은 미사용
193+ # 그 이상은 splitindex 용도로 사용함
194+ if pinfo [len (pinfo )- 1 ]['getver' ] == - 1 :
195+ version = ''
196+ else :
197+ path = pinfo [5 ].split (pinfo [len (pinfo )- 1 ]['publicName' ])[1 ]
198+ path = path .split ('\\ ' )[pinfo [len (pinfo )- 1 ]['getver' ]]
199+ version = path .replace (" " , '' )
200+
201+ filename = window_title .split (pinfo [len (pinfo )- 1 ]['splitBy' ])[pinfo [len (pinfo )- 1 ]['splitIndex' ]]
202+ lmt = pinfo [len (pinfo )- 1 ]['largeText' ].replace ('%Ver%' , version )
203+ lmt = lmt .replace ('%Filename%' , filename )
204+ smt = pinfo [len (pinfo )- 1 ]['smallText' ].replace ('%Filename%' , filename )
205+ smt = smt .replace ('%Ver%' , version )
206+ b = True
207+
208+ plyer .notification .notify (
209+ title = 'Adobe Discord RPC' ,
210+ message = '성공적으로 디스코드와 연결했습니다.\n %s를 플레이 하게 됩니다.' % (pinfo [len (pinfo )- 1 ]['publicName' ]),
211+ app_name = 'Adobe Discord RPC' ,
212+ app_icon = 'icon_alpha.ico'
213+ )
214+
215+ while b :
216+ # 20-04-25 코드 구조 대량으로 변경되어서 응답없음 여부 사용 안함
217+ """if not isresponding(pinfo['processName'].replace('.exe', ''), datetime):
218+ # 응답없음은 10초 간격으로 체크해서 응답없음 풀리면 c = False 로 만듬
219+ c = True
220+ while c:
221+ try:
222+ rtn = RPC.update(
223+ large_image='lg', large_text='프로그램 : %s' % (pinfo['publicName']),
224+ small_image='sm_temp', small_text="파일명 : %s" %(filename),
225+ details="응답없음", state="응답없음",
226+ start=int(time.mktime(dt.timetuple()))
227+ )
228+ except Exception as e:
229+ log("ERROR", "pypresence 갱신 실패... 10초 대기 : %s" % (e), datetime)
230+ plyer.notification.notify(
231+ title='Adobe Discord RPC',
232+ message='RPC 갱신에 실패하였습니다.\n 10초 후 다시 시도합니다.',
233+ app_name='Adobe Discord RPC',
234+ app_icon='icon_alpha.ico'
235+ )
236+ b = False
237+ time.sleep(10)
238+ else:
239+ log("DEBUG", "pypresence 리턴 : %s" % (rtn), datetime)
240+ time.sleep(10)
241+
242+ if not isresponding(pinfo['processName'].replace('.exe', ''), datetime):
243+ pass
244+ else:
245+ # 정상실행 경우
246+ # RPC.clear(pid=os.getpid())
247+ c = False
248+ pass
249+ else:"""
250+ try :
251+ rtn = RPC .update (
252+ large_image = 'lg' , large_text = '프로그램 : %s' % (pinfo [len (pinfo )- 1 ]['publicName' ]),
253+ small_image = 'sm_temp' , small_text = "Adobe Discord RPC" ,
254+ details = lmt , state = smt ,
255+ start = int (time .mktime (dt .timetuple ()))
256+ )
257+ except Exception as e :
258+ log ("ERROR" , "pypresence 갱신 실패... 30초 대기 : %s" % (e ), datetime )
259+ plyer .notification .notify (
260+ title = 'Adobe Discord RPC' ,
261+ message = 'RPC 갱신에 실패하였습니다.\n 30초 후 다시 시도합니다.' ,
262+ app_name = 'Adobe Discord RPC' ,
263+ app_icon = 'icon_alpha.ico'
264+ )
265+ b = False
266+ time .sleep (30 )
267+ else :
268+ log ("DEBUG" , "pypresence 리턴 : %s" % (rtn ), datetime )
269+ time .sleep (30 )
270+ #time.sleep(5) # 테스트용인데 왜 주석 안하고 배포한거야
271+
272+ try :
273+ window_title = get_window_title (pinfo [2 ])
274+ filename = window_title .split (pinfo [len (pinfo )- 1 ]['splitBy' ])[pinfo [len (pinfo )- 1 ]['splitIndex' ]]
275+ lmt = pinfo [len (pinfo )- 1 ]['largeText' ].replace ('%Ver%' , version )
276+ lmt = lmt .replace ('%Filename%' , filename )
277+ smt = pinfo [len (pinfo )- 1 ]['smallText' ].replace ('%Filename%' , filename )
278+ smt = smt .replace ('%Ver%' , version )
279+ pass
280+ except IndexError as e :
281+ # PID 변경 OR 프로그램 종료. 같은 PID 금방 다시 할당할 일 없음.
282+ log ("DEBUG" , "PID 변동 OR 프로세스 종료. : %s -> %s" % (pinfo ['pid' ], e ), datetime )
283+ RPC .clear (pid = os .getpid ())
284+ b = False
285+ except KeyboardInterrupt :
286+ log ("DEBUG" , "콘솔 단에서 중지함." , datetime )
287+ goout ()
288+ except Exception as e :
289+ log ("ERROR" , "미정의 애러 : %s" % (e ), datetime )
290+ goout ()
291+
292+ # End of Code.
0 commit comments