-
Notifications
You must be signed in to change notification settings - Fork 2
/
addon.py
490 lines (389 loc) · 18.6 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# -*- coding: utf-8 -*-
'''
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import os
import xbmcaddon
import xbmcvfs
import github
from github import *
ADDON = xbmcaddon.Addon()
# check if we have allowed testing, this allowes normal users not to stumble across non-working sections
TESTING_ENABLED = ADDON.getSetting('testing_enabled') == 'true'
@kodi.register('main')
def main():
""" Main Menu """
kodi.add_menu_item({'mode': 'search_menu', 'type': "username", 'title': "Search by GitHub Username"}, {'title': "Search by GitHub Username"}, icon='username.png')
kodi.add_menu_item({'mode': 'search_menu', 'type': "repository", 'title': "Search by GitHub Repository Title"}, {'title': "Search by GitHub Repository Title"}, icon='repository.png')
if TESTING_ENABLED:
kodi.add_menu_item({'mode': 'search_menu', 'type': "addonid",'title': "Search by Addon ID"}, {'title': "Search by Addon ID"}, icon='addonid.png')
kodi.add_menu_item({'mode': 'feed_menu'}, {'title': "Search Feeds"}, icon='search_feeds.png')
kodi.add_menu_item({'mode': 'user_list_menu'}, {'title': "Search from list"})
kodi.add_menu_item({'mode': 'installer_menu'}, {'title': "Batch Installers"}, icon='batch_installer.png')
kodi.add_menu_item({'mode': 'settings_menu'}, {'title': "Tools and Settings"}, icon='settings.png')
@kodi.register('search_menu')
def search_menu():
""" Creates search menu """
menu = kodi.context_menu()
menu.add('Search Filter', {"mode": "search_filter"})
kodi.add_menu_item({'mode': 'void'}, {'title': "[COLOR darkorange]%s[/COLOR]" % kodi.arg('title')}, icon='null', menu=menu)
kodi.add_menu_item({'mode': 'search', 'type': kodi.arg('type')}, {'title': "*** New Search ***"}, icon='null', menu=menu)
results = DB.query_assoc("SELECT search_id, query FROM search_history WHERE search_type=? ORDER BY ts DESC LIMIT 25", [kodi.arg('type')], quiet=True)
if results is not None:
for result in results:
menu = kodi.context_menu()
menu.add('Search Filter', {"mode": "search_filter"})
menu.add('Delete from search history', {"mode": "history_delete", "id": result['search_id']})
kodi.add_menu_item({'mode': 'search', 'type': kodi.arg('type'), 'query': result['query']}, {'title': result['query']}, menu=menu, icon='null')
@kodi.register('feed_menu')
def feed_menu():
""" Creates feed menu """
kodi.add_menu_item({'mode': 'install_local_feed'}, {'title': "*** Local Search Feed File ***"}, icon='install_feed_local.png')
#kodi.add_menu_item({'mode': 'search', 'query': 'gitbrowser.feed', 'type': 'addonid'}, {'title': "*** Search for Feeds ***"}, icon='null')
feeds = DB.query_assoc("SELECT feed_id, name, url, enabled FROM feed_subscriptions")
for feed in feeds:
menu = kodi.ContextMenu()
name = feed['name'] if feed['name'] else feed['url']
if not feed['enabled']:
title = "[COLOR darkred]%s[/COLOR]" % name
else: title = name
menu.add('Delete Feed', {"mode": "delete_feed", "title": title, "id": feed['feed_id']})
kodi.add_menu_item({'mode': 'list_feed', 'url': feed['url']}, {'title': title}, menu=menu, icon='null')
@kodi.register('user_list_menu')
def user_list():
"""
Creates user list menu
A list compiled to make users life easier
will only contain legal plugins
"""
menu = kodi.context_menu()
with open( xbmcvfs.translatePath( 'special://home/addons/plugin.git.browser/resources/user_lists.txt' ), 'r', encoding='utf8' ) as users:
if users:
users = users.read().split("\n")
for user in users:
kodi.add_menu_item({'mode': 'search', 'type': 'repository', 'query': str( user )}, {'title': str( user )}, menu=menu, icon='null')
@kodi.register('installer_menu')
def installer_menu():
""" Creates installer menu """
kodi.add_menu_item({'mode': 'browse_local'}, {'title': "*** Install From Local File ***"}, icon='install_batch_local.png')
#kodi.add_menu_item({'mode': 'search', 'query': 'gitbrowser.installer', 'type': 'addonid'}, {'title': "*** Search for Batch Installers ***"}, icon='null')
@kodi.register('settings_menu')
def settings_menu():
""" Creates settings menu """
kodi.add_menu_item({'mode': 'dependency_search'}, {'title': "Search for missing dependencies"}, icon='search_failed.png')
kodi.add_menu_item({'mode': 'update_addons'}, {'title': "Check for Updates [COLOR red](Advanced)[/COLOR]"}, icon='update.png', visible=kodi.get_setting('enable_updates') == 'true')
kodi.add_menu_item({'mode': 'addon_settings'}, {'title': "Addon Settings"}, icon='settings.png')
@kodi.register('dependency_search')
def dependency_search():
results = DB.query("SELECT addon_id FROM failed_depends WHERE resolved=0 ORDER BY addon_id ASC")
if results is not None:
for result in results:
if kodi.has_addon(result[0]):
DB.execute("UPDATE failed_depends SET resolved=1 WHERE addon_id=?", [result[0]])
DB.commit()
continue
kodi.add_menu_item({'mode': 'search', 'type': "addonid",'query': result[0]}, {'title': result[0]}, icon='addonid.png')
@kodi.register('search')
def search():
q = kodi.arg('query') if kodi.arg('query') else kodi.dialog_input('Search GitHub')
if q in [None, False, '']:
return False
DB.execute('REPLACE INTO search_history(search_type, query) VALUES(?,?)', [kodi.arg('type'), q])
DB.commit()
@dispatcher.register('username')
def username():
results = github.search(q, 'user')
if results is None:
return
for i in results['items']:
user = i['owner']['login']
# Lookup newest release zip files for this repo
response = github.find_latest_release_zips(user, i['name'])
if response is not None and response.get('message') is None:
for r in github.sort_results(response['assets']):
url = r['browser_download_url']
menu = kodi.context_menu()
kodi.add_menu_item({'mode': 'github_install', "url": url, "user": user, "file": r['name'], "full_name": "%s/%s" % (user, i['name'])}, {'title': f"{user}/{i['name']}/{r['name']}"}, menu=menu, icon='null')
else:
# Get the complete list of files for the main branch of this repo
response = github.get_repo_filelist(user, i['name'], i['default_branch'])
if response is not None and response.get('tree') is not None:
for r in response['tree']:
if r['path'].endswith('.zip'):
url = github.get_download_url(user + '/' + i['name'], r['path'], i['default_branch'], False)
file_name = os.path.basename(r['path'])
menu = kodi.context_menu()
kodi.add_menu_item({'mode': 'github_install', "url": url, "user": user, "file": file_name, "full_name": "%s/%s" % (user, i['name'])}, {'title': f"{user}/{i['name']}/{file_name}"}, menu=menu, icon='null')
@dispatcher.register('repository')
def repository():
results = github.search(q, 'title')
if results is None:
return
for i in results['items']:
user = i['owner']['login']
# Lookup newest release zip files for this repo
response = github.find_latest_release_zips(user, i['name'])
if response is not None and response.get('message') is None:
for r in github.sort_results(response['assets']):
url = r['browser_download_url']
menu = kodi.context_menu()
kodi.add_menu_item({'mode': 'github_install', "url": url, "user": user, "file": r['name'], "full_name": "%s/%s" % (user, i['name'])}, {'title': f"{user}/{i['name']}/{r['name']}"}, menu=menu, icon='null')
else:
# Get the complete list of files for the main branch of this repo
response = github.get_repo_filelist(user, i['name'], i['default_branch'])
if response is not None and response.get('tree') is not None:
for r in response['tree']:
if r['path'].endswith('.zip'):
url = github.get_download_url(user + '/' + i['name'], r['path'], i['default_branch'], False)
file_name = os.path.basename(r['path'])
menu = kodi.context_menu()
kodi.add_menu_item({'mode': 'github_install', "url": url, "user": user, "file": file_name, "full_name": "%s/%s" % (user, i['name'])}, {'title': f"{user}/{i['name']}/{file_name}"}, menu=menu, icon='null')
@dispatcher.register('addonid')
def addonid():
rtype = 'api'
results = github.search(q, 'id')
if results is None:
return
results.sort(key=lambda x:github.version_sort(x['name']), reverse=True)
for i in results:
menu = kodi.context_menu()
r = i['repository']
full_name = r['full_name']
title = kodi.highlight("%s/%s" % (full_name, i['name']), q, 'yellow')
url = github.get_download_url(full_name, i['path'])
menu.add("Search Username", {'mode': 'search', 'type': 'username', 'query': r['owner']['login']})
kodi.add_menu_item({'mode': 'github_install', "url": url, "file": i['name'], "full_name": full_name}, {'title': title}, menu=menu, icon='null')
dispatcher.run(kodi.arg('type'))
@kodi.register('search_filter', False)
def search_filter():
options = display =['None', 'Repository', 'Feed', 'Music Plugin', 'Video Plugin', 'Script']
filter = kodi.get_property('search.filter')
if filter in options:
index = options.index(filter)
display[index] = kodi.format_color(display[index], 'yellow')
else:
display[0] = kodi.format_color(display[0], 'yellow')
c = kodi.dialog_select("Filter Results by:", display)
if c is not False:
if c == 0:
kodi.set_property('search.filter', '')
else:
kodi.set_property('search.filter', options[c])
@kodi.register(['install_feed', 'install_local_feed'], False)
def install_feed():
if kodi.mode == 'install_feed':
url = kodi.arg('url')
xml = github.install_feed(url)
else:
url = kodi.dialog_browser('Select a feed file',type=kodi.BROWSER_TYPES.FILE, mask='.zip')
if not github.re_feed.search(url):
return
xml = github.install_feed(url, True)
if not kodi.dialog_confirm('Install Feed?', "Click YES to proceed."):
return
try:
for f in xml.findAll('feeds'):
name = f.find('name').text
url = f.find('url').text
DB.execute("INSERT INTO feed_subscriptions(name, url) VALUES(?,?)", [name, url])
DB.commit()
count = DB.query("SELECT count(1) FROM feed_subscriptions")
kodi.set_setting('installed_feeds', str(count[0][0]))
kodi.notify("Install Complete",'Feed Installed')
except Exception:
kodi.notify("Install failed",'Invalid Format.')
def feed_count():
try:
count = DB.query("SELECT count(1) FROM feed_subscriptions")[0][0]
except Exception:
count = 0
return count
@kodi.register(['install_batch', 'browse_local'], False)
def install_batch():
import xbmcgui
if kodi.mode == 'install_batch':
url = kodi.arg('url')
xml, zip_ref = github.batch_installer(url)
else:
url = kodi.dialog_browser(
'Select a install file',
type=kodi.BROWSER_TYPES.FILE,
mask='.zip'
)
if not github.re_installer.search(url):
return
xml, zip_ref = github.batch_installer(url, True)
if not kodi.dialog_confirm(
'Batch Installer?', "Click YES to proceed.", "This will install a list of addons.",
"Some configuration files and settings may be overwritten."
):
return
if not xml:
return
# Install each addon as instructed
installed_list = []
failed_list = []
count = 0
for a in xml.findAll('addon'):
count +=1
PB = kodi.ProgressBar()
PB.new('Batch Installer - Progress', count)
for a in xml.findAll('addon'):
addon_id = a.find('addon_id')
username = a.find('username')
if addon_id is None or username is None:
continue
username = username.text
addon_id = addon_id.text
PB.next(addon_id)
if not kodi.has_addon(addon_id):
if PB.is_canceled():
return
kodi.log("Batch install " + addon_id)
url, filename, full_name, version = github.find_zip(username, addon_id)
if url:
installed_list += github_installer.GitHub_Installer(addon_id, url, full_name, kodi.vfs.join("special://home", "addons"), quiet=True, batch=True, installed_list=installed_list).installed_list
kodi.sleep(1000)
else:
failed_list.append(addon_id)
# Look for config files.
# Need to add error checking for missing config files
configs= xml.find('configs')
if configs is not None and 'dir' in configs.attrs[0]:
config_dir = configs['dir']
for config in configs.findAll('config'):
source = config.find('source')
destination = config.find('destination')
if source is None or destination is None:
continue
source = source.text
destination = destination.text
if not kodi.vfs.exists(destination):
kodi.vfs.mkdir(destination, True)
kodi.vfs.write_file(kodi.vfs.join(destination, source), zip_ref.read(config_dir + '/' + source))
# Now look for individual setting key and value pairs
# Set them as instructed
settings= xml.find('settings')
if settings is not None:
for setting in settings.findAll('setting'):
if 'addon_id' in setting.attrs[0]:
addon_id = setting['addon_id']
k = setting.find('key')
v = setting.find('value')
if k is None or v is None:
continue
kodi.set_setting(k.text, v.text, addon_id)
builtins= xml.find('builtins')
if builtins is not None:
for cmd in builtins.findAll('command'):
cmd = cmd.text
kodi.run_command(cmd)
jsonrpc= xml.find('jsonrpc')
if jsonrpc is not None:
from ast import literal_eval
for cmd in jsonrpc.findAll('command'):
method = cmd.find('method').text
params = literal_eval(cmd.find('params').text)
id = cmd.find('id').text
kodi.kodi_json_request(method, params, id)
# Now clean up
zip_ref.close()
PB.close()
if len(failed_list):
kodi.dialog_ok("Batch Error", "One or more Addons failed to install", "See log for list")
kodi.log("Failed list: %s" % ",".join(failed_list))
r = kodi.dialog_confirm(
kodi.get_name(), 'Click Continue to install more addons or',
'Restart button to finalize addon installation',
yes='Restart', no='Continue'
)
if r:
import sys
import xbmc
if sys.platform in ['linux', 'linux2', 'win32']:
xbmc.executebuiltin('RestartApp')
else:
xbmc.executebuiltin('ShutDown')
@kodi.register('new_feed')
def new_feed():
url = kodi.dialog_input('Feed URL')
if not url:
return
DB.execute("INSERT INTO feed_subscriptions(url) VALUES(?)", [url])
DB.commit()
kodi.refresh()
@kodi.register('delete_feed', False)
def delete_feed():
if not kodi.dialog_confirm('Delete Feed?', kodi.arg('title'), "Click YES to proceed."):
return
DB.execute("DELETE FROM feed_subscriptions WHERE feed_id=?", [kodi.arg('id')])
DB.commit()
kodi.refresh()
@kodi.register('list_feed')
def feed_list():
from commoncore.baseapi import CACHABLE_API, EXPIRE_TIMES
class FeedAPI(CACHABLE_API):
base_url = ''
default_return_type = 'xml'
try:
xml = FeedAPI().request(kodi.arg('url')) #, cache_limit=EXPIRE_TIMES.EIGHTHOURS)
for r in xml.iter('repository'):
name = r.find('name').text
username = r.find('username').text
desc = r.find('description').text
title = "%s: %s" % (name, desc)
kodi.add_menu_item({'mode': 'search', 'type': 'username', 'query': username}, {'title': title, 'plot': desc}, icon='null')
kodi.eod()
except Exception as err_str:
kodi.log(err_str)
@kodi.register('github_install', False)
def github_install():
import re
from github import github_installer
confirmed = kodi.dialog_confirm(
"Confirm Install", kodi.arg('file'),
yes="Install", no="Cancel"
)
if not confirmed:
return
addon_id = re.sub("-[\d\.]+zip$", "", kodi.arg('file'))
github_installer.GitHub_Installer(addon_id, kodi.arg('url'), kodi.arg('full_name'), kodi.vfs.join("special://home", "addons"))
@kodi.register('browse_repository', False)
def browse_repository():
xml = github.browse_repository(kodi.arg('url'))
heading = "%s/%s" % (kodi.arg('full_name'), kodi.arg('file'))
options = []
if xml:
for addon in xml.findAll('addon'):
options.append("%s (%s)" % (addon['name'], addon['version']))
kodi.dialog_select(heading, sorted(options))
@kodi.register('history_delete', False)
def history_delete():
if not kodi.arg('id'):
return
DB.execute("DELETE FROM search_history WHERE search_id=?", [kodi.arg('id')])
DB.commit()
kodi.refresh()
@kodi.register('update_addons', False)
def update_addons():
from github import github_installer
quiet = kodi.arg('quiet') == 'quiet'
if not quiet:
confirmed = kodi.dialog_confirm(
"Confirm Update", "Check for updates",
yes="Update", no="Cancel"
)
if not confirmed:
return
github_installer.update_addons(quiet)
if __name__ == '__main__':
kodi.run()