def run(self, url, source): path = os.path.join(control.dataPath, 'temp') try: path = path.decode('utf-8') except Exception: pass control.deleteDir(control.join(path, ''), force=True) control.makeFile(control.dataPath) control.makeFile(path) if source == 's4f': subtitle = s4f.s4f().download(path, url) elif source == 'subztv': subtitle = subztv.subztv().download(path, url) elif source == 'yifi': subtitle = yifi.yifi().download(path, url) else: subtitle = None if subtitle is not None: item = control.item(label=subtitle) control.addItem(handle=syshandle, url=subtitle, listitem=item, isFolder=False) control.directory(syshandle)
def download_media(url, path, file_name, progress=None): try: if progress is None: progress = int(control.setting('progress_dialog')) active = not progress == PROGRESS.OFF background = progress == PROGRESS.BACKGROUND with control.ProgressDialog( control.addonInfo('name'), control.lang(30500).format(file_name), background=background, active=active ) as pd: try: headers = dict([item.split('=') for item in (url.split('|')[1]).split('&')]) for key in headers: headers[key] = unquote(headers[key]) except: headers = {} if 'User-Agent' not in headers: headers['User-Agent'] = randomagent() request = urllib2.Request(url.split('|')[0], headers=headers) response = urllib2.urlopen(request) if 'Content-Length' in response.info(): content_length = int(response.info()['Content-Length']) else: content_length = 0 file_name += '.' + get_extension(url, response) full_path = control.join(path, file_name) log_debug('Downloading: %s -> %s' % (url, full_path)) path = control.transPath(control.legalfilename(path)) try: control.makeFiles(path) except Exception as e: log_debug('Path Create Failed: %s (%s)' % (e, path)) from os import sep if not path.endswith(sep): path += sep if not control.exists(path): raise Exception('Failed to create dir') file_desc = control.openFile(full_path, 'w') total_len = 0 cancel = False while 1: data = response.read(512 * 1024) if not data: break if pd.is_canceled(): cancel = True break total_len += len(data) if not file_desc.write(data): raise Exception('Failed to write file') percent_progress = total_len * 100 / content_length if content_length > 0 else 0 log_debug('Position : {0} / {1} = {2}%'.format(total_len, content_length, percent_progress)) pd.update(percent_progress) file_desc.close() if not cancel: control.infoDialog(control.lang(30501).format(file_name)) log_debug('Download Complete: {0} -> {1}'.format(url, full_path)) except Exception as e: log_debug('Error ({0}) during download: {1} -> {2}'.format(str(e), url, file_name)) control.infoDialog(control.lang(30502).format(str(e), file_name))