def send_email(TOWHO,LOG):
PASSWORD=EmailPass()
dp = xbmcgui.DialogProgress()
dp.create(".Kodi Log Emailer",'Logging Into Your Email')
dp.update(0)
THESMTP ,THEPORT = Servers()
fromaddr=ADDON.getSetting('email')
if TOWHO =='ME':
toaddr=fromaddr
else:
toaddr=getOther()
if toaddr =='[COLOR red]Cancel[/COLOR]':
Show_Dialog('No Email Sent','','Email Cancelled')
else:
import datetime
TODAY=datetime.datetime.today().strftime('[%d-%m-%Y %H:%M]')
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
fromaddr = '"Hi Message From Yourself" <%s>'% (fromaddr)
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Your Kodi Log "+str(TODAY)
body = open(THEHTML).read()
content = MIMEText(body, 'html')
msg.attach(content)
try:filename = LOG.rsplit('\\', 1)[1]
except:filename = LOG.rsplit('/', 1)[1]
f = file(LOG)
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename=filename.replace('log','txt'))
msg.attach(attachment)
import smtplib
server = smtplib.SMTP(str(THESMTP), int(THEPORT))
dp.update(50, 'Attaching Your Email',filename.replace('log','txt'))
server.ehlo()
server.starttls()
server.ehlo()
try:server.login(ADDON.getSetting('email').encode('UTF-8'),PASSWORD.encode('UTF-8'))
except Exception as e:
if 'gmail' in THESMTP:
if '/answer/787' in str(e):
e=getMessage()
return showText('[COLOR red]ERROR !![/COLOR]',str(e).replace('\\n','[CR]'))
text = msg.as_string()
dp.update(75, 'Sending........',filename.replace('log','txt'))
server.sendmail(fromaddr, toaddr, text)
dp.close()
Show_Dialog('Email Sent To','[COLOR green]'+toaddr+'[/COLOR]','Also Check Junk Folder')
python类DialogProgress()的实例源码
def add_movie(self, title, alt_title, year, video_id, build_url):
"""Adds a movie to the local db, generates & persists the strm file
Parameters
----------
title : :obj:`str`
Title of the show
alt_title : :obj:`str`
Alternative title given by the user
year : :obj:`int`
Release year of the show
video_id : :obj:`str`
ID of the video to be played
build_url : :obj:`fn`
Function to generate the stream url
"""
title = re.sub(r'[?|$|!|:|#]', r'', title)
movie_meta = '%s (%d)' % (title, year)
folder = re.sub(r'[?|$|!|:|#]', r'', alt_title)
dirname = self.kodi_helper.check_folder_path(
path=os.path.join(self.movie_path, folder))
filename = os.path.join(dirname, movie_meta + '.strm')
progress = xbmcgui.DialogProgress()
progress.create(self.kodi_helper.get_local_string(650), movie_meta)
if xbmcvfs.exists(filename):
return
if not xbmcvfs.exists(dirname):
xbmcvfs.mkdirs(dirname)
if self.movie_exists(title=title, year=year) is False:
progress.update(50)
time.sleep(0.5)
self.db[self.movies_label][movie_meta] = {'alt_title': alt_title}
self._update_local_db(filename=self.db_filepath, db=self.db)
url = build_url({'action': 'play_video', 'video_id': video_id})
self.write_strm_file(path=filename, url=url, title_player=movie_meta)
progress.update(100)
time.sleep(1)
progress.close()
def add_show(self, title, alt_title, episodes, build_url):
"""Adds a show to the local db, generates & persists the strm files
Note: Can also used to store complete seasons or single episodes,
it all depends on what is present in the episodes dictionary
Parameters
----------
title : :obj:`str`
Title of the show
alt_title : :obj:`str`
Alternative title given by the user
episodes : :obj:`dict` of :obj:`dict`
Episodes that need to be added
build_url : :obj:`fn`
Function to generate the stream url
"""
title = re.sub(r'[?|$|!|:|#]', r'', title)
show_meta = '%s' % (title)
folder = re.sub(r'[?|$|!|:|#]', r'', alt_title.encode('utf-8'))
show_dir = self.kodi_helper.check_folder_path(
path=os.path.join(self.tvshow_path, folder))
progress = xbmcgui.DialogProgress()
progress.create(self.kodi_helper.get_local_string(650), show_meta)
count = 1
if not xbmcvfs.exists(show_dir):
xbmcvfs.mkdirs(show_dir)
if self.show_exists(title) is False:
self.db[self.series_label][show_meta] = {
'seasons': [],
'episodes': [],
'alt_title': alt_title}
episode_count_total = len(episodes)
step = round(100.0 / episode_count_total, 1)
percent = step
for episode in episodes:
desc = self.kodi_helper.get_local_string(20373) + ': '
desc += str(episode.get('season'))
long_desc = self.kodi_helper.get_local_string(20359) + ': '
long_desc += str(episode.get('episode'))
progress.update(
percent=int(percent),
line1=show_meta,
line2=desc,
line3=long_desc)
self._add_episode(
show_dir=show_dir,
title=title,
season=episode.get('season'),
episode=episode.get('episode'),
video_id=episode.get('id'),
build_url=build_url)
percent += step
time.sleep(0.05)
self._update_local_db(filename=self.db_filepath, db=self.db)
time.sleep(1)
progress.close()
return show_dir
def remove_show(self, title):
"""Removes the DB entry & the strm files for the show given
Parameters
----------
title : :obj:`str`
Title of the show
Returns
-------
bool
Delete successfull
"""
title = re.sub(r'[?|$|!|:|#]', r'', title)
label = self.series_label
rep_str = self.db[label][title]['alt_title'].encode('utf-8')
folder = re.sub(
pattern=r'[?|$|!|:|#]',
repl=r'',
string=rep_str)
progress = xbmcgui.DialogProgress()
progress.create(self.kodi_helper.get_local_string(1210), title)
time.sleep(0.5)
del self.db[self.series_label][title]
self._update_local_db(filename=self.db_filepath, db=self.db)
show_dir = self.kodi_helper.check_folder_path(
path=os.path.join(self.tvshow_path, folder))
if xbmcvfs.exists(show_dir):
show_files = xbmcvfs.listdir(show_dir)[1]
episode_count_total = len(show_files)
step = round(100.0 / episode_count_total, 1)
percent = 100 - step
for filename in show_files:
progress.update(int(percent))
xbmcvfs.delete(os.path.join(show_dir, filename))
percent = percent - step
time.sleep(0.05)
xbmcvfs.rmdir(show_dir)
return True
return False
time.sleep(1)
progress.close()
def download_and_play(url,file_name,download_path):
# Lanza thread
logger.info("Active threads "+str(threading.active_count()))
logger.info(""+repr(threading.enumerate()))
logger.info("Starting download thread...")
download_thread = DownloadThread(url,file_name,download_path)
download_thread.start()
logger.info("Download thread started")
logger.info("Active threads "+str(threading.active_count()))
logger.info(""+repr(threading.enumerate()))
# Espera
logger.info("Waiting...")
while True:
cancelled=False
dialog = xbmcgui.DialogProgress()
dialog.create('Descargando...', 'Cierra esta ventana para empezar la reproducción')
dialog.update(0)
while not cancelled and download_thread.isAlive():
dialog.update( download_thread.get_progress() , "Cancela esta ventana para empezar la reproducción", "Velocidad: "+str(int(download_thread.get_speed()/1024))+" KB/s "+str(download_thread.get_actual_size())+"MB de "+str(download_thread.get_total_size())+"MB" , "Tiempo restante: "+str( downloadtools.sec_to_hms(download_thread.get_remaining_time())) )
xbmc.sleep(1000)
if dialog.iscanceled():
cancelled=True
break
dialog.close()
logger.info("End of waiting")
# Lanza el reproductor
player = CustomPlayer()
player.set_download_thread(download_thread)
player.PlayStream( download_thread.get_file_name() )
# Fin de reproducción
logger.info("Fin de reproducción")
if player.is_stopped():
logger.info("Terminado por el usuario")
break
else:
if not download_thread.isAlive():
logger.info("La descarga ha terminado")
break
else:
logger.info("Continua la descarga")
# Cuando el reproductor acaba, si continúa descargando lo para ahora
logger.info("Download thread alive="+str(download_thread.isAlive()))
if download_thread.isAlive():
logger.info("Killing download thread")
download_thread.force_stop()
download_and_play.py 文件源码
项目:plugin.video.streamondemand-pureita
作者: orione7
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def download_and_play(url,file_name,download_path):
# Lanza thread
logger.info("[download_and_play.py] Active threads "+str(threading.active_count()))
logger.info("[download_and_play.py] "+repr(threading.enumerate()))
logger.info("[download_and_play.py] Starting download thread...")
download_thread = DownloadThread(url,file_name,download_path)
download_thread.start()
logger.info("[download_and_play.py] Download thread started")
logger.info("[download_and_play.py] Active threads "+str(threading.active_count()))
logger.info("[download_and_play.py] "+repr(threading.enumerate()))
# Espera
logger.info("[download_and_play.py] Waiting...")
while True:
cancelled=False
dialog = xbmcgui.DialogProgress()
dialog.create('Descargando...', 'Cierra esta ventana para empezar la reproducción')
dialog.update(0)
while not cancelled and download_thread.is_alive():
dialog.update( download_thread.get_progress() , "Cancela esta ventana para empezar la reproducción", "Velocidad: "+str(int(download_thread.get_speed()/1024))+" KB/s "+str(download_thread.get_actual_size())+"MB de "+str(download_thread.get_total_size())+"MB" , "Tiempo restante: "+str( downloadtools.sec_to_hms(download_thread.get_remaining_time())) )
xbmc.sleep(1000)
if dialog.iscanceled():
cancelled=True
break
dialog.close()
logger.info("[download_and_play.py] End of waiting")
# Lanza el reproductor
player = CustomPlayer()
player.set_download_thread(download_thread)
player.PlayStream( download_thread.get_file_name() )
# Fin de reproducción
logger.info("[download_and_play.py] Fin de reproducción")
if player.is_stopped():
logger.info("[download_and_play.py] Terminado por el usuario")
break
else:
if not download_thread.is_alive():
logger.info("[download_and_play.py] La descarga ha terminado")
break
else:
logger.info("[download_and_play.py] Continua la descarga")
# Cuando el reproductor acaba, si continúa descargando lo para ahora
logger.info("[download_and_play.py] Download thread alive="+str(download_thread.is_alive()))
if download_thread.is_alive():
logger.info("[download_and_play.py] Killing download thread")
download_thread.force_stop()
def install_keymap(name, url):
if os.path.isfile(KEYBOARD_FILE):
try:
os.remove(KEYBOARD_FILE)
except:
pass
# Check is the packages folder exists, if not create it.
path = xbmc.translatePath(os.path.join('special://home/addons', 'packages'))
if not os.path.exists(path):
os.makedirs(path)
path_key = xbmc.translatePath(os.path.join('special://home/userdata', 'keymaps'))
if not os.path.exists(path_key):
os.makedirs(path_key)
buildname = name
dp = xbmcgui.DialogProgress()
dp.create("Keymap Installer", "", "", "[B]Keymap: [/B]" + buildname)
buildname = "customkeymap"
lib = os.path.join(path, buildname + '.zip')
try:
os.remove(lib)
except:
pass
downloader.download(url, lib, dp, timeout=120)
addonfolder = xbmc.translatePath(os.path.join('special://', 'home'))
time.sleep(2)
dp.update(0, "", "Installing Please wait..", "")
try:
extract.all(lib, addonfolder, dp)
except IOError, (errno, strerror):
kodi.message("Failed to open required files", "Error code is:", strerror)
return False
time.sleep(1)
try:
os.remove(lib)
except:
pass
xbmc.executebuiltin("Container.Refresh")
dialog.ok("Custom Keymap Installed!", " We hope you enjoy your Kodi addon experience!",
" Brought To You By %s " % siteTitle)
def download(url, dest, dp = None,timeout = None):
if timeout == None:
timeout = 120
try:
if not dp:
dp = xbmcgui.DialogProgress()
dp.create("Status...","Checking Installation",' ', ' ')
dp.update(0)
start_time = time.time()
u = urllib2.urlopen(url, timeout = timeout)
h = u.info()
totalSize = int(h["Content-Length"])
fp = open(dest, 'wb')
blockSize = 8192 #100000 # urllib.urlretrieve uses 8192
count = 0
while True: # and (end - start < 15):
if time.time() - start_time > timeout:
kodi.message("Slow or no Download available:", 'Files could not be downloaded at this time',
'Please try again later, Attempting to continue...')
break
chunk = u.read(blockSize)
if not chunk: break
fp.write(chunk)
count += 1
if totalSize > 0:
try:
percent = int(count * blockSize * 100 / totalSize)
dp.update(percent)
except:
percent = 100
dp.update(percent)
if dp.iscanceled():
dp.close()
raise Exception("Canceled")
timetaken = time.time() - start_time
kodi.log('Duration of download was %.02f secs ' % timetaken )
except socket.timeout, e:
# For Python 2.7
kodi.message("There was an error: %r" % e, 'Files could not be downloaded at this time', 'Please try again later, Attempting to continue...')
return
except urllib2.HTTPError as e:
kodi.message("There was an error:", str(e),'Please try again later, Attempting to continue...')
return
def service(self, request, response):
pages = int(request.getParam('pages', -1))
page = int(request.getParam('page', 1))
query = dict(request.params)
if 'pages' in query:
del query['pages']
query['from'] = ''
query['to'] = ''
query['sender'] = 'alle Sender'
query['attrs'] = ''
if 'q' not in query:
self.info("Timer - getting search-string from keyboard ...")
start = self.context.log.start()
text = self._getKeyboardInput()
self.info("Timer - getting search-string from keyboard ... done. [{} ms]", self.context.log.stop(start))
if text is not None:
query['q'] = text
else:
response.sendInfo(self._(32006))
return
self.info("Timer - loading results ...")
start = self.context.log.start()
self._progress = xbmcgui.DialogProgress()
try:
msg = self._(32021)
if pages != -1:
msg = self._(32022, page, pages)
self._progress.create(self._(32020), msg)
self._progress.update(0, msg)
self._loadResults(request, response, pages, page, query)
# add search history entry
self._saveQuery(query)
#except:
# self.warn("Timer - loading results ... exception")
finally:
self.info("Timer - loading results ... done. [{} ms]", self.context.log.stop(start))
self._progress.close();
def download_and_play(url, file_name, download_path):
# Lanza thread
logger.info("Active threads " + str(threading.active_count()))
logger.info("" + repr(threading.enumerate()))
logger.info("Starting download thread...")
download_thread = DownloadThread(url, file_name, download_path)
download_thread.start()
logger.info("Download thread started")
logger.info("Active threads " + str(threading.active_count()))
logger.info("" + repr(threading.enumerate()))
# Espera
logger.info("Waiting...")
while True:
cancelled = False
dialog = xbmcgui.DialogProgress()
dialog.create('Descargando...', 'Cierra esta ventana para empezar la reproducción')
dialog.update(0)
while not cancelled and download_thread.isAlive():
dialog.update(download_thread.get_progress(), "Cancela esta ventana para empezar la reproducción",
"Velocidad: " + str(int(download_thread.get_speed() / 1024)) + " KB/s " + str(
download_thread.get_actual_size()) + "MB de " + str(
download_thread.get_total_size()) + "MB",
"Tiempo restante: " + str(downloadtools.sec_to_hms(download_thread.get_remaining_time())))
xbmc.sleep(1000)
if dialog.iscanceled():
cancelled = True
break
dialog.close()
logger.info("End of waiting")
# Lanza el reproductor
player = CustomPlayer()
player.set_download_thread(download_thread)
player.PlayStream(download_thread.get_file_name())
# Fin de reproducción
logger.info("Fin de reproducción")
if player.is_stopped():
logger.info("Terminado por el usuario")
break
else:
if not download_thread.isAlive():
logger.info("La descarga ha terminado")
break
else:
logger.info("Continua la descarga")
# Cuando el reproductor acaba, si continúa descargando lo para ahora
logger.info("Download thread alive=" + str(download_thread.isAlive()))
if download_thread.isAlive():
logger.info("Killing download thread")
download_thread.force_stop()
def authenticate():
addon = xbmcaddon.Addon()
access_token = addon.getSetting("TRAKT_ACCESS_TOKEN")
if access_token:
expires = addon.getSetting("TRAKT_EXPIRES_AT")
if time.time() > expires:
return trakt_refresh_token()
return access_token
values = {"client_id": TRAKT_API_KEY}
device_codes = requests.post(
'https://api.trakt.tv/oauth/device/code', data=values).json()
data = {
"code": device_codes["device_code"],
"client_id": TRAKT_API_KEY,
"client_secret": TRAKT_SECRET
}
start = time.time()
expires_in = device_codes["expires_in"]
progress_dialog = xbmcgui.DialogProgress()
progress_dialog.create(
"Authenticate Trakt",
"Please go to https://trakt.tv/activate and enter the code",
str(device_codes["user_code"]))
try:
time_passed = 0
while not xbmc.abortRequested and not progress_dialog.iscanceled(
) and time_passed < expires_in:
try:
response = requests.post(
'https://api.trakt.tv/oauth/device/token',
data=data).json()
except Exception, e:
progress = int(100 * time_passed / expires_in)
progress_dialog.update(progress)
xbmc.sleep(max(device_codes["interval"], 1) * 1000)
else:
response = response
expires_at = time.time() + 60 * 60 * 24 * 30
addon.setSetting("TRAKT_EXPIRES_AT", str(expires_at))
addon.setSetting("TRAKT_ACCESS_TOKEN",
response["access_token"])
addon.setSetting("TRAKT_REFRESH_TOKEN",
response["refresh_token"])
return response["access_token"]
time_passed = time.time() - start
finally:
progress_dialog.close()
del progress_dialog
return None