#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
###
#
# Programa realizado por Javier Perez Pacheco
# http://www.javielinux.com
#
# Para realizar el programa se ha usado partes del codigo de:
# http://mundogeek.net/megaupload-dl/
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
###
import cookielib, urllib, urllib2
import time, sys
import subprocess
import re
import os
import ConfigParser
import sys, threading, time
import pycurl
from xml.dom import minidom
try:
import pygtk
pygtk.require("2.0")
import gtk
with_gtk = True
except ImportError:
with_gtk = False
try:
import signal
from signal import SIGPIPE, SIG_IGN
signal.signal(signal.SIGPIPE, signal.SIG_IGN)
except ImportError:
pass
cookie_mu = ""
cookie_rs = ""
###########################
## CLASS DownloadFile
###########################
class DownloadFile(threading.Thread):
def __init__(self, dw, users, target_file, progress, finishDownload, error):
threading.Thread.__init__(self)
self.target_file = target_file
self.finishDownload = finishDownload
self.error = error
self.progress = progress
self.curl = pycurl.Curl()
self.curl.setopt(pycurl.URL, str(dw.getRealURL()))
self.curl.setopt(pycurl.WRITEDATA, self.target_file)
self.curl.setopt(pycurl.FOLLOWLOCATION, 1)
self.curl.setopt(pycurl.NOPROGRESS, 0)
self.curl.setopt(pycurl.PROGRESSFUNCTION, self.progress)
#self.curl.setopt(pycurl.MAXREDIRS, 5)
self.curl.setopt(pycurl.NOSIGNAL, 1)
if dw.web == "rapidshare":
strPath = os.path.expanduser("~") + "/.megadownloader/cookie-rapidshare"
self.curl.setopt(pycurl.COOKIEFILE, strPath)
def run(self):
try:
self.curl.perform()
self.curl.close()
self.target_file.close()
self.progress(0, 0, 0, 0)
self.finishDownload()
except:
self.error()
###########################
## CLASS redirectManager
###########################
class redirectManager(urllib2.HTTPRedirectHandler):
"""Used to manage the redirects we can find when the user selected direct
downloads at Megaupload"""
def __init__(self):
self.redirect = ""
def http_error_301(self, req, fp, code, msg, headers):
"""Executed when we find a 301 redirect"""
result = urllib2.HTTPRedirectHandler.http_error_301(self, req, fp, code, msg, headers)
result.status = code
self.redirect = result.geturl()
return result
def http_error_302(self, req, fp, code, msg, headers):
"""Executed when we find a 302 redirect"""
result = urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
result.status = code
self.redirect = result.geturl()
return result
###########################
## CLASS Options
###########################
class Options:
downloadFolder = ""
def __init__(self):
self.fileOptions = os.path.expanduser("~") + "/.megadownloader/options"
createFile = False
if os.path.exists(self.fileOptions):
cfg = ConfigParser.SafeConfigParser()
cfg.readfp(file(self.fileOptions))
try:
self.downloadFolder = cfg.get("Options", "downloadfolder")
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
os.remove(self.fileOptions)
createFile = True
else:
createFile = True
if createFile:
self.downloadFolder = os.path.expanduser("~")
self.save()
def save(self):
config = "[Options]\n"
config += "downloadfolder = %s\n" % self.downloadFolder
config_file = open(self.fileOptions, "w")
config_file.write(config)
config_file.close()
###########################
## CLASS Users
###########################
class Users:
user_mu = ""
password_mu = ""
connected_mu = False
user_rs = ""
password_rs = ""
connected_rs = False
def __init__(self):
self.fileUser = os.path.expanduser("~") + "/.megadownloader/users"
user_mu = ""
password_mu = ""
user_rs = ""
password_rs = ""
if os.path.exists(self.fileUser):
cfg = ConfigParser.SafeConfigParser()
cfg.readfp(file(self.fileUser))
try:
user_mu = cfg.get("Megaupload", "user")
password_mu = cfg.get("Megaupload", "password")
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
user_mu = ""
password_mu = ""
print "No existen datos para conectar MegaUpload"
try:
user_rs = cfg.get("Rapidshare", "user")
password_rs = cfg.get("Rapidshare", "password")
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
user_rs = ""
password_rs = ""
print "No existen datos para conectar Rapidshare"
else:
print "Para poder usar el programa necesita insertar los datos de usuario"
self.user_mu = user_mu
self.password_mu = password_mu
self.user_rs = user_rs
self.password_rs = password_rs
def connect(self):
global cookie_mu
global cookie_rs
config = ""
#proxy_support = urllib2.ProxyHandler({"http" : "http://intproxy:8080"})
#opener = urllib2.build_opener(proxy_support)
#urllib2.install_opener(opener)
if not self.user_mu == "" and not self.password_mu == "":
try:
cred_mu = urllib.urlencode({"login": self.user_mu, "password": self.password_mu})
req_mu = urllib2.urlopen("http://megaupload.com", cred_mu)
cookie_mu = req_mu.headers.get("set-cookie", "")
if cookie_mu:
(cookie_mu,_) = cookie_mu.split(";",1)
self.connected_mu = True
config += "[Megaupload]\n"
config += "user = %s\n" % self.user_mu
config += "password = %s\n" % self.password_mu
else:
self.connected_mu = False
except:
print "Error al logarse en Megaupload"
self.connected_mu = False
if not self.user_rs == "" and not self.password_rs == "":
try:
cred_rs = urllib.urlencode({"login": self.user_rs, "password": self.password_rs})
req_rs = urllib2.urlopen("https://ssl.rapidshare.com/cgi-bin/premiumzone.cgi", cred_rs)
cookie_rs = req_rs.headers.get("set-cookie", "")
if cookie_rs:
self.connected_rs = True
config += "[Rapidshare]\n"
config += "user = %s\n" % self.user_rs
config += "password = %s\n" % self.password_rs
else:
self.connected_rs = False
except:
print "Error al logarse en Rapidshare"
self.connected_rs = False
config_file = open(self.fileUser, "w")
config_file.write(config)
config_file.close()
###########################
## CLASS DOWNLOAD
###########################
class Download:
url = ""
filename = ""
size = ""
strError = ""
state = ""
web = ""
comments = ""
def __init__(self, url, filename="", size="", state="waiting"):
if self.from_rapidshare(url):
self.web = "rapidshare"
if self.from_megaupload(url):
self.web = "megaupload"
self.url = self.getValidURL(url)
if filename=="":
self.filename = self.getRealFileName()
else:
self.filename = filename
self.size = size
self.state = state
def from_rapidshare(self, url):
"""Check if this is a rapidshare link"""
return (url.startswith("rapidshare.com") or
url.startswith("www.rapidshare.com") or
url.startswith("http://rapidshare.com") or
url.startswith("http://www.rapidshare.com") or
url.startswith("rapidshare.de") or
url.startswith("www.rapidshare.de") or
url.startswith("http://rapidshare.de") or
url.startswith("http://www.rapidshare.de"))
def from_megaupload(self, url):
"""Check if this is a megaupload link"""
return (url.startswith("megaupload.com") or
url.startswith("www.megaupload.com") or
url.startswith("http://megaupload.com") or
url.startswith("http://www.megaupload.com"))
def getValidURL(self, url):
strurl = url
if self.web == "rapidshare":
if strurl.endswith('.html'):
strurl = strurl[0:len(strurl)-5]
if self.web == "megaupload":
strurl = strurl.replace("es/", "")
return strurl
def getMarKupData(self):
text = ''
f = self.filename
if len(f)>50:
text = text + f[0:22] + "..." + f[-22:len(f)]
else:
text = text + f
text = text + '\n' + self.url + '\n' + self.state + ' ('
if self.state == "error":
text = text + self.strError
else:
text = text + self.web
text = text + ')'
return text
def getRealFileName(self):
parts = self.getRealURL().split("/")
return urllib.unquote(parts[-1])
def getRealURL(self):
if self.web == "rapidshare":
return self.url
if self.web == "megaupload":
global cookie_mu
real_url = ""
try:
url = self.url
req = urllib2.Request(url)
req.add_header("cookie", cookie_mu)
req.add_header("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.8 (Ubuntu-gutsy)")
gr = redirectManager()
opener = urllib2.build_opener(gr)
source = opener.open(req)
if gr.redirect and url != gr.redirect:
# If this is a redirect, the user selected Direct Downloads at Megaupload's preferences
# so we can download the file already
real_url = gr.redirect
else:
# If this is not a redirect, we have to look for the direct download link
source = source.read()
prefixes = re.findall("document.getElementById\(\"download_html\"\).innerHTML = '", source)
if prefixes:
prefix = prefixes[-1]
else:
return ""
real_url = re.findall("document.getElementById\(\"downloadhtml\"\).innerHTML = '=0:
self.currentDownload = position
self.downloads[self.currentDownload].state = "downloading"
def append(self, url):
d = Download(url)
self.downloads.append(d)
self.save()
def remove(self, pos):
del self.downloads[pos]
self.save()
def isDownloading(self):
for d in self.downloads:
if d.state == "downloading":
return True
return False
def clearWaiting(self):
#for n in range(len(self.downloads)):
# self.downloads.pop()
self.downloads = []
dom = minidom.parse(self.file)
count = 0
upPositions = 0
for node in dom.getElementsByTagName('download'):
if not node.attributes["state"].value == "downloaded":
d = Download(node.attributes["url"].value, node.attributes["filename"].value,
node.attributes["size"].value, node.attributes["state"].value)
self.downloads.append(d)
else:
if self.currentDownload>=0 and count <= self.currentDownload:
upPositions = upPositions + 1
count = count + 1
if upPositions > 0:
self.currentDownload = self.currentDownload - upPositions
self.save()
def load(self):
#for n in range(len(self.downloads)):
# self.downloads.pop()
self.downloads = []
dom = minidom.parse(self.file)
count = 0
#upPositions = 0
for node in dom.getElementsByTagName('download'):
d = Download(node.attributes["url"].value, node.attributes["filename"].value,
node.attributes["size"].value, node.attributes["state"].value)
d.comments = node.attributes["comments"].value
self.downloads.append(d)
# if not node.attributes["state"].value == "downloaded":
# d = Download(node.attributes["url"].value, node.attributes["filename"].value,
# node.attributes["size"].value, node.attributes["state"].value)
# d.comments = node.attributes["comments"].value
# self.downloads.append(d)
# else:
# if self.currentDownload>=0 and count <= self.currentDownload:
# upPositions = upPositions + 1
count = count + 1
# if upPositions > 0:
# self.currentDownload = self.currentDownload - upPositions
# self.save()
def save(self):
strXml = """
"""
for d in self.downloads:
strXml = strXml + """
""" % (d.url, d.filename, d.size, d.state, d.comments)
strXml = strXml + """
"""
xml = open(self.file, 'w')
xml.write(strXml)
xml.close()
###########################
## CLASS WINDOW
###########################
class App:
ui = '''
'''
## FUNCTION: CONFIG
def config(self):
self.configDirectory = os.path.expanduser("~") + "/.megadownloader"
if not os.path.exists(self.configDirectory):
os.mkdir(self.configDirectory)
self.md = ManagerDownload()
self.users = Users()
self.options = Options()
self.users.connect()
## FUNCTION: ALERT
def alert (self, message):
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, message)
dialog.run()
dialog.destroy()
## FUNCTION: NEW_CB
def new_cb(self, b):
dialog = gtk.Dialog("Nueva descarga", self.window, 0, (gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
dialog.set_border_width(4)
dialog.set_size_request(450, 350)
l_name = gtk.Label("Direcciones")
dialog.vbox.pack_start(l_name, False, False, 0)
sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
tv_downloads = gtk.TextView()
tb_downloads = tv_downloads.get_buffer()
sw.add(tv_downloads)
sw.show()
tv_downloads.show()
dialog.vbox.pack_start(sw, True, True, 0)
dialog.show_all()
response = dialog.run()
if response == gtk.RESPONSE_OK:
start, end = tb_downloads.get_bounds()
urls = tb_downloads.get_text(start,end).split("\n")
for u in urls:
mo = re.finditer("http://\S*",u)
if mo:
for u2 in mo:
self.md.append(u2.group())
if self.md.isDownloading():
self.refresh()
else:
self.nextDownload()
dialog.destroy()
## FUNCTION: DELETE_CB
def foreach_cods(self, model, path, it, cods):
cod = int(self.store_dw.get_value(it, 0))
cods.append(cod)
def delete_cb(self, b):
(tree, iters) = self.tv_dw.get_selection().get_selected_rows()
if iters == None:
self.alert("Seleccione una descarga")
else:
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_YES_NO, "¿Está seguro de querer borrarlo?")
response = dialog.run()
if response == gtk.RESPONSE_YES:
sw = False
cods = []
self.tv_dw.get_selection().selected_foreach(self.foreach_cods, cods)
for c in range(len(cods)-1,-1,-1):
cod = cods[c]
if self.md.downloads[cod].state == "downloading":
sw = True
self.md.remove(cod)
if sw:
self.nextDownload()
else:
self.refresh()
dialog.destroy()
## FUNCTION: ABOUT_CB
def about_cb(self, b):
self.alert("MegadDownloader 0.3\n\nPrograma realizado por Fco. Javier Pérez Pacheco\nwww.javielinux.com\n\nMas información en:\nhttp://megadownloader.javielinux.com\n\nPara realizar el programa se ha usado partes del código de:\nhttp://mundogeek.net/megaupload-dl/\nhttp://mundogeek.net/rapidshare-dl/\n\nLicencia GPL")
## FUNCTION: CLEANDOWNLOADED_CB
def cleandownloaded_cb(self, b):
self.md.clearWaiting()
self.refresh()
## FUNCTION: STATEWAITING_CB
def statewaiting_cb(self, b):
(tree, iters) = self.tv_dw.get_selection().get_selected_rows()
if iters == None:
self.alert("Seleccione una descarga")
else:
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_YES_NO, "¿Está seguro de querer cambiarlo?")
response = dialog.run()
if response == gtk.RESPONSE_YES:
sw = False
cods = []
self.tv_dw.get_selection().selected_foreach(self.foreach_cods, cods)
for c in range(len(cods)-1,-1,-1):
cod = cods[c]
if self.md.downloads[cod].state == "downloading":
sw = True
self.md.downloads[cod].state = "waiting"
if sw:
self.nextDownload()
else:
self.refresh()
dialog.destroy()
## FUNCTION: PREFERENCES_CB
def ClickButton_dir(self, widget, *args):
dialog = gtk.FileChooserDialog("Seleccionar directorio", None, gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
dialog.set_filename(self.options.downloadFolder)
dialog.set_default_response(gtk.RESPONSE_OK)
response = dialog.run()
if response == gtk.RESPONSE_OK:
self.e_dir.set_text(dialog.get_filename())
self.options.downloadFolder = dialog.get_filename()
dialog.destroy()
def preference_cb(self, b):
dialog = gtk.Dialog("Preferencias", self.window, 0, (gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
dialog.set_size_request(450, 400)
dialog.set_border_width(12)
lMegaupload = gtk.Label("Cuenta Megaupload")
lMegaupload.set_use_markup(True)
lMegaupload.set_alignment(0, 0)
dialog.vbox.pack_start(lMegaupload, False, False, 0)
table = gtk.Table(2, 2)
table.set_border_width(8)
table.set_row_spacings(12)
table.set_col_spacings(12)
l_name = gtk.Label("Nombre:")
table.attach(l_name, 0, 1, 0, 1, gtk.FILL)
e_name = gtk.Entry()
table.attach(e_name, 1, 2, 0, 1, gtk.EXPAND|gtk.FILL)
l_pass = gtk.Label("Clave:")
table.attach(l_pass, 0, 1, 1, 2, gtk.FILL)
e_pass = gtk.Entry()
e_pass.set_visibility(False)
table.attach(e_pass, 1, 2, 1, 2, gtk.EXPAND|gtk.FILL)
e_name.set_text(self.users.user_mu)
e_pass.set_text(self.users.password_mu)
dialog.vbox.pack_start(table, False, False, 0)
lBlank = gtk.Label("")
dialog.vbox.pack_start(lBlank, False, False, 0)
lRapidshare = gtk.Label("Cuenta Rapidshare")
lRapidshare.set_use_markup(True)
lRapidshare.set_alignment(0, 0)
dialog.vbox.pack_start(lRapidshare, False, False, 0)
table1 = gtk.Table(2, 2)
table1.set_border_width(8)
table1.set_row_spacings(12)
table1.set_col_spacings(12)
l_namers = gtk.Label("Nombre:")
table1.attach(l_namers, 0, 1, 0, 1, gtk.FILL)
e_namers = gtk.Entry()
table1.attach(e_namers, 1, 2, 0, 1, gtk.EXPAND|gtk.FILL)
l_passrs = gtk.Label("Clave:")
table1.attach(l_passrs, 0, 1, 1, 2, gtk.FILL)
e_passrs = gtk.Entry()
e_passrs.set_visibility(False)
table1.attach(e_passrs, 1, 2, 1, 2, gtk.EXPAND|gtk.FILL)
e_namers.set_text(self.users.user_rs)
e_passrs.set_text(self.users.password_rs)
dialog.vbox.pack_start(table1, False, False, 0)
lBlank1 = gtk.Label("")
dialog.vbox.pack_start(lBlank1, False, False, 0)
lOthers = gtk.Label("Otros datos")
lOthers.set_use_markup(True)
lOthers.set_alignment(0, 0)
dialog.vbox.pack_start(lOthers, False, False, 0)
table2 = gtk.Table(3, 2)
table2.set_border_width(8)
table2.set_row_spacings(12)
table2.set_col_spacings(12)
l_dir = gtk.Label("Descargar en:")
table2.attach(l_dir, 0, 1, 0, 1, gtk.FILL)
self.e_dir = gtk.Entry()
table2.attach(self.e_dir, 1, 2, 0, 1, gtk.EXPAND|gtk.FILL)
button_dir = gtk.Button("")
button_dir.set_use_stock(1)
imgbutton_dir = gtk.Image()
imgbutton_dir.set_from_stock(gtk.STOCK_FIND, gtk.ICON_SIZE_BUTTON)
button_dir.set_image(imgbutton_dir)
button_dir.connect("clicked", self.ClickButton_dir)
table2.attach(button_dir, 2, 3, 0, 1, gtk.FILL)
self.e_dir.set_text(self.options.downloadFolder)
dialog.vbox.pack_start(table2, False, False, 0)
dialog.show_all()
response = dialog.run()
if response == gtk.RESPONSE_OK:
self.options.downloadFolder = self.e_dir.get_text()
self.options.save()
self.users.user_mu = e_name.get_text()
self.users.password_mu = e_pass.get_text()
self.users.user_rs = e_namers.get_text()
self.users.password_rs = e_passrs.get_text()
self.users.connect()
strUser = "Datos de la conexion:"
if self.users.connected_mu:
strUser += "\n\tUsuario conectado a MegaUpload"
else:
strUser += "\n\tUsuario no conectado a MegaUpload"
if self.users.connected_rs:
strUser += "\n\tUsuario conectado a RapidShare"
# cookie for rapidshare
os.system('curl --cookie-jar ' + self.configDirectory + '/cookie-rapidshare -d login=' + self.users.user_rs + ' -d password=' + self.users.password_rs + ' https://ssl.rapidshare.com/cgi-bin/premiumzone.cgi > /dev/null')
else:
strUser += "\n\tUsuario no conectado a RapidShare"
self.alert(strUser)
self.set_title_window()
dialog.destroy()
## FUNCTION: QUIT_CB
def quit_cb(self, b):
if self.md.isDownloading():
os.abort()
gtk.main_quit()
## FUNCTION: SET_TITLE_WINDOW
def set_title_window(self):
strTitle = "MegaDownloader"
if self.users.connected_mu:
strTitle += " - Megaupload (" + self.users.user_mu + ")"
else:
strTitle += " - Megaupload (NO)"
if self.users.connected_rs:
strTitle += " - RapidShare (" + self.users.user_rs + ")"
else:
strTitle += " - RapidShare (NO)"
self.window.set_title(strTitle)
def close_app(self, *args):
if self.md.isDownloading():
os.abort()
gtk.main_quit()
def on_cursor_changed(self, arg):
(tree, iters) = self.tv_dw.get_selection().get_selected_rows()
cods = []
self.tv_dw.get_selection().selected_foreach(self.foreach_cods, cods)
self.writeDataDownload (cods[0])
def ClickSaveComment(self, widget):
if self.currentDownloadInfo >= 0:
start = self.textbuffer_comments.get_start_iter()
end = self.textbuffer_comments.get_end_iter()
self.md.downloads[self.currentDownloadInfo].comments = self.textbuffer_comments.get_text(start, end).replace("\n", "|")
self.md.save()
def __init__(self):
self.currentDownloadInfo = -1
self.firstTry = True
self.round = 0.0
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_size_request(780, 550)
self.window.connect("destroy", self.close_app)
self.config()
self.set_title_window()
vbox = gtk.VBox()
self.window.add(vbox)
uimanager = gtk.UIManager()
accelgroup = uimanager.get_accel_group()
self.window.add_accel_group(accelgroup)
actiongroup = gtk.ActionGroup('UIManagerExample')
self.actiongroup = actiongroup
uimanager.insert_action_group(actiongroup, 0)
actiongroup.add_actions([
('Quit', gtk.STOCK_QUIT, '_Salir', None, 'Salir del programa', self.quit_cb),
('New', gtk.STOCK_NEW, 'Nueva descarga', None, 'Nueva descarga', self.new_cb),
('Connect', gtk.STOCK_NEW, 'Conectar', None, 'Conectar', self.connect),
('Delete', gtk.STOCK_DELETE, 'Borrar descarga', None, 'Borrar descarga', self.delete_cb),
('Options', gtk.STOCK_PREFERENCES, 'Opciones', None, 'Opciones', self.preference_cb),
('StateWaiting', None, 'Cambiar estado a \'Espera\'', None, 'Cambiar estado a \'Espera\'', self.statewaiting_cb),
('CleanDownloaded', None, 'Limpiar completados', None, 'Limpiar completados', self.cleandownloaded_cb),
('About', gtk.STOCK_ABOUT, 'Acerca de', None, 'Acerca de', self.about_cb),
('Actions', None, 'Acciones'),
('File', None, '_Archivo'),
('Help', None, 'Ayuda')
])
uimanager.add_ui_from_string(self.ui)
menubar = uimanager.get_widget('/MenuBar')
toolbar = uimanager.get_widget('/Toolbar')
vbox.pack_start(menubar, False)
vbox.pack_start(toolbar, False)
self.store_dw = gtk.ListStore(str, str)
sw_dw = gtk.ScrolledWindow()
sw_dw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.tv_dw = gtk.TreeView(self.store_dw)
self.tv_dw.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
self.tv_dw.connect("cursor-changed", self.on_cursor_changed)
# Column: text
cell = gtk.CellRendererText()
column_text = gtk.TreeViewColumn('Pos', cell, text=0)
self.tv_dw.append_column(column_text)
column_text.set_visible(False)
# Column: text
cell2 = gtk.CellRendererText()
column_text2 = gtk.TreeViewColumn('Descargas', cell2, markup=1)
self.tv_dw.append_column(column_text2)
sw_dw.add(self.tv_dw)
hpaned = gtk.HPaned()
hpaned.set_border_width(8)
hpaned.set_position(400)
vbox.pack_start(hpaned, True)
hpaned.show()
hpaned.add1(sw_dw)
frameVBox =gtk.VBox(False, 4)
frameVBox.show()
frameInfoFile = gtk.Frame("Informacion del archivo")
tableInfoFile = gtk.Table(2, 2)
tableInfoFile.set_border_width(8)
tableInfoFile.set_row_spacings(12)
tableInfoFile.set_col_spacings(12)
#lInfoFile_name = gtk.Label("Nombre:")
#lInfoFile_name.set_alignment(0, 0)
#tableInfoFile.attach(lInfoFile_name, 0, 1, 0, 1, gtk.FILL, gtk.FILL)
self.lInfoFile_name_value = gtk.Label("")
self.lInfoFile_name_value.set_alignment(0, 0)
tableInfoFile.attach(self.lInfoFile_name_value, 0, 2, 0, 1, gtk.EXPAND|gtk.FILL, gtk.FILL)
lInfoFile_status = gtk.Label("Estado:")
lInfoFile_status.set_alignment(0, 0)
tableInfoFile.attach(lInfoFile_status, 0, 1, 1, 2, gtk.FILL, gtk.FILL)
self.lInfoFile_status_value = gtk.Label("")
self.lInfoFile_status_value.set_alignment(0, 0)
tableInfoFile.attach(self.lInfoFile_status_value, 1, 2, 1, 2, gtk.EXPAND|gtk.FILL, gtk.FILL)
lInfoFile_from = gtk.Label("Desde:")
lInfoFile_from.set_alignment(0, 0)
tableInfoFile.attach(lInfoFile_from, 0, 1, 2, 3, gtk.FILL, gtk.FILL)
self.lInfoFile_from_value = gtk.Label("")
self.lInfoFile_from_value.set_alignment(0, 0)
tableInfoFile.attach(self.lInfoFile_from_value, 1, 2, 2, 3, gtk.EXPAND|gtk.FILL, gtk.FILL)
lInfoFile_info = gtk.Label("Información:")
lInfoFile_info.set_alignment(0, 0)
tableInfoFile.attach(lInfoFile_info, 0, 1, 3, 4, gtk.FILL, gtk.FILL)
sw_comments = gtk.ScrolledWindow()
sw_comments.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.textview_comments = gtk.TextView()
self.textview_comments.set_wrap_mode(gtk.WRAP_WORD)
self.textbuffer_comments = self.textview_comments.get_buffer()
sw_comments.add(self.textview_comments)
sw_comments.show()
self.textview_comments.show()
tableInfoFile.attach(sw_comments, 1, 2, 3, 4, gtk.EXPAND|gtk.FILL, gtk.EXPAND|gtk.FILL)
aligButtonSaveComment = gtk.Alignment(0.0, 0.5)
btnSaveComment = gtk.Button("Guardar información")
btnSaveComment.connect("clicked", self.ClickSaveComment)
aligButtonSaveComment.add(btnSaveComment)
tableInfoFile.attach(aligButtonSaveComment, 1, 2, 4, 5, gtk.FILL)
frameInfoFile.add(tableInfoFile)
frameVBox.pack_start(frameInfoFile, True, True, 0)
frameInfoGeneral = gtk.Frame("Descarga actual")
tableInfoGeneral = gtk.Table(2, 2)
tableInfoGeneral.set_border_width(8)
tableInfoGeneral.set_row_spacings(12)
tableInfoGeneral.set_col_spacings(12)
#lInfoGeneral_name = gtk.Label("Nombre:")
#lInfoGeneral_name.set_alignment(0, 0)
#tableInfoGeneral.attach(lInfoGeneral_name, 0, 1, 0, 1, gtk.FILL, gtk.FILL)
self.lInfoGeneral_name_value = gtk.Label("")
self.lInfoGeneral_name_value.set_alignment(0, 0)
tableInfoGeneral.attach(self.lInfoGeneral_name_value, 0, 2, 0, 1, gtk.EXPAND|gtk.FILL, gtk.FILL)
lInfoGeneral_velocity = gtk.Label("Velocidad:")
lInfoGeneral_velocity.set_alignment(0, 0)
tableInfoGeneral.attach(lInfoGeneral_velocity, 0, 1, 1, 2, gtk.FILL, gtk.FILL)
self.lInfoGeneral_velocity_value = gtk.Label("")
self.lInfoGeneral_velocity_value.set_alignment(0, 0)
tableInfoGeneral.attach(self.lInfoGeneral_velocity_value, 1, 2, 1, 2, gtk.EXPAND|gtk.FILL, gtk.FILL)
lInfoGeneral_downloaded = gtk.Label("Descargado:")
lInfoGeneral_downloaded.set_alignment(0, 0)
tableInfoGeneral.attach(lInfoGeneral_downloaded, 0, 1, 2, 3, gtk.FILL, gtk.FILL)
self.lInfoGeneral_downloaded_value = gtk.Label("")
self.lInfoGeneral_downloaded_value.set_alignment(0, 0)
tableInfoGeneral.attach(self.lInfoGeneral_downloaded_value, 1, 2, 2, 3, gtk.EXPAND|gtk.FILL, gtk.FILL)
lInfoGeneral_total = gtk.Label("Total:")
lInfoGeneral_total.set_alignment(0, 0)
tableInfoGeneral.attach(lInfoGeneral_total, 0, 1, 3, 4, gtk.FILL, gtk.FILL)
self.lInfoGeneral_total_value = gtk.Label("")
self.lInfoGeneral_total_value.set_alignment(0, 0)
tableInfoGeneral.attach(self.lInfoGeneral_total_value, 1, 2, 3, 4, gtk.EXPAND|gtk.FILL, gtk.FILL)
pbar = gtk.ProgressBar()
pbar.show()
self.pbar = pbar
tableInfoGeneral.attach(pbar, 0, 2, 4, 5, gtk.EXPAND|gtk.FILL, gtk.FILL)
#vbox.pack_start(pbar, False)
frameInfoGeneral.add(tableInfoGeneral)
frameVBox.pack_start(frameInfoGeneral, False, True, 0)
hpaned.add2(frameVBox)
self.md.load()
self.refresh()
self.window.show()
self.window.show_all()
if len(self.md.downloads) > 0:
self.nextDownload()
def connect(self, b):
if not self.md.isDownloading():
self.nextDownload()
def progress(self, download_t, download_d, upload_t, upload_d):
if not download_t == 0:
self.round = float(download_d) / float(download_t)
if self.round >= 1.0:
self.round = 0.0
gtk.gdk.threads_enter()
self.pbar.set_fraction(self.round)
self.pbar.set_text(str(int(self.round*100)) + "%")
self.lInfoGeneral_downloaded_value.set_text(str(int((download_d/1024)/1024)) + " mb")
self.lInfoGeneral_total_value.set_text(str(int((download_t/1024)/1024)) + " mb")
t = time.time()
if t-self.timeStart >= 1:
end = (self.bytesPerSecond/1024)/(t-self.timeStart)
txt = str(int(end)) + " kb/s"
self.lInfoGeneral_velocity_value.set_text(txt)
self.bytesPerSecond = 0
self.timeStart = t
else:
self.bytesPerSecond = self.bytesPerSecond + (download_d-self.oldDownload_d)
self.oldDownload_d = download_d
gtk.gdk.threads_leave()
def refresh(self):
self.store_dw.clear()
cont = 0
for d in self.md.downloads:
self.store_dw.append([str(cont), d.getMarKupData()])
cont = cont + 1
def finishDownload(self):
print "(" + str(self.md.currentDownload) + ") Archivo " + self.md.downloads[self.md.currentDownload].filename + " descargado"
self.md.downloads[self.md.currentDownload].state = "downloaded"
self.md.save()
self.nextDownload()
def nextDownload(self):
self.firstTry = True
searchWaiting = True
cont = 0
for d in self.md.downloads:
if d.state == "downloading":
self.startDownload(cont)
searchWaiting = False
break
cont = cont + 1
if searchWaiting:
cont = 0
for d in self.md.downloads:
if d.state == "waiting":
self.startDownload(cont)
break
cont = cont + 1
self.refresh()
def errorDownload(self):
if self.firstTry:
self.firstTry = False
self.startDownload(self.md.currentDownload)
else:
self.md.downloads[self.md.currentDownload].state = "error"
self.md.downloads[self.md.currentDownload].strError = "Problema al conectar con la dirección URL"
self.md.save()
self.nextDownload()
def startDownload(self, position):
isConnected = True
if self.md.downloads[position].web == "megaupload" and not self.users.connected_mu:
isConnected = False
self.md.downloads[position].state = "error"
self.md.downloads[position].strError = "No esta conectado a MegaUpload"
if self.md.downloads[position].web == "rapidshare" and not self.users.connected_rs:
isConnected = False
self.md.downloads[position].state = "error"
self.md.downloads[position].strError = "No esta conectado a RapidShare"
if isConnected:
if self.md.downloads[position].filename == "":
self.md.downloads[position].state = "error"
self.md.downloads[position].strError = "Error al buscar el nombre real de la descarga. Es posible que su cuenta esté caducada."
self.nextDownload()
else:
self.round = 0.0
self.md.startDownload(position)
path = self.options.downloadFolder + "/" + self.md.downloads[position].filename
self.downloadFile = DownloadFile(self.md.downloads[position], self.users, open(path, 'wb'), self.progress, self.finishDownload, self.errorDownload)
self.downloadFile.start()
print "(" + str(self.md.currentDownload) + ") Comenzando descarga de " + self.md.downloads[self.md.currentDownload].filename
self.md.save()
self.writeDataCurrentDownload()
else:
self.nextDownload()
def writeDataDownload(self, pos):
self.currentDownloadInfo = pos
#self.tv_dw.get_selection().select_path((self.currentDownloadInfo,))
filename = self.md.downloads[pos].filename
if len(filename)>47:
filename = filename[0:22] + "..." + filename[-22:len(filename)]
self.lInfoFile_name_value.set_text(filename)
self.textbuffer_comments.set_text(self.md.downloads[pos].comments.replace("|", "\n"))
self.lInfoFile_status_value.set_text(self.md.downloads[pos].state)
self.lInfoFile_from_value.set_text(self.md.downloads[pos].web)
def writeDataCurrentDownload(self):
filename = self.md.downloads[self.md.currentDownload].filename
if len(filename)>47:
filename = filename[0:22] + "..." + filename[-22:len(filename)]
self.lInfoGeneral_name_value.set_text(filename)
if self.lInfoFile_name_value.get_text() == "":
self.writeDataDownload(self.md.currentDownload)
def main(self):
self.timeStart = time.time()
self.oldDownload_d = 0
self.bytesPerSecond = 0
gtk.gdk.threads_enter()
gtk.main()
gtk.gdk.threads_leave()
###########################
##
## PROGRAM
##
###########################
app = App()
gtk.gdk.threads_init()
try:
app.main()
except KeyboardInterrupt:
pass