forked from 4lb3rtO/service.nfo.watchedstate.updater
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdefault.py
183 lines (142 loc) · 6.35 KB
/
default.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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
'''
* This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) License.
*
*
* To view a copy of this license, visit
*
* English version: http://creativecommons.org/licenses/by-nc-sa/4.0/
* German version: http://creativecommons.org/licenses/by-nc-sa/4.0/deed.de
*
* or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
'''
import xbmc
import xbmcvfs
import xbmcaddon
import socket
import json
import xml.etree.ElementTree as ET
from os import path
addon = xbmcaddon.Addon('service.nfo.watchedstate.updater')
addon_name = addon.getAddonInfo('name')
delay = '4000'
logo = 'special://home/addons/service.nfo.watchedstate.updater/icon.png'
class NFOWatchedstateUpdater():
def __init__(self):
self.methodDict = {"VideoLibrary.OnUpdate": self.VideoLibraryOnUpdate,
}
self.XBMCIP = addon.getSetting('xbmcip')
self.XBMCPORT = int(addon.getSetting('xbmcport'))
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.setblocking(1)
try:
self.s.connect((self.XBMCIP, self.XBMCPORT))
except Exception, e:
xbmc.executebuiltin('Notification(%s, Error: %s, %s, %s)' %(addon_name, str(e), delay, logo) )
xbmc.sleep(int(delay))
xbmc.executebuiltin('Notification(%s, Please check remote control settings, %s, %s)' %(addon_name, delay, logo) )
xbmc.sleep(int(delay))
#xbmc.executebuiltin('ActivateWindow(10018)')
exit(0)
def handleMsg(self, msg):
jsonmsg = json.loads(msg)
method = jsonmsg['method']
if method in self.methodDict:
methodHandler = self.methodDict[method]
methodHandler(jsonmsg)
def listen(self):
currentBuffer = []
msg = ''
depth = 0
while not xbmc.abortRequested:
chunk = self.s.recv(1)
currentBuffer.append(chunk)
if chunk == '{':
depth += 1
elif chunk == '}':
depth -= 1
if not depth:
msg = ''.join(currentBuffer)
self.handleMsg(msg)
currentBuffer = []
self.s.close()
def VideoLibraryOnUpdate(self, jsonmsg):
#xbmc.log(str(jsonmsg["params"]["data"]["item"]["id"]))
#xbmc.log(str(jsonmsg["params"]["data"]["item"]["type"]))
#xbmc.log(str(jsonmsg["params"]["data"]["playcount"]))
if (jsonmsg["params"]["data"]["item"].has_key("id")) and (jsonmsg["params"]["data"]["item"].has_key("type")) and (jsonmsg["params"]["data"].has_key("playcount")):
itemid = jsonmsg["params"]["data"]["item"]["id"]
itemtype = jsonmsg["params"]["data"]["item"]["type"]
itemplaycount = jsonmsg["params"]["data"]["playcount"]
#xbmc.log(str(type(itemid)))
#xbmc.log(str(type(itemtype)))
#xbmc.log(str(type(itemplaycount)))
if itemtype == u'movie':
msg = xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"VideoLibrary.GetMovieDetails","params":{"movieid":%d,"properties":["file"]},"id":1}' %(itemid) )
jsonmsg = json.loads(msg)
filepath = jsonmsg["result"]["moviedetails"]["file"]
self.updateNFO(filepath, itemplaycount, itemtype)
##When a season is marked as un-/watched, all episodes are edited
if itemtype == u'episode':
msg = xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"VideoLibrary.GetEpisodeDetails","params":{"episodeid":%s,"properties":["file"]},"id":1}' %(str(itemid)) )
jsonmsg = json.loads(msg)
filepath = jsonmsg["result"]["episodedetails"]["file"]
self.updateNFO(filepath, itemplaycount, itemtype)
#if itemtype == u'tvshow':
def updateNFO(self, filepath, playcount, itemtype):
filepath = filepath.replace(path.splitext(filepath)[1], '.nfo')
if xbmcvfs.exists(filepath):
sFile = xbmcvfs.File(filepath)
currentBuffer = []
msg = ''
while True:
buf = sFile.read(1024)
currentBuffer.append(buf)
if not buf:
msg = ''.join(currentBuffer)
break
sFile.close()
tree = ET.ElementTree(ET.fromstring(msg)) # crashes if msg empty
root = tree.getroot()
else:
root = ET.Element(itemtype)
p = root.find('playcount')
if p is None:
p = ET.SubElement(root, 'playcount')
p.text = str(playcount)
if addon.getSetting('changewatchedtag') == 'true':
w = root.find('watched')
if (w is None) and (addon.getSetting('createwatchedtag') == 'true'):
w = ET.SubElement(root, 'watched')
if playcount > 0:
w.text = 'true'
else:
w.text = 'false'
self.prettyPrintXML(root)
msg = ET.tostring(root, encoding='UTF-8')
if msg:
dFile = xbmcvfs.File(filepath, 'w')
dFile.write(msg) ##String msg or bytearray: bytearray(msg)
dFile.close()
#if addon.getSetting('notification') == 'true':
# xbmc.executebuiltin('Notification(%s, NFO updated, %s, %s)' %(addon_name, noti_duration, logo) )
else:
if addon.getSetting('notification') == 'true':
xbmc.executebuiltin('Notification(%s, Error occured, %s, %s)' %(addon_name, delay, logo) )
def prettyPrintXML(self, elem, level=0):
i = '\n' + level * ' '
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
self.prettyPrintXML(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
if __name__ == '__main__':
WU = NFOWatchedstateUpdater()
WU.listen()
del WU