-
Notifications
You must be signed in to change notification settings - Fork 7
/
addon.py
311 lines (288 loc) · 10.3 KB
/
addon.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#!/usr/bin/env python
import os
import sys
import urllib
from urllib.parse import quote_plus
import http.cookiejar
import xbmcgui
import xbmcaddon
import xbmcvfs
import simplejson as json
__addon__ = xbmcaddon.Addon()
__addonname__ = __addon__.getAddonInfo('name')
__profile__ = xbmcvfs.translatePath( __addon__.getAddonInfo('profile') )
__icon__ = __addon__.getAddonInfo('icon')
localize = __addon__.getLocalizedString
from xbmcapi import XBMCSourcePlugin
cookie_filename = __profile__+'pwg.cookie'
cookieJar = http.cookiejar.LWPCookieJar(cookie_filename)
if os.access(cookie_filename, os.F_OK):
cookieJar.load(ignore_discard=True)
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookieJar))
opener.add_handler(urllib.request.HTTPSHandler())
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11'),]
plugin = XBMCSourcePlugin()
def cleanURL(src):
return urllib.parse.quote(src, safe='/:?&')
def checkMethods():
opts = [
{'dependencies': ['pwg.categories.getImages'], 'urivar': 'recent', 'labelid': 43100, 'adminonly': False},
{'dependencies': ['pwg.categories.getImages'], 'urivar': 'random', 'labelid': 43101, 'adminonly': False},
{'dependencies': ['pwg.categories.getImages'], 'urivar': 'rated', 'labelid': 43102, 'adminonly': False},
{'dependencies': ['pwg.categories.getList'], 'urivar': 'cats', 'labelid': 43103, 'adminonly': False},
{'dependencies': ['pwg.tags.getList', 'pwg.tags.getImages'], 'urivar': 'tags', 'labelid': 43104, 'adminonly': False},
{'dependencies': ['pwg.collections.getList', 'pwg.collections.getImages'], 'urivar': 'collection', 'labelid': 43119, 'adminonly': False},
{'dependencies': ['pwg.users.favorites.getList'], 'urivar': 'favorites', 'labelid': 43120, 'adminonly': False},
{'dependencies': ['pwg.images.search'], 'urivar': 'search', 'labelid': 43105, 'adminonly': False},
{'dependencies': False, 'urivar': 'sync', 'labelid': 43114, 'adminonly': True},
]
returnopts = {}
user = serverRequest('pwg.session.getStatus')
methods = serverRequest('reflection.getMethodList')['methods']
for opt in opts :
addOpt = False
if opt['dependencies'] != False :
approved = 0
for optDep in opt['dependencies'] :
for method in methods :
if method == optDep :
approved += 1
break
if len(opt['dependencies']) <= approved :
addOpt = True
else :
addOpt = True
if opt['adminonly'] == True and (user['status'] != 'webmaster' and user['status'] != 'admin' and user['status'] != 'administrator') :
addOpt = False
if addOpt == True:
returnopts[localize(opt['labelid'])] = opt['urivar']
return returnopts
def home():
opts = checkMethods()
for key in opts.items():
listitem = xbmcgui.ListItem(key[0])
plugin.addDirectoryItem(url='%s/%s' % (plugin.root, key[1]), listitem=listitem, isFolder=True)
plugin.endOfDirectory()
def serverLogin():
url = '%s/ws.php?format=json' % (plugin.getSetting('server'))
values = {
'method' : 'pwg.session.login',
'username' : plugin.getSetting('username'),
'password' : plugin.getSetting('password')
}
data = urllib.parse.urlencode(values).encode('utf-8')
req = urllib.request.Request(url, data)
try:
conn = opener.open(req)
cookieJar.save(ignore_discard=True)
connRead = conn.read()
conn.close()
except:
die(True)
else:
try:
response = json.loads(connRead)
except:
die(True)
else:
if(response['stat'] == 'ok') :
return True
else:
if(plugin.getSetting('username') != 'guest' and plugin.getSetting('username') != '') :
xbmcgui.Dialog().ok(__addonname__, localize(43106), localize(43107))
die(False)
pass
def serverRequest(method,extraData = []):
url = '%s/ws.php?format=json' % (plugin.getSetting('server'))
values = {
'method' : method
}
try:
for key in extraData.items():
values[key[0]] = key[1]
except:
pass
data = urllib.parse.urlencode(values).encode('utf-8')
req = urllib.request.Request(url, data)
conn = opener.open(req)
response = json.loads(conn.read())
conn.close()
if(response['stat'] == 'ok') :
return response['result']
else :
xbmcgui.Dialog().ok(__addonname__, localize(43109), '%s: %s' % (localize(43110), method), response['message'])
die(False)
def populateDirectory(array):
for obj in array:
try:
thumb = cleanURL(obj['tn_url'])
except:
listitem = xbmcgui.ListItem(obj['name'])
else:
listitem = xbmcgui.ListItem(obj['name'])
listitem.setArt({'thumb':thumb, 'icon':thumb})
finally:
plugin.addDirectoryItem(url='%s/%s/%s/0' % (plugin.root, plugin.path, obj['id']), listitem=listitem, isFolder=True)
plugin.endOfDirectory()
def populateImages(imgs):
for img in imgs['images']:
if(img['name'] == None) :
if(img['date_creation'] == None) :
ttl = img['date_available']
else :
ttl = img['date_creation']
else :
ttl = img['name']
listitem = xbmcgui.ListItem(ttl)
listitem.setArt({ 'thumb' : cleanURL(img['derivatives']['thumb']['url']) })
listitem.setInfo('pictures',{'date':img['date_available']})
commands = []
listitem.addContextMenuItems( commands )
try:
src = img['element_url']
except:
src = img['derivatives']['xxlarge']['url']
plugin.addDirectoryItem(url=cleanURL(src), listitem=listitem)
if(int(plugin.getSetting('limit')) <= int(imgs['paging']['count'])) :
nextString = '> %s' % (localize(43115))
nextCount = plugin.getSetting('limit')
try:
imgCount = (imgs['paging']['page'] + 1)* imgs['paging']['per_page']
remainingImageCount = imgs['paging']['total_count'] - imgCount
if(remainingImageCount < int(plugin.getSetting('limit'))):
nextCount = remainingImageCount
except:
pass
try:
nextString += ' %s (%s %s)' % (nextCount, imgs['paging']['total_count'], localize(43116))
except:
nextString += ' %s' % (nextCount)
listitem = xbmcgui.ListItem(nextString)
newpath = plugin.path.split('/')
try:
if(int(newpath[-1]) >= 0):
del newpath[-1]
except:
pass
newpathCon = '/'.join(newpath)
plugin.addDirectoryItem(url='%s/%s/%s' % (plugin.root, newpathCon, (int(imgs['paging']['page']) + 1)), listitem=listitem, isFolder=True)
plugin.endOfDirectory()
def recursiveCategoryImages(catId,page):
if(page == 0) :
categories = serverRequest('pwg.categories.getList',{'cat_id':catId})['categories']
del categories[0]
for catg in categories:
listitem = xbmcgui.ListItem('> '+catg['name'])
try:
thumb = cleanURL(catg['tn_url'])
listitem.setArt({'icon': thumb, 'thumb': thumb})
except:
pass
finally:
plugin.addDirectoryItem(url='%s/cats/%s/0' % (plugin.root, catg['id']), listitem=listitem, isFolder=True)
populateImages(serverRequest('pwg.categories.getImages', {'cat_id':catId, 'page':page, 'per_page':plugin.getSetting('limit')}))
def die(alert):
if alert:
xbmcgui.Dialog().ok(localize(43111), localize(43107))
raise SystemExit(0)
def syncServer():
url = '%s/admin.php?page=site_update&site=1' % (plugin.getSetting('server'))
values = {
'sync': 'files',
'display_info': 1,
'add_to_caddie': 1,
'privacy_level': 0,
'simulate': 0,
'subcats-included': 1,
'submit': 1
}
data = urllib.parse.urlencode(values).encode('utf-8')
req = urllib.request.Request(url, data)
try:
conn = opener.open(req)
except:
xbmcgui.Dialog().ok(__addonname__, localize(43112), localize(43108))
die(False)
else:
response = conn.read()
conn.close()
if response.find(b'scanning dirs'):
xbmc.executebuiltin('Notification(%s, %s, 5000, %s)'%(__addonname__, localize(43117), __icon__))
elif response.find(b'synchronization is disabled'):
xbmc.executebuiltin('Notification(%s, %s, 5000, %s)'%(__addonname__, localize(43112), __icon__))
else:
xbmcgui.Dialog().ok(__addonname__, localize(43112), localize(43108))
die(False)
if plugin.path:
split = plugin.path.split('/')
crntPage = 0
if(split[0] == 'tags') :
try:
typeId0 = split[1]
crntPage = int(split[2])
except:
populateDirectory(serverRequest('pwg.tags.getList')['tags'])
else :
populateImages(serverRequest('pwg.tags.getImages', {'tag_id':typeId0,'page':crntPage,'per_page' : plugin.getSetting('limit')}))
elif(split[0] == 'cats') :
try:
typeId0 = split[1]
crntPage = int(split[2])
except:
populateDirectory(serverRequest('pwg.categories.getList')['categories'])
else :
recursiveCategoryImages(typeId0,crntPage)
elif(split[0] == 'collection') :
try:
typeId0 = split[1]
crntPage = int(split[2])
except:
populateDirectory(serverRequest('pwg.collections.getList', {'page':0, 'per_page':plugin.getSetting('limit')})['collections'])
else :
populateImages(serverRequest('pwg.collections.getImages', {'col_id':typeId0, 'page':crntPage, 'per_page':plugin.getSetting('limit')}))
elif(split[0] == 'recent'):
try:
crntPage = int(split[1])
except:
pass
populateImages(serverRequest('pwg.categories.getImages', {'order':'date_available DESC', 'page':crntPage, 'per_page':plugin.getSetting('limit')}))
elif(split[0] == 'random'):
populateImages(serverRequest('pwg.categories.getImages', {'order':'random', 'per_page':plugin.getSetting('limit')}))
elif(split[0] == 'rated'):
try:
crntPage = int(split[1])
except:
pass
populateImages(serverRequest('pwg.categories.getImages', {'order':'rating_score desc', 'page':crntPage, 'per_page':plugin.getSetting('limit'), 'f_min_rate':0, 'f_max_rate':5}))
elif(split[0] == 'favorites'):
try:
crntPage = int(split[1])
except:
pass
populateImages(serverRequest('pwg.users.favorites.getList', {'page':crntPage, 'per_page':plugin.getSetting('limit')}))
elif(split[0] == 'sync'):
syncServer()
# elif(split[0] == 'views'):
# xbmcgui.Window();
# ui = modifyTags.modifyTagsWindow('piwigoTagDialog.xml' , __cwd__, 'Default')
# ui.doModal()
elif(split[0] == 'search'):
try:
crntPage = int(split[2])
except:
pass
if(crntPage > 0):
populateImages(serverRequest('pwg.images.search', {'query':split[1], 'per_page':plugin.getSetting('limit'), 'page':crntPage}))
else:
keyboard = xbmc.Keyboard('', localize(43118), False)
keyboard.doModal()
if keyboard.isConfirmed() and keyboard.getText() != '':
plugin.path += '/%s' % (keyboard.getText())
populateImages(serverRequest('pwg.images.search', {'query':keyboard.getText(), 'per_page':plugin.getSetting('limit'), 'page':crntPage}))
else:
xbmcgui.Dialog().ok(__addonname__, localize(43113))
else :
home()
else:
serverLogin()
home()