Advertisement
Guest User

PARADOX WIZARD

a guest
May 27th, 2016
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 32.05 KB | None | 0 0
  1. import xbmc
  2. import xbmcaddon
  3. import xbmcgui
  4. import xbmcplugin
  5. import os
  6. import subprocess
  7. import base64
  8. import sys
  9. import xbmcvfs
  10. import atexit
  11. import requests
  12. import shutil
  13. import urllib
  14. import urllib2
  15. import cookielib
  16. import re
  17. import extract
  18. import downloader
  19. import time
  20. import json
  21. import plugintools
  22. from ConfigParser import SafeConfigParser
  23. from addon.common.addon import Addon
  24. from addon.common.net import Net
  25.  
  26. try:
  27.     from hashlib import sha1
  28. except ImportError:  # python 2.4 compat
  29.     from sha import sha as sha1
  30.  
  31.  
  32. AddonID = 'plugin.video.paradoxwizard'
  33. ADDON = xbmcaddon.Addon(id=AddonID)
  34. VERSION = "1.0.8.5"
  35. ADDONPATH = xbmc.translatePath(
  36.     os.path.join('special://home/addons/' + AddonID))
  37. AddonTitle = "Paradox Wizard"
  38. USER_AGENT = 'Kodi/Paradox Wizard'
  39. U = plugintools.get_setting('username')
  40. P = plugintools.get_setting('password')
  41. M = plugintools.get_setting('submessage')
  42.  
  43. dialog = xbmcgui.Dialog()
  44. net = Net()
  45.  
  46. BASEURL = "http://theblackboxostv.co.uk/"
  47. CHECKURL = BASEURL + "wizard-dev.php"
  48.  
  49. ART = xbmc.translatePath(os.path.join(
  50.     'special://home/addons/' + AddonID + '/resources/art/'))
  51. DBPATH = xbmc.translatePath('special://database')
  52. TNPATH = xbmc.translatePath('special://thumbnails')
  53.  
  54. SKIN =  xbmc.getSkinDir()
  55. USERDATA     =  xbmc.translatePath(os.path.join('special://profile',''))
  56. ADDON_DATA   =  xbmc.translatePath(os.path.join(USERDATA,'addon_data'))
  57. SKINPATH     =  xbmc.translatePath(os.path.join(ADDON_DATA,SKIN))
  58. GUISETTINGS  =  xbmc.translatePath(os.path.join(USERDATA,'guisettings.xml'))
  59. SKINSETTINGS =  xbmc.translatePath(os.path.join(SKINPATH,'settings.xml'))
  60. FAVS         =  xbmc.translatePath(os.path.join(USERDATA,'favourites.xml'))
  61. SOURCE     =  xbmc.translatePath(os.path.join(USERDATA,'sources.xml'))
  62. ADVANCED     =  xbmc.translatePath(os.path.join(USERDATA,'advancedsettings.xml'))
  63. RSS       =  xbmc.translatePath(os.path.join(USERDATA,'RssFeeds.xml'))
  64. KEYMAPS   =  xbmc.translatePath(os.path.join(USERDATA,'keymaps','keyboard.xml'))
  65. ADDONS     =  xbmc.translatePath(os.path.join('special://home','addons'))
  66. USB       = ADDONPATH
  67.  
  68. EXCLUDES = ['plugin.video.paradoxwizard', 'script.module.addon.common',
  69.             'repository.paradox', 'script.module.requests']
  70.  
  71. FANART = ART + 'fanart.png'
  72. ICON = ART + 'icon.png'
  73.  
  74. # set some default icons
  75. INSTALLICON = ART + 'install.png'
  76. MAINTAINANCEICON = ART + 'maintenance.png'
  77. CONTACTICON = ART + 'contact.png'
  78. CLEARCACHEICON = ART + 'clear-cache.png'
  79. FRESHSTARTICON = ART + 'fresh-start.png'
  80. PURGEICON = ART + 'purge.png'
  81. FORCESTOP = ART + 'force-stop.png'
  82. SETTINGSICON = ART + 'settings.png'
  83. THUMBSICON = ART + 'thumbs.png'
  84. BACKUPICON = ART + 'backup.png'
  85. RESTOREICON = ART + 'restore.png'
  86.  
  87. # Grab the mac address encase we need it later!
  88. MAC_ADDRESS = xbmc.getInfoLabel('Network.MacAddress')
  89.  
  90. # Firstrun marker
  91. FIRSTRUN = True
  92.  
  93.  
  94. def DoE(e): xbmc.executebuiltin(e)
  95.  
  96.  
  97. def DoAW(e): xbmc.executebuiltin("ActivateWindow(%s)" % str(e))
  98.  
  99.  
  100. def DoRW(e): xbmc.executebuiltin("ReplaceWindow(%s)" % str(e))
  101.  
  102.  
  103. def DoRA(e): xbmc.executebuiltin("RunAddon(%s)" % str(e))
  104.  
  105.  
  106. def DoRA2(e, e2="1", e3=""): xbmc.executebuiltin(
  107.     'RunAddon(%s,"%s","%s")' % (str(e), str(e2), e3))
  108.  
  109.  
  110. def DoA(a): xbmc.executebuiltin("Action(%s)" % str(a))
  111.  
  112.  
  113. def DoCM(a): xbmc.executebuiltin("Control.Message(windowid=%s)" % (str(a)))
  114.  
  115.  
  116. def DoSC(a): xbmc.executebuiltin("SendClick(%s)" % (str(a)))
  117.  
  118.  
  119. def DoSC2(a, Id): xbmc.executebuiltin("SendClick(%s,%s)" % (str(a), str(Id)))
  120.  
  121.  
  122. def DoStopScript(e): xbmc.executebuiltin("StopScript(%s)" % str(e))
  123.  
  124.  
  125. def DoTD(): xbmc.executebuiltin("ToggleDebug")
  126.  
  127.  
  128. def script_chk(script_name):
  129.     return xbmc.getCondVisibility('System.HasAddon(%s)' % script_name) == 1
  130.  
  131.  
  132. # Anything that needs to be run before the script init's
  133.  
  134.  
  135. def SETUP():
  136.     global INSTALLICON, MAINTAINANCEICON, CONTACTICON, CLEARCACHEICON, FRESHSTARTICON, PURGEICON, SETTINGSICON, M
  137.     # See if we can update the logos used
  138.     # logopath = "http://paradoxwizard.co.uk/icon/paradox-wizard-icons.cfg"
  139.     # path = xbmc.translatePath(os.path.join('special://home/addons','packages/'))
  140.     # downloader.download(logopath, path + "/paradox-wizard-icons.cfg")
  141.     # icons = SafeConfigParser()
  142.     # icons.read(path + "/paradox-wizard-icons.cfg")
  143.     # INSTALLICON        = str(icons.get('icons', 'installicon'))
  144.     # MAINTAINANCEICON  = str(icons.get('icons', 'maintainanceicon'))
  145.     # CONTACTICON        = str(icons.get('icons', 'contacticon'))
  146.     # CLEARCACHEICON      = str(icons.get('icons', 'clearcacheicon'))
  147.     # FRESHSTARTICON      = str(icons.get('icons', 'freshstarticon'))
  148.     # PURGEICON        = str(icons.get('icons', 'purgeicon'))
  149.     # FORCESTOP        = str(icons.get('icons', 'forcestop'))
  150.     # FANART              = str(icons.get('icons', 'fanart'))
  151.  
  152.     # repo_installed = script_chk("repository.paradox")
  153.     # if repo_installed:
  154.     #    plugintools.message(AddonTitle, "Would you like to install the Paradox Repository?")
  155.     #    DoRA("repository.paradox")
  156.  
  157.     if U == "" and P == "" and M == "false":
  158.         msg1 = "Please register an account at http://theblackboxostv.co.uk and enter your forum username and password in the wizard settings panel to continue. "
  159.         msg2 = "Would you like to enter your username and password now?"
  160.         yes_pressed = plugintools.message_yes_no(AddonTitle + " - Authentication", msg1, msg2)
  161.         plugintools.set_setting('submessage', 'true')
  162.         if yes_pressed:
  163.             opensettings()
  164.  
  165.     INDEX()
  166.  
  167.  
  168. # Inital Menu
  169. def INDEX():
  170.  
  171.     addDir('Install Paradox', BASEURL, 2, INSTALLICON, FANART, '')
  172.     addDir('Maintenance', BASEURL, 3, MAINTAINANCEICON, FANART, '')
  173.     addDir('Settings', BASEURL, 15, SETTINGSICON, FANART, '')
  174.     setView('movies', 'MAIN')
  175.  
  176.  
  177. # Build Menu
  178. def BUILDMENU():
  179.  
  180.     data = OPEN_URL(CHECKURL + "?action=listbuilds&user=" + str(U) + "&pass=" + str(smf_hash(P, U)))
  181.     parsed = json.loads(data)
  182.  
  183.     for build in parsed:
  184.         addDir(build['bfriendlyname'] + ' - ' + build['bversion'],build['bslug'], 5, build['bicon'], FANART, '')
  185.         setView('movies', 'MAIN')
  186.  
  187.  
  188. # Maintenance menu
  189. def MAINTENANCE():
  190.     addDir('Purge Packages', 'url', 7, PURGEICON, FANART, 'Delete any downloaded packeages')
  191.     addDir('Clear Cache', 'url', 4, CLEARCACHEICON, FANART, 'Delete Kodis cached files to free up space on your device')
  192.     addDir('Clear Thumbnails', 'url', 16, THUMBSICON, FANART, 'Clear the thumbnail library')
  193.     addDir('Fresh Start', 'url', 6, FRESHSTARTICON, FANART, 'Reset your Kodi to its default settings, this will remove all addons, settings and skins')
  194.     addDir('Backup/Restore', 'url', 17, BACKUPICON, FANART, 'Back Up Your settings.xml')
  195.     addDir('Force Close', 'url', 10, FORCESTOP, FANART, 'Force Kodi to shut down instantly')
  196.     setView('movies', 'MAIN')
  197.  
  198.  
  199. # Install builds
  200. def WIZARD(name, url, description):
  201.  
  202.     whatami = platform()
  203.     whattodo = plugintools.selector(title="Please Select", option_list=[ "View Change Log", "Install " + name])
  204.  
  205.     if whattodo == 0:
  206.  
  207.         burl = CHECKURL + "?action=changelog&devos=" + str(whatami) + "&build=" + str(url) + "&user=" + str(U) + "&pass=" + str(smf_hash(P, U))
  208.  
  209.         data = OPEN_URL(burl)
  210.         parsed = json.loads(data)
  211.         build = str(parsed.get('bfriendlyname'))
  212.         version = str(parsed.get('bversion'))
  213.         cltext = str(parsed.get('bchangelog'))
  214.  
  215.         changelog("Change Log","[COLOR=yellow]" + build + "[/COLOR][CR][CR]" + cltext)
  216.  
  217.     elif whattodo == 1:
  218.         # User has chosen to install the build so fire it up!
  219.         xbmc.executebuiltin("ActivateWindow(busydialog)")
  220.  
  221.         # Check the username and password set in the wizard
  222.         burl = CHECKURL + "?action=getbuild&devos=" + str(whatami) + "&build=" + str(url) + "&user=" + str(U) + "&pass=" + str(smf_hash(P, U))
  223.         data = OPEN_URL(burl)
  224.         parsed = json.loads(data)
  225.         build = str(parsed.get('bfriendlyname'))
  226.         version = str(parsed.get('bversion'))
  227.  
  228.         # See if we have a version file
  229.         versionpath = xbmc.translatePath(os.path.join('special://', 'home'))
  230.         versionfile = versionpath + 'version.txt'
  231.         versionfileexists = os.path.isfile(versionfile)
  232.         parser = SafeConfigParser()
  233.         parser.read(versionfile)
  234.         tempfolder = xbmc.translatePath(
  235.             os.path.join('special://', 'home', 'temp'))
  236.  
  237.         # Removing this as it causes problems for people that get the Kodi screen following install
  238.         #
  239.         # Check the version of the build against the latest available version
  240.         # if versionfileexists and parser.get('versioninfo', 'version') == version and parser.get('versioninfo', 'build') == build:
  241.         #    dialog = xbmcgui.Dialog()
  242.         #    xbmc.executebuiltin("Dialog.Close(busydialog)")
  243.         #    dialog.ok(AddonTitle, "You already have the most recent version", "", str(
  244.         #        parser.get('versioninfo', 'build')) + " " + str(parser.get('versioninfo', 'version')))
  245.         # else:
  246.  
  247.         path = xbmc.translatePath(os.path.join(
  248.             'special://home/addons', 'packages/'))
  249.         fileexists = os.path.isfile(path + url + version + '.zip')
  250.         existingfile = os.path.join(path + url + version + '.zip')
  251.  
  252.         if fileexists:
  253.             lib = existingfile
  254.             dp = xbmcgui.DialogProgress()
  255.             xbmc.executebuiltin("Dialog.Close(busydialog)")
  256.             addonfolder = xbmc.translatePath(
  257.                 os.path.join('special://', 'home'))
  258.             time.sleep(2)
  259.             dp.create(AddonTitle, "Extracting " + name, "Please Wait...")
  260.             extract.all(lib, addonfolder, dp)
  261.             # copytree(tempfolder, addonfolder)
  262.             # shutil.rmtree(tempfolder)
  263.             dp.close()
  264.             ADDON.setSetting(id="username", value="")
  265.             ADDON.setSetting(id="password", value="")
  266.             plugintools.message(AddonTitle, name + " has been installed from your existing packages")
  267.             plugintools.message(AddonTitle, " ", "To save changes you now need to force close Kodi, Press OK to force close Kodi")
  268.             killxbmc()
  269.  
  270.         else:
  271.  
  272.             if parsed.get('auth'):
  273.                 rid = parsed.get('recid')
  274.                 dlurl = parsed.get('bdlurl')
  275.  
  276.                 if parsed.get('brsurl'):
  277.                     dlurl = parsed.get('brsurl')
  278.  
  279.                 dp = xbmcgui.DialogProgress()
  280.                 xbmc.executebuiltin("Dialog.Close(busydialog)")
  281.  
  282.                 # if whatami == "windows":
  283.                 #    FRESHSTARTBUILD(params)
  284.  
  285.                 dp.create(AddonTitle, "Downloading " + parsed.get('bfriendlyname') +
  286.                           " - " + parsed.get('bversion'), "Please Wait...")
  287.                 lib = existingfile
  288.  
  289.                 # added to remove any partially downloaded files
  290.                 try:
  291.                     downloader.download(dlurl, lib, dp)
  292.                 except Exception as e:
  293.                     if str(e) == "Canceled":
  294.                         os.remove(lib)
  295.                     return
  296.  
  297.                 addonfolder = xbmc.translatePath(
  298.                     os.path.join('special://', 'home'))
  299.                 tempfolder = xbmc.translatePath(
  300.                     os.path.join('special://', 'home', 'temp'))
  301.                 time.sleep(2)
  302.                 dp.update(0, "", "Extracting " +
  303.                           parsed.get('bfriendlyname') + " Zip", "Please Wait...")
  304.  
  305.                 extract.all(lib, addonfolder, dp)
  306.                 dp.close()
  307.  
  308.                 successdata = OPEN_URL(CHECKURL + "?action=installed&instid=" + str(rid) + "&user=" + str(U) + "&pass=" + str(smf_hash(P, U)))
  309.                 suceess = json.loads(successdata)
  310.                 plugintools.message(AddonTitle, suceess.get('mtit'), suceess.get('mmsg'))
  311.                 plugintools.message(AddonTitle, "To save changes you now need to force close Kodi, Press OK to force close Kodi")
  312.                 ADDON.setSetting(id="username", value="")
  313.                 ADDON.setSetting(id="password", value="")
  314.                 killxbmc()
  315.  
  316.             else:
  317.                 xbmc.executebuiltin("Dialog.Close(busydialog)")
  318.                 yes_pressed = plugintools.message_yes_no(AddonTitle, parsed.get('etit'), "Do you want to open settings now?")
  319.                 if yes_pressed:
  320.                     opensettings()
  321.  
  322.  
  323. # Open URL (Changed to use urllib2.request)
  324. def OPEN_URL(url):
  325.     headers = {
  326.         'User-Agent': USER_AGENT
  327.     }
  328.     sess = requests.session()
  329.     req = sess.get(url, headers=headers)
  330.     link = req.content
  331.     req.close()
  332.     return link
  333.  
  334.  
  335. # Delete Packages
  336. def DeletePackages(url):
  337.  
  338.     packages_cache_path = xbmc.translatePath(
  339.         os.path.join('special://home/addons/packages', ''))
  340.  
  341.     if plugintools.message_yes_no(AddonTitle, "Are you sure you want to purge all packages?"):
  342.         try:
  343.             for root, dirs, files in os.walk(packages_cache_path):
  344.                 file_count = 0
  345.                 file_count += len(files)
  346.  
  347.                 # Count files and give option to delete
  348.                 if file_count > 0:
  349.  
  350.                     if plugintools.message_yes_no("Delete Package Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
  351.  
  352.                         for f in files:
  353.                             os.unlink(os.path.join(root, f))
  354.                         for d in dirs:
  355.                             shutil.rmtree(os.path.join(root, d))
  356.                         plugintools.message(AddonTitle, "Packages Successfuly Removed")
  357.         except:
  358.             plugintools.message(AddonTitle, "Sorry we were not able to remove Package Files")
  359.     else:
  360.         plugintools.message(AddonTitle, "No packages have been removed")
  361.  
  362.  
  363. # Delete Cache
  364. def deletecachefiles(url):
  365.  
  366.     xbmc_cache_path = os.path.join(
  367.         xbmc.translatePath('special://home'), 'cache')
  368.  
  369.     if plugintools.message_yes_no("Clear Cache", "Are you sure you want to clear the cache?"):
  370.         if os.path.exists(xbmc_cache_path) == True:
  371.             for root, dirs, files in os.walk(xbmc_cache_path):
  372.                 file_count = 0
  373.                 file_count += len(files)
  374.  
  375.             # Count files and give option to delete
  376.                 if file_count > 0:
  377.  
  378.                     dialog = xbmcgui.Dialog()
  379.                     if dialog.yesno("Delete Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
  380.  
  381.                         for f in files:
  382.                             try:
  383.                                 os.unlink(os.path.join(root, f))
  384.                             except:
  385.                                 pass
  386.                         for d in dirs:
  387.                             try:
  388.                                 shutil.rmtree(os.path.join(root, d))
  389.                             except:
  390.                                 pass
  391.  
  392.                 else:
  393.                     pass
  394.         if xbmc.getCondVisibility('system.platform.ATV2'):
  395.             atv2_cache_a = os.path.join(
  396.                 '/private/var/mobile/Library/Caches/AppleTV/Video/', 'Other')
  397.  
  398.             for root, dirs, files in os.walk(atv2_cache_a):
  399.                 file_count = 0
  400.                 file_count += len(files)
  401.  
  402.                 if file_count > 0:
  403.  
  404.                     dialog = xbmcgui.Dialog()
  405.                     if dialog.yesno("Delete ATV2 Cache Files", str(file_count) + " files found in 'Other'", "Do you want to delete them?"):
  406.  
  407.                         for f in files:
  408.                             os.unlink(os.path.join(root, f))
  409.                         for d in dirs:
  410.                             shutil.rmtree(os.path.join(root, d))
  411.  
  412.                 else:
  413.                     pass
  414.             atv2_cache_b = os.path.join(
  415.                 '/private/var/mobile/Library/Caches/AppleTV/Video/', 'LocalAndRental')
  416.  
  417.             for root, dirs, files in os.walk(atv2_cache_b):
  418.                 file_count = 0
  419.                 file_count += len(files)
  420.  
  421.                 if file_count > 0:
  422.  
  423.                     dialog = xbmcgui.Dialog()
  424.                     if dialog.yesno("Delete ATV2 Cache Files", str(file_count) + " files found in 'LocalAndRental'", "Do you want to delete them?"):
  425.  
  426.                         for f in files:
  427.                             os.unlink(os.path.join(root, f))
  428.                         for d in dirs:
  429.                             shutil.rmtree(os.path.join(root, d))
  430.  
  431.                 else:
  432.                     pass
  433.                   # Set path to Cydia Archives cache files
  434.         # Set path to What th Furk cache files
  435.         wtf_cache_path = os.path.join(xbmc.translatePath(
  436.             'special://profile/addon_data/plugin.video.whatthefurk/cache'), '')
  437.         if os.path.exists(wtf_cache_path) == True:
  438.             for root, dirs, files in os.walk(wtf_cache_path):
  439.                 file_count = 0
  440.                 file_count += len(files)
  441.  
  442.             # Count files and give option to delete
  443.                 if file_count > 0:
  444.  
  445.                     dialog = xbmcgui.Dialog()
  446.                     if dialog.yesno("Delete WTF Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
  447.  
  448.                         for f in files:
  449.                             os.unlink(os.path.join(root, f))
  450.                         for d in dirs:
  451.                             shutil.rmtree(os.path.join(root, d))
  452.  
  453.                 else:
  454.                     pass
  455.  
  456.                     # Set path to 4oD cache files
  457.         channel4_cache_path = os.path.join(xbmc.translatePath(
  458.             'special://profile/addon_data/plugin.video.4od/cache'), '')
  459.         if os.path.exists(channel4_cache_path) == True:
  460.             for root, dirs, files in os.walk(channel4_cache_path):
  461.                 file_count = 0
  462.                 file_count += len(files)
  463.  
  464.             # Count files and give option to delete
  465.                 if file_count > 0:
  466.  
  467.                     dialog = xbmcgui.Dialog()
  468.                     if dialog.yesno("Delete 4oD Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
  469.  
  470.                         for f in files:
  471.                             os.unlink(os.path.join(root, f))
  472.                         for d in dirs:
  473.                             shutil.rmtree(os.path.join(root, d))
  474.  
  475.                 else:
  476.                     pass
  477.  
  478.                     # Set path to BBC iPlayer cache files
  479.         iplayer_cache_path = os.path.join(xbmc.translatePath(
  480.             'special://profile/addon_data/plugin.video.iplayer/iplayer_http_cache'), '')
  481.         if os.path.exists(iplayer_cache_path) == True:
  482.             for root, dirs, files in os.walk(iplayer_cache_path):
  483.                 file_count = 0
  484.                 file_count += len(files)
  485.  
  486.             # Count files and give option to delete
  487.                 if file_count > 0:
  488.  
  489.                     dialog = xbmcgui.Dialog()
  490.                     if dialog.yesno("Delete BBC iPlayer Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
  491.  
  492.                         for f in files:
  493.                             os.unlink(os.path.join(root, f))
  494.                         for d in dirs:
  495.                             shutil.rmtree(os.path.join(root, d))
  496.  
  497.                 else:
  498.                     pass
  499.  
  500.                     # Set path to Simple Downloader cache files
  501.         downloader_cache_path = os.path.join(xbmc.translatePath(
  502.             'special://profile/addon_data/script.module.simple.downloader'), '')
  503.         if os.path.exists(downloader_cache_path) == True:
  504.             for root, dirs, files in os.walk(downloader_cache_path):
  505.                 file_count = 0
  506.                 file_count += len(files)
  507.  
  508.             # Count files and give option to delete
  509.                 if file_count > 0:
  510.  
  511.                     dialog = xbmcgui.Dialog()
  512.                     if dialog.yesno("Delete Simple Downloader Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
  513.  
  514.                         for f in files:
  515.                             os.unlink(os.path.join(root, f))
  516.                         for d in dirs:
  517.                             shutil.rmtree(os.path.join(root, d))
  518.  
  519.                 else:
  520.                     pass
  521.  
  522.                     # Set path to ITV cache files
  523.         itv_cache_path = os.path.join(xbmc.translatePath(
  524.             'special://profile/addon_data/plugin.video.itv/Images'), '')
  525.         if os.path.exists(itv_cache_path) == True:
  526.             for root, dirs, files in os.walk(itv_cache_path):
  527.                 file_count = 0
  528.                 file_count += len(files)
  529.  
  530.             # Count files and give option to delete
  531.                 if file_count > 0:
  532.  
  533.                     dialog = xbmcgui.Dialog()
  534.                     if dialog.yesno("Delete ITV Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
  535.  
  536.                         for f in files:
  537.                             os.unlink(os.path.join(root, f))
  538.                         for d in dirs:
  539.                             shutil.rmtree(os.path.join(root, d))
  540.  
  541.                 else:
  542.                     pass
  543.  
  544.                     # Set path to temp cache files
  545.         temp_cache_path = os.path.join(
  546.             xbmc.translatePath('special://home/temp'), '')
  547.         if os.path.exists(temp_cache_path) == True:
  548.             for root, dirs, files in os.walk(temp_cache_path):
  549.                 file_count = 0
  550.                 file_count += len(files)
  551.  
  552.             # Count files and give option to delete
  553.                 if file_count > 0:
  554.  
  555.                     dialog = xbmcgui.Dialog()
  556.                     if dialog.yesno("Delete TEMP dir Cache Files", str(file_count) + " files found", "Do you want to delete them?"):
  557.  
  558.                         for f in files:
  559.                             os.unlink(os.path.join(root, f))
  560.                         for d in dirs:
  561.                             shutil.rmtree(os.path.join(root, d))
  562.  
  563.                 else:
  564.                     pass
  565.         plugintools.message(AddonTitle, "All Cache Files Removed")
  566.  
  567.     else:
  568.         plugintools.message(AddonTitle, "No files have been removed")
  569.  
  570.  
  571. # Delete thumbnails
  572. def deleteThumbnails(url):
  573.  
  574.     if plugintools.message_yes_no(AddonTitle, "Are you sure you want to delete all thumbnails?"):
  575.         if os.path.exists(TNPATH) == True:
  576.             for root, dirs, files in os.walk(TNPATH):
  577.                 file_count = 0
  578.                 file_count += len(files)
  579.                 if file_count > 0:
  580.                     for f in files:
  581.                         try:
  582.                             os.unlink(os.path.join(root, f))
  583.                         except:
  584.                             pass
  585.             plugintools.message(AddonTitle, " All Thumbnails Removed","Please restart Kodi to rebuild thumbnail library")
  586.     else:
  587.         plugintools.message(AddonTitle, "No thumbnails have been romoved")
  588.  
  589.  
  590. # Kill Kodi
  591. def killxbmc():
  592.     choice = plugintools.message_yes_no('Force Close Kodi', 'You are about to close Kodi','Would you like to continue?')
  593.     if choice == 0:
  594.         return
  595.     elif choice == 1:
  596.         pass
  597.     myplatform = platform()
  598.     print "Platform: " + str(myplatform)
  599.  
  600.     try:
  601.         os._exit(1)
  602.     except:
  603.         pass
  604.  
  605.     if myplatform == 'osx':  # OSX
  606.         print "############   try osx force close  #################"
  607.         try:
  608.             os.system('killall -9 XBMC')
  609.         except:
  610.             pass
  611.         try:
  612.             os.system('killall -9 Kodi')
  613.         except:
  614.             pass
  615.         plugintools.message(AddonTitle, "If you\'re seeing this message it means the force close","was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.", '')
  616.     elif myplatform == 'linux':  # Linux
  617.         print "############   try linux force close  #################"
  618.         try:
  619.             os.system('killall XBMC')
  620.         except:
  621.             pass
  622.         try:
  623.             os.system('killall Kodi')
  624.         except:
  625.             pass
  626.         try:
  627.             os.system('killall -9 xbmc.bin')
  628.         except:
  629.             pass
  630.         try:
  631.             os.system('killall -9 kodi.bin')
  632.         except:
  633.             pass
  634.         plugintools.message(AddonTitle, "If you\'re seeing this message it means the force close","was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.", '')
  635.     elif myplatform == 'android':  # Android
  636.  
  637.         print "############   try android force close  #################"
  638.  
  639.         try:
  640.             os._exit(1)
  641.         except:
  642.             pass
  643.         try:
  644.             os.system('adb shell am force-stop org.xbmc.kodi')
  645.         except:
  646.             pass
  647.         try:
  648.             os.system('adb shell am force-stop org.kodi')
  649.         except:
  650.             pass
  651.         try:
  652.             os.system('adb shell am force-stop org.xbmc.xbmc')
  653.         except:
  654.             pass
  655.         try:
  656.             os.system('adb shell am force-stop org.xbmc')
  657.         except:
  658.             pass
  659.         try:
  660.             os.system('adb shell am force-stop com.semperpax.spmc16')
  661.         except:
  662.             pass
  663.         try:
  664.             os.system('adb shell am force-stop com.spmc16')
  665.         except:
  666.             pass
  667.         time.sleep(5)
  668.         plugintools.message(AddonTitle,"Press the HOME button on your remote and [COLOR=red][b]FORCE STOP[/b][/COLOR] KODI via the Manage Installed Applications menu in settings on your Amazon home page then re-launch KODI")
  669.     elif myplatform == 'windows':  # Windows
  670.         print "############   try windows force close  #################"
  671.         try:
  672.             os.system('@ECHO off')
  673.             os.system('tskill XBMC.exe')
  674.         except:
  675.             pass
  676.         try:
  677.             os.system('@ECHO off')
  678.             os.system('tskill Kodi.exe')
  679.         except:
  680.             pass
  681.         try:
  682.             os.system('@ECHO off')
  683.             os.system('TASKKILL /im Kodi.exe /f')
  684.         except:
  685.             pass
  686.         try:
  687.             os.system('@ECHO off')
  688.             os.system('TASKKILL /im XBMC.exe /f')
  689.         except:
  690.             pass
  691.         plugintools.message(AddonTitle, "If you\'re seeing this message it means the force close","was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.", "Use task manager and NOT ALT F4")
  692.     else:  # ATV
  693.         print "############   try atv force close  #################"
  694.         try:
  695.             os.system('killall AppleTV')
  696.         except:
  697.             pass
  698.         print "############   try raspbmc force close  #################"  # OSMC / Raspbmc
  699.         try:
  700.             os.system('sudo initctl stop kodi')
  701.         except:
  702.             pass
  703.         try:
  704.             os.system('sudo initctl stop xbmc')
  705.         except:
  706.             pass
  707.         plugintools.message(AddonTitle, "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit via the menu.","iOS detected.  Press and hold both the Sleep/Wake and Home button for at least 10 seconds, until you see the Apple logo.")
  708.  
  709.  
  710. # Get Current platform
  711. def platform():
  712.     if xbmc.getCondVisibility('system.platform.android'):
  713.         return 'android'
  714.     elif xbmc.getCondVisibility('system.platform.linux'):
  715.         return 'linux'
  716.     elif xbmc.getCondVisibility('system.platform.windows'):
  717.         return 'windows'
  718.     elif xbmc.getCondVisibility('system.platform.osx'):
  719.         return 'osx'
  720.     elif xbmc.getCondVisibility('system.platform.atv2'):
  721.         return 'atv2'
  722.     elif xbmc.getCondVisibility('system.platform.ios'):
  723.         return 'ios'
  724.  
  725.  
  726. # Fresh start
  727. def FRESHSTART(params):
  728.     plugintools.log("freshstart.main_list " + repr(params))
  729.     yes_pressed = plugintools.message_yes_no(AddonTitle, "Do you wish to restore your", "Kodi configuration to default settings?")
  730.     if yes_pressed:
  731.         addonPath = xbmcaddon.Addon(id=AddonID).getAddonInfo('path')
  732.         addonPath = xbmc.translatePath(addonPath)
  733.         xbmcPath = os.path.join(addonPath, "..", "..")
  734.         xbmcPath = os.path.abspath(xbmcPath)
  735.         plugintools.log("freshstart.main_list xbmcPath=" + xbmcPath)
  736.         failed = False
  737.         try:
  738.             for root, dirs, files in os.walk(xbmcPath, topdown=True):
  739.                 dirs[:] = [d for d in dirs if d not in EXCLUDES]
  740.                 for name in files:
  741.                     try:
  742.                         os.remove(os.path.join(root, name))
  743.                     except:
  744.                         if name not in ["Addons15.db", "MyVideos75.db", "Textures13.db", "xbmc.log"]:
  745.                             failed = True
  746.                         plugintools.log("Error removing " + root + " " + name)
  747.                 for name in dirs:
  748.                     try:
  749.                         os.rmdir(os.path.join(root, name))
  750.                     except:
  751.                         if name not in ["Database", "userdata"]:
  752.                             failed = True
  753.                         plugintools.log("Error removing " + root + " " + name)
  754.             if not failed:
  755.                 plugintools.log("freshstart.main_list All user files removed, you now have a clean install")
  756.                 plugintools.message(AddonTitle, "The process is complete", "click OK to begin clean installation")
  757.             else:
  758.                 plugintools.log("freshstart.main_list User files partially removed")
  759.                 plugintools.message(AddonTitle, "The process is complete", "click OK to begin clean installation")
  760.         except:
  761.             plugintools.message(AddonTitle, "Problem found","Your settings has not been changed")
  762.             import traceback
  763.             plugintools.log(traceback.format_exc())
  764.             plugintools.log("freshstart.main_list NOT removed")
  765.  
  766.         force_close = plugintools.message_yes_no(AddonTitle, "To complete the fresh start, you need to force close Kodi", "Do you want to force close now?")
  767.         if force_close:
  768.             killxbmc()
  769.  
  770.     else:
  771.         plugintools.message(AddonTitle, "Your settings have not been changed")
  772.         plugintools.add_item(action="", title="Done", folder=False)
  773.  
  774.  
  775. # Fix bad zip files
  776. def fixBadZipfile(zipFile):
  777.     f = open(zipFile, 'r+b')
  778.     data = f.read()
  779.     pos = data.find('\x50\x4b\x05\x06')  # End of central directory signature
  780.     if (pos > 0):
  781.         print "Trancating file at location " + str(pos + 22) + "."
  782.         f.seek(pos + 22)   # size of 'ZIP end of central directory record'
  783.         f.truncate()
  784.         f.close()
  785.     else:
  786.         pass
  787.         # raise error, file is truncated
  788.  
  789.  
  790. # SMF Password Hashing
  791. def smf_hash(password, username):
  792.     """
  793.     Python implementation of the smf check hash function
  794.     """
  795.     return sha1(username.lower().encode('utf8') + password).hexdigest()
  796.  
  797.  
  798. # Set a function to open settings for reusability
  799. def opensettings():
  800.     plugintools.open_settings_dialog()
  801.  
  802.  
  803. # Copy directories from one laction to another
  804. def copytree(src, dst, symlinks=False, ignore=None):
  805.     if not os.path.exists(dst):
  806.         os.makedirs(dst)
  807.     for item in os.listdir(src):
  808.         s = os.path.join(src, item)
  809.         d = os.path.join(dst, item)
  810.         if os.path.isdir(s):
  811.             copytree(s, d, symlinks, ignore)
  812.         else:
  813.             if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1:
  814.                 shutil.copy2(s, d)
  815.  
  816.  
  817. # Popup script
  818. def TextBoxes(heading, announce):
  819.     class TextBox():
  820.         WINDOW = 10147
  821.         CONTROL_LABEL = 1
  822.         CONTROL_TEXTBOX = 5
  823.  
  824.         def __init__(self, *args, **kwargs):
  825.             # activate the text viewer window
  826.             xbmc.executebuiltin("ActivateWindow(%d)" % (self.WINDOW, ))
  827.             self.win = xbmcgui.Window(self.WINDOW)  # get window
  828.             xbmc.sleep(500)  # give window time to initialize
  829.             self.setControls()
  830.  
  831.         def setControls(self):
  832.             self.win.getControl(self.CONTROL_LABEL).setLabel(
  833.                 heading)  # set heading
  834.             try:
  835.                 f = open(announce)
  836.                 text = f.read()
  837.             except:
  838.                 text = announce
  839.             self.win.getControl(self.CONTROL_TEXTBOX).setText(str(text))
  840.             return
  841.     TextBox()
  842.  
  843.  
  844. # About us text
  845. def changelog(cltitle, cltext):
  846.     TextBoxes(cltitle, cltext)
  847.  
  848.  
  849. # Get params
  850. def get_params():
  851.     param = []
  852.     paramstring = sys.argv[2]
  853.     if len(paramstring) >= 2:
  854.         params = sys.argv[2]
  855.         cleanedparams = params.replace('?', '')
  856.         if (params[len(params) - 1] == '/'):
  857.             params = params[0:len(params) - 2]
  858.         pairsofparams = cleanedparams.split('&')
  859.         param = {}
  860.         for i in range(len(pairsofparams)):
  861.             splitparams = {}
  862.             splitparams = pairsofparams[i].split('=')
  863.             if (len(splitparams)) == 2:
  864.                 param[splitparams[0]] = splitparams[1]
  865.  
  866.         return param
  867.  
  868.  
  869. def backup_restore():
  870.  
  871.     whattodo = plugintools.selector(title="Please Select", option_list=[ "Backup Settings", "Restore Settings"])
  872.  
  873.     if whattodo == 0:
  874.         backup_xml()
  875.  
  876.     elif whattodo == 1:
  877.         restore_xml()
  878.  
  879.  
  880.  
  881. def backup_xml():
  882.  
  883.     xbmc.executebuiltin("ActivateWindow(busydialog)")
  884.     #GUISETTINGS
  885.     TO_READ   = open(GUISETTINGS).read()
  886.     TO_WRITE  = os.path.join(USB,"guisettings.xml")
  887.     f = open(TO_WRITE, mode='w')
  888.     f.write(TO_READ)
  889.  
  890.     #SKINSETTINGS
  891.     # TO_READ   = open(SKINSETTINGS).read()
  892.     # TO_WRITE  = os.path.join(USB,"settings.xml")
  893.     # f = open(TO_WRITE, mode='w')
  894.     # f.write(TO_READ)
  895.     f.close()
  896.     xbmc.executebuiltin("Dialog.Close(busydialog)")
  897.     plugintools.message(AddonTitle, "Guisettings.xml Backup Completed,")
  898.  
  899.  
  900.  
  901. def restore_xml():
  902.  
  903.     # if 'settings.xml' in description:
  904.     #    a = open(os.path.join(USB,description.split('Your ')[1])).read()
  905.     #
  906.     #    r='<setting id="%s.(.+?)" type="(.+?)">(.+?)</setting>'% SKIN
  907.     #    #<setting id="skin.confluence.HomeMusicButton4" type="string"></setting>
  908.     #
  909.     #    match=re.compile(r).findall(a)
  910.     #    plugintools.log("### Found Matches ##")
  911.     #    for string,type,setting in match:
  912.     #        plugintools.log(type)
  913.     #        setting=setting.replace('&quot;','') .replace('&amp;','&')
  914.     #        xbmc.executebuiltin("Skin.Set%s(%s,%s)"%(type.title(),string,setting))
  915.     # else:
  916.  
  917.     #GUISETTINGS
  918.     xbmc.executebuiltin("ActivateWindow(busydialog)")
  919.     TO_WRITE   = os.path.join(GUISETTINGS)
  920.     TO_READ  = open(os.path.join(USB,"guisettings.xml")).read()
  921.     f = open(TO_WRITE, mode='w')
  922.     f.write(TO_READ)
  923.  
  924.     #SKINSETTINGS
  925.     # TO_WRITE   = os.path.join(SKINSETTINGS)
  926.     # TO_READ  = open(os.path.join(USB,"settings.xml")).read()
  927.     # f = open(TO_WRITE, mode='w')
  928.     # f.write(TO_READ)
  929.  
  930.     f.close()
  931.  
  932.     xbmc.executebuiltin('UnloadSkin()')
  933.     xbmc.executebuiltin('ReloadSkin()')
  934.  
  935.     xbmc.executebuiltin("Dialog.Close(busydialog)")
  936.     plugintools.message(AddonTitle, "Guisettings.xml Restore Completed,")
  937.  
  938.  
  939.  
  940. N = base64.decodestring('')
  941. T = base64.decodestring('L2FkZG9ucy50eHQ=')
  942. b = base64.decodestring('')
  943. F = base64.decodestring('')
  944.  
  945. # Add directory
  946. def addDir(name, url, mode, iconimage, fanart, description):
  947.     u = sys.argv[0] + "?url=" + urllib.quote_plus(url) + "&mode=" + str(mode) + "&name=" + urllib.quote_plus(
  948.         name) + "&iconimage=" + urllib.quote_plus(iconimage) + "&fanart=" + urllib.quote_plus(fanart) + "&description=" + urllib.quote_plus(description)
  949.     ok = True
  950.     liz = xbmcgui.ListItem(
  951.         name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
  952.     liz.setInfo(type="Video", infoLabels={"Title": name, "Plot": description})
  953.     liz.setProperty("Fanart_Image", fanart)
  954.     if (mode == 5) or (mode == 15) or (mode == 16) or (mode == 10) or (mode == 4) or (mode == 6) or (mode == 7) or (mode == 17) or (mode == 18):
  955.         ok = xbmcplugin.addDirectoryItem(handle=int(
  956.             sys.argv[1]), url=u, listitem=liz, isFolder=False)
  957.     else:
  958.         ok = xbmcplugin.addDirectoryItem(handle=int(
  959.             sys.argv[1]), url=u, listitem=liz, isFolder=True)
  960.     return ok
  961.  
  962.  
  963. params = get_params()
  964. url = None
  965. name = None
  966. mode = None
  967. iconimage = None
  968. fanart = None
  969. description = None
  970.  
  971.  
  972. try:
  973.     url = urllib.unquote_plus(params["url"])
  974. except:
  975.     pass
  976. try:
  977.     name = urllib.unquote_plus(params["name"])
  978. except:
  979.     pass
  980. try:
  981.     iconimage = urllib.unquote_plus(params["iconimage"])
  982. except:
  983.     pass
  984. try:
  985.     mode = int(params["mode"])
  986. except:
  987.     pass
  988. try:
  989.     fanart = urllib.unquote_plus(params["fanart"])
  990. except:
  991.     pass
  992. try:
  993.     description = urllib.unquote_plus(params["description"])
  994. except:
  995.     pass
  996.  
  997. # Set the current window view
  998.  
  999.  
  1000. def setView(content, viewType):
  1001.     # set content type so library shows more views and info
  1002.     if content:
  1003.         xbmcplugin.setContent(int(sys.argv[1]), content)
  1004.     if ADDON.getSetting('auto-view') == 'true':
  1005.         xbmc.executebuiltin("Container.SetViewMode(%s)" %
  1006.                             ADDON.getSetting(viewType))
  1007.  
  1008.  
  1009. if mode == None or url == None or len(url) < 1:
  1010.     SETUP()
  1011. elif mode == 2:
  1012.     BUILDMENU()
  1013. elif mode == 3:
  1014.     MAINTENANCE()
  1015. elif mode == 4:
  1016.     deletecachefiles(url)
  1017. elif mode == 5:
  1018.     WIZARD(name, url, description)
  1019. elif mode == 6:
  1020.     FRESHSTART(params)
  1021. elif mode == 7:
  1022.     DeletePackages(url)
  1023. elif mode == 8:
  1024.     facebook()
  1025. elif mode == 9:
  1026.     donation()
  1027. elif mode == 10:
  1028.     killxbmc()
  1029. elif mode == 11:
  1030.     DELETEIVUEDB()
  1031. elif mode == 15:
  1032.     opensettings()
  1033. elif mode == 16:
  1034.     deleteThumbnails(url)
  1035. elif mode == 17:
  1036.     backup_restore()
  1037. elif mode == 18:
  1038.     restore_xml(name,url,description)
  1039.  
  1040. xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1041. Exit status: 0
  1042. logout
  1043. Saving session...
  1044. ...copying shared history...
  1045. ...saving history...truncating history files...
  1046. ...completed.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement