Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # Author: Jan Tulak <jan@tulak.me>
- #
- # You can feel free to do anything with this source as you want.
- #
- # NO WARRANTY!!!
- #
- # This script is for fast file upload on a ftp server.
- # You can create an shortcut with "-g" parameter, so you can simply drag'n drop any file
- # to it and this script upload the file and show its address in dialog.
- # Or you can add "-c" parameter and it will paste its address into clipboard,
- # or you can combine it.
- # If you give a directory instead of file, this script make an .tgz archive from it
- # and upload this archive (is using your temp dir)
- # settings - change to yourself
- FTP_HOST='host' # FTP server address
- FTP_USER='user' # user for FTP
- FTP_PASS='pass' # password for the user
- FTP_DIR='your_dir/on/ftp' # directory on FTP server, in which you want store files
- retUrl='http://your-webhost/your_dir/on/ftp' # URL which will be added to filename pasted into the clipboard
- retUrlDir='http://your-webhost/?show-files=true' # URL to a list of all uploaded files
- # ----------------------------------------------------------------------------
- # HERE BEGIN SCRIPT
- # ----------------------------------------------------------------------------
- from ftplib import FTP
- import os
- import urllib
- import sys
- import pygtk
- pygtk.require('2.0')
- import gtk
- import tarfile
- import tempfile
- import re
- import string
- # ----------------------------------------------------------------------------
- # vlastni tridy
- # ----------------------------------------------------------------------------
- # trida na vlastni vyjimku
- class uploadError(Exception):
- def __init__(self, value):
- self.value = value
- def __str__(self):
- return repr(self.value)
- def string(self):
- return self.value
- # trida na vlastni zpravuu
- class uploadMsg(Exception):
- def __init__(self, value):
- self.value = value
- def __str__(self):
- return repr(self.value)
- def string(self):
- return self.value
- # ----------------------------------------------------------------------------
- # globalni promenne
- # ----------------------------------------------------------------------------
- debug=0
- useClipboard=0
- useGTK=0
- # ----------------------------------------------------------------------------
- # definice funkci
- # ----------------------------------------------------------------------------
- # tohle nahraje pres FTP zadany soubor na zadane spojeni
- def upload(conn, fname):
- # pokud jde o adresar, vytvori archiv a zavola sebe sama s cestou k archivu
- if os.path.isdir(fname):
- if debug: print '"%s" is a dir - tgz must be created.' % fname
- fname=os.path.abspath(fname) # aby slo pouzivat i veci jako "./"
- cregex=re.compile('/$') # compile the search regexp
- fname=cregex.sub('',fname) # nahradime koncove lomitko, kdyby uzivatel zadal cestu s nim
- (head, tail) = os.path.split(fname) # zjistime nazev soubor/adresare
- tmpDir=tempfile.gettempdir() # dostaneme temp dir
- tar = tarfile.open(tmpDir+'/'+tail+'.tgz', "w:gz")
- if debug: print 'Adding files to archive.'
- tar.add(fname,arcname=tail)
- tar.close()
- upload(conn, tmpDir+'/'+tail+'.tgz') # zavolame se znova, tentokrat s cestou k archivu
- # smazeme docasny archiv
- os.remove(tmpDir+'/'+tail+'.tgz')
- raise uploadMsg, tmpDir+'/'+tail+'.tgz'
- #raise uploadError, "ERROR: %s is a dir!" % fname
- # pokud jde o soubor, odesle ho
- elif os.path.isfile(fname):
- if debug: print 'Begin upload of "%s".' % fname
- (head, tail) = os.path.split(fname) # zjistime nazev soubor/adresare
- command = "STOR " + tail
- fd = open(fname, 'rb')
- temp = fd.read(2048)
- fd.seek(0, 0)
- if temp.find('\0') != -1:
- conn.storbinary(command, fd)
- else:
- conn.storlines(command, fd)
- fd.close()
- raise uploadMsg, tail
- # neexistujici soubor
- else:
- raise uploadError, "ERROR: %s not exist!" % fname
- # vytiskne napovedu
- def usage():
- print 'usage: '+sys.argv[0]+' [COMMAND] file1 file2 ...'
- print 'COMMAND:'
- print ' -h --help Show this help'
- print ' -d Debug mode'
- print ' -c Store address to clipboar'
- print ' -g Show GTK Dialog'
- print 'Tip:'
- print 'You can create an desktop entry, combine -c and -g and simply drag and drop any file on it.'
- print 'If you give a directory instead of file, this script make an .tgz archive from it a upload this archive (is using your temp dir).'
- print 'Author: Jan Tulak <jan@tulak.me>'
- # dialog
- def custom_dialog(dialog_type, title, message):
- '''custom_dialog(dialog_type, title, message)
- This is a generic Gtk Message Dialog function.
- dialog_type = this is a Gtk type. The options are:
- gtk.MESSAGE_INFO
- gtk.MESSAGE_WARNING
- gtk.MESSAGE_ERROR
- '''
- dialog = gtk.MessageDialog(None,
- gtk.DIALOG_MODAL,
- type=dialog_type,
- buttons=gtk.BUTTONS_OK)
- dialog.set_markup("<b>%s</b>" % title)
- dialog.format_secondary_markup(message)
- dialog.run()
- dialog.destroy()
- # ----------------------------------------------------------------------------
- # MAIN
- # ----------------------------------------------------------------------------
- # lets begin
- if __name__ == "__main__":
- if len(sys.argv) == 1:
- usage()
- sys.exit(0)
- targetFiles = []
- # parametry
- i=0
- for arg in sys.argv:
- if arg in ("-h", "--help"):
- usage()
- sys.exit(0)
- elif arg == '-d':
- if len(sys.argv) == 2:
- usage()
- sys.exit(0)
- debug = 1
- elif arg == '-c':
- if len(sys.argv) == 2:
- usage()
- sys.exit(0)
- useClipboard = 1
- elif arg == '-g':
- if len(sys.argv) == 2:
- usage()
- sys.exit(0)
- useGTK = 1
- elif i > 0:
- targetFiles.append(arg)
- i=i+1
- # vytvoreni FTP spojeni
- #
- # Create an instance of the FTP object
- # Optionally, you could specify username and password:
- # FTP('hostname', 'username', 'password')
- #ftp = FTP('tulak.me','tulakme','C4dRr40fb4')
- ftp = FTP(FTP_HOST)
- # Log in to the server
- if debug: print 'Logging in.'
- # You can specify username and password here if you like:
- try:
- res=ftp.login(FTP_USER,FTP_PASS)
- if debug: print res
- # Otherwise, it defaults to Anonymous
- #print ftp.login()
- except:
- # error dialog
- message_type = gtk.MESSAGE_ERROR
- error_title = "ERROR!"
- error_description = "Cannot connect to server"
- custom_dialog(message_type, error_title, error_description)
- print 'Cannot connect'
- exit(1)
- # zkusime vlezt do adresare a nahrat tam soubor
- try:
- if debug: print 'Changing to ' + FTP_DIR
- res=ftp.cwd(FTP_DIR)
- if debug: print res
- retUrlWithFile=""
- for targetFile in targetFiles:
- try:
- res=upload(ftp, targetFile)
- if debug: print res
- except uploadMsg,msg:
- retUrlWithFile = retUrlWithFile+retUrl+urllib.quote(msg.string())+'\n'
- print retUrl+urllib.quote(os.path.basename(msg.string()))
- if debug: print 'File/dir was uploaded successfuly.'
- except uploadError,msg:
- if useGTK:
- # error dialog
- message_type = gtk.MESSAGE_ERROR
- error_title = "ERROR!"
- error_description = "Cannot upload file:\n"+msg.string()
- custom_dialog(message_type, error_title, error_description)
- sys.exit("Cannot upload file:\n"+msg.string()) # chyba souboru - neexistuje a podobne
- except:
- if useGTK:
- # error dialog
- message_type = gtk.MESSAGE_ERROR
- error_title = "ERROR!"
- error_description = "Cannot upload file due an error."
- custom_dialog(message_type, error_title, error_description)
- sys.exit('ERROR: Cannot upload file due an error.') # nejaka chyba od ftp knihovny
- # chceme ulozit do clipboardu
- if useClipboard:
- # get the clipboard
- clipboard = gtk.clipboard_get()
- # set the clipboard text data
- clipboard.set_text(retUrlWithFile)
- # make our data available to other applications
- clipboard.store()
- # chceme zobrazit dialog
- if useGTK:
- # Info dialog
- message_type = gtk.MESSAGE_INFO
- info_title = "File was succesfully uploaded"
- info_description = "File was succesfully uploaded"
- if useClipboard:
- info_description=info_description+" and addres stored in the clipboard"
- info_description=info_description+":\n\n" + retUrlWithFile +"\n"+\
- "<a href='"+retUrlDir+"'>List of files</a>"
- custom_dialog(message_type, info_title, info_description)
- if debug: print 'Closing FTP connection'
- ftp.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement