nyk0r

PasteBin Python 2.XX Binding

Aug 30th, 2011
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.31 KB | None | 0 0
  1. #/usr/bin/env python
  2.  
  3. import urllib, urllib2, re
  4. from xml.dom import minidom
  5.  
  6. DEV_KEY = 'DEVELOPER-KEY' # http://pastebin.com/api#1
  7.  
  8. FILE_FORMATS = {
  9.     '4cs' : '4CS',
  10.     '6502acme' : '6502 ACME Cross Assembler',
  11.     '6502kickass' : '6502 Kick Assembler',
  12.     '6502tasm' : '6502 TASM/64TASS',
  13.     'abap' : 'ABAP',
  14.     'actionscript' : 'ActionScript',
  15.     'actionscript3' : 'ActionScript 3',
  16.     'ada' : 'Ada',
  17.     'algol68' : 'ALGOL 68',
  18.     'apache' : 'Apache Log',
  19.     'applescript' : 'AppleScript',
  20.     'apt_sources' : 'APT Sources',
  21.     'asm' : 'ASM (NASM)',
  22.     'asp' : 'ASP',
  23.     'autoconf' : 'autoconf',
  24.     'autohotkey' : 'Autohotkey',
  25.     'autoit' : 'AutoIt',
  26.     'avisynth' : 'Avisynth',
  27.     'awk' : 'Awk',
  28.     'bascomavr' : 'BASCOM' 'AVR',
  29.     'bash' : 'Bash',
  30.     'basic4gl' : 'Basic4GL',
  31.     'bibtex' : 'BibTeX',
  32.     'blitzbasic' : 'Blitz Basic',
  33.     'bnf' : 'BNF',
  34.     'boo' : 'BOO',
  35.     'bf' : 'BrainFuck',
  36.     'c' : 'C',
  37.     'c_mac' : 'C for Macs',
  38.     'cil' : 'C Intermediate Language',
  39.     'csharp' : 'C#',
  40.     'cpp' : 'C++',
  41.     'cpp-qt' : 'C++ (with QT extensions)',
  42.     'c_loadrunner' : 'C: Loadrunner',
  43.     'caddcl' : 'CAD DCL',
  44.     'cadlisp' : 'CAD Lisp',
  45.     'cfdg' : 'CFDG',
  46.     'chaiscript' : 'ChaiScript',
  47.     'clojure' : 'Clojure',
  48.     'klonec' : 'Clone C',
  49.     'klonecpp' : 'Clone C++',
  50.     'cmake' : 'CMake',
  51.     'cobol' : 'COBOL',
  52.     'coffeescript' : 'CoffeeScript',
  53.     'cfm' : 'ColdFusion',
  54.     'css' : 'CSS',
  55.     'cuesheet' : 'Cuesheet',
  56.     'd' : 'D',
  57.     'dcs' : 'DCS',
  58.     'delphi' : 'Delphi',
  59.     'oxygene' : 'Delphi Prism (Oxygene)',
  60.     'diff' : 'Diff',
  61.     'div' : 'DIV',
  62.     'dos' : 'DOS',
  63.     'dot' : 'DOT',
  64.     'e' : 'E',
  65.     'ecmascript' : 'ECMAScript',
  66.     'eiffel' : 'Eiffel',
  67.     'email' : 'Email',
  68.     'epc' : 'EPC',
  69.     'erlang' : 'Erlang',
  70.     'fsharp' : 'F#',
  71.     'falcon' : 'Falcon',
  72.     'fo' : 'FO' 'Language',
  73.     'f1' : 'Formula One',
  74.     'fortran' : 'Fortran',
  75.     'freebasic' : 'FreeBasic',
  76.     'gambas' : 'GAMBAS',
  77.     'gml' : 'Game Maker',
  78.     'gdb' : 'GDB',
  79.     'genero' : 'Genero',
  80.     'genie' : 'Genie',
  81.     'gettext' : 'GetText',
  82.     'go' : 'Go',
  83.     'groovy' : 'Groovy',
  84.     'gwbasic' : 'GwBasic',
  85.     'haskell' : 'Haskell',
  86.     'hicest' : 'HicEst',
  87.     'hq9plus' : 'HQ9 Plus',
  88.     'html4strict' : 'HTML',
  89.     'html5' : 'HTML 5',
  90.     'icon' : 'Icon',
  91.     'idl' : 'IDL',
  92.     'ini' : 'INI file',
  93.     'inno' : 'Inno Script',
  94.     'intercal' : 'INTERCAL',
  95.     'io' : 'IO',
  96.     'j' : 'J',
  97.     'java' : 'Java',
  98.     'java5' : 'Java 5',
  99.     'javascript' : 'JavaScript',
  100.     'jquery' : 'jQuery',
  101.     'kixtart' : 'KiXtart',
  102.     'latex' : 'Latex',
  103.     'lb' : 'Liberty BASIC',
  104.     'lsl2' : 'Linden Scripting',
  105.     'lisp' : 'Lisp',
  106.     'llvm' : 'LLVM',
  107.     'locobasic' : 'Loco Basic',
  108.     'logtalk' : 'Logtalk',
  109.     'lolcode' : 'LOL Code',
  110.     'lotusformulas' : 'Lotus Formulas',
  111.     'lotusscript' : 'Lotus Script',
  112.     'lscript' : 'LScript',
  113.     'lua' : 'Lua',
  114.     'm68k' : 'M68000 Assembler',
  115.     'magiksf' : 'MagikSF',
  116.     'make' : 'Make',
  117.     'mapbasic' : 'MapBasic',
  118.     'matlab' : 'MatLab',
  119.     'mirc' : 'mIRC',
  120.     'mmix' : 'MIX Assembler',
  121.     'modula2' : 'Modula 2',
  122.     'modula3' : 'Modula 3',
  123.     '68000devpac' : 'Motorola 68000 HiSoft Dev',
  124.     'mpasm' : 'MPASM',
  125.     'mxml' : 'MXML',
  126.     'mysql' : 'MySQL',
  127.     'newlisp' : 'newLISP',
  128.     'text' : 'None',
  129.     'nsis' : 'NullSoft Installer',
  130.     'oberon2' : 'Oberon 2',
  131.     'objeck' : 'Objeck Programming Langua',
  132.     'objc' : 'Objective C',
  133.     'ocaml-brief' : 'OCalm Brief',
  134.     'ocaml' : 'OCaml',
  135.     'pf' : 'OpenBSD PACKET FILTER',
  136.     'glsl' : 'OpenGL Shading',
  137.     'oobas' : 'Openoffice BASIC',
  138.     'oracle11' : 'Oracle 11',
  139.     'oracle8' : 'Oracle 8',
  140.     'oz' : 'Oz',
  141.     'pascal' : 'Pascal',
  142.     'pawn' : 'PAWN',
  143.     'pcre' : 'PCRE',
  144.     'per' : 'Per',
  145.     'perl' : 'Perl',
  146.     'perl6' : 'Perl 6',
  147.     'php' : 'PHP',
  148.     'php-brief' : 'PHP Brief',
  149.     'pic16' : 'Pic 16',
  150.     'pike' : 'Pike',
  151.     'pixelbender' : 'Pixel Bender',
  152.     'plsql' : 'PL/SQL',
  153.     'postgresql' : 'PostgreSQL',
  154.     'povray' : 'POV-Ray',
  155.     'powershell' : 'Power Shell',
  156.     'powerbuilder' : 'PowerBuilder',
  157.     'proftpd' : 'ProFTPd',
  158.     'progress' : 'Progress',
  159.     'prolog' : 'Prolog',
  160.     'properties' : 'Properties',
  161.     'providex' : 'ProvideX',
  162.     'purebasic' : 'PureBasic',
  163.     'pycon' : 'PyCon',
  164.     'python' : 'Python',
  165.     'q' : 'q/kdb+',
  166.     'qbasic' : 'QBasic',
  167.     'rsplus' : 'R',
  168.     'rails' : 'Rails',
  169.     'rebol' : 'REBOL',
  170.     'reg' : 'REG',
  171.     'robots' : 'Robots',
  172.     'rpmspec' : 'RPM Spec',
  173.     'ruby' : 'Ruby',
  174.     'gnuplot' : 'Ruby Gnuplot',
  175.     'sas' : 'SAS',
  176.     'scala' : 'Scala',
  177.     'scheme' : 'Scheme',
  178.     'scilab' : 'Scilab',
  179.     'sdlbasic' : 'SdlBasic',
  180.     'smalltalk' : 'Smalltalk',
  181.     'smarty' : 'Smarty',
  182.     'sql' : 'SQL',
  183.     'systemverilog' : 'SystemVerilog',
  184.     'tsql' : 'T-SQL',
  185.     'tcl' : 'TCL',
  186.     'teraterm' : 'Tera Term',
  187.     'thinbasic' : 'thinBasic',
  188.     'typoscript' : 'TypoScript',
  189.     'unicon' : 'Unicon',
  190.     'uscript' : 'UnrealScript',
  191.     'vala' : 'Vala',
  192.     'vbnet' : 'VB.NET',
  193.     'verilog' : 'VeriLog',
  194.     'vhdl' : 'VHDL',
  195.     'vim' : 'VIM',
  196.     'visualprolog' : 'Visual Pro Log',
  197.     'vb' : 'VisualBasic',
  198.     'visualfoxpro' : 'VisualFoxPro',
  199.     'whitespace' : 'WhiteSpace',
  200.     'whois' : 'WHOIS',
  201.     'winbatch' : 'Winbatch',
  202.     'xbasic' : 'XBasic',
  203.     'xml' : 'XML',
  204.     'xorg_conf' : 'Xorg Config',
  205.     'xpp' : 'XPP',
  206.     'yaml' : 'YAML',
  207.     'z80' : 'Z80 Assembler',
  208.     'zxbasic' : 'ZXBasic'
  209. }
  210.  
  211. EXPIRATION_FORMAT = {
  212.     'N' : 'Never',
  213.     '10M' : '10 Minutes',
  214.     '1H' : '1 Hour',
  215.     '1D' : '1 Day',
  216.     '1M' : '1 Month'
  217. }
  218.  
  219. KEY_URL = 'http://pastebin.com/api/api_login.php'
  220.  
  221. POST_URL = 'http://pastebin.com/api/api_post.php'
  222.  
  223. BAD_REQUEST = 'Bad API request'
  224.  
  225. class BadRequestError(Exception):
  226.     pass
  227.    
  228. class InvalidArgumentError(Exception):
  229.     pass    
  230.  
  231. class PasteBinComConnection(object):
  232.     def __init__(self, auth=None):
  233.         if auth:
  234.             self.name, self.password = auth
  235.    
  236.     def open(self):
  237.         if self.name and self.password:
  238.             data = urllib.urlencode([
  239.                 ('api_dev_key', DEV_KEY),
  240.                 ('api_user_name', self.name),
  241.                 ('api_user_password', self.password)])
  242.             response = urllib2.urlopen(KEY_URL, data).readline()
  243.             if response.find(BAD_REQUEST) == -1:
  244.                 self.session = response
  245.             else:
  246.                 self.__raiseError(response)
  247.         else:
  248.             self.session = ''
  249.        
  250.     def createPaste(self, code, name='', format='', isPrivate=0, expireDate='N'):
  251.         self.__checkSession()
  252.         if format and not format in FILE_FORMATS.keys():
  253.             raise InvalidArgumentError('This format is not supported')
  254.         if expireDate and not expireDate in EXPIRATION_FORMAT.keys():
  255.             raise InvalidArgumentError('This expiration type is not supported')
  256.            
  257.         data = [
  258.             ('api_option', 'paste'),
  259.             ('api_user_key', self.session),
  260.             ('api_paste_private', isPrivate),
  261.             ('api_paste_expire_date', expireDate),
  262.             ('api_dev_key', DEV_KEY),
  263.             ('api_paste_code', code)]
  264.         if name: data.append(('api_paste_name', name))
  265.         if format: data.append(('api_paste_format', format))
  266.         data = urllib.urlencode(data)
  267.        
  268.         response = urllib2.urlopen(POST_URL, data).readline()
  269.         if response.find(BAD_REQUEST) == -1:
  270.             return response
  271.         else:
  272.             self.__raiseError(response)
  273.        
  274.     def delete(self, paste):
  275.         self.__checkSession()
  276.         if not paste or not re.match(r'^\w{8}$', paste):
  277.             raise InvalidArgumentError('Invalid paste key')
  278.         data = urllib.urlencode([
  279.             ('api_option', 'delete'),
  280.             ('api_user_key', self.session),
  281.             ('api_dev_key', DEV_KEY),
  282.             ('api_paste_key', paste)])
  283.         response = urllib2.urlopen(POST_URL, data).readline()
  284.         if response.find(BAD_REQUEST) == -1:
  285.             return response
  286.         else:
  287.             self.__raiseError(response)
  288.        
  289.     def list(self, limit=1000):      
  290.         self.__checkSession()
  291.         data = urllib.urlencode([
  292.             ('api_option', 'list'),
  293.             ('api_user_key', self.session),
  294.             ('api_dev_key', DEV_KEY),
  295.             ('api_results_limit', limit)])
  296.         response = urllib2.urlopen(POST_URL, data).readlines()
  297.         if response[0].find(BAD_REQUEST) == -1:
  298.             response = '<pastes>{0}</pastes>'.format(''.join(response))
  299.             xml = minidom.parseString(response)
  300.             result = []
  301.             for infoNode in [node for node in xml.childNodes[0].childNodes if node.nodeType == node.ELEMENT_NODE]:
  302.                 info = {}
  303.                 for dataNode in [node for node in infoNode.childNodes if node.nodeType == node.ELEMENT_NODE]:
  304.                     if dataNode.hasChildNodes() and dataNode.childNodes[0].nodeType == dataNode.TEXT_NODE:
  305.                         info[dataNode.tagName] = dataNode.childNodes[0].data
  306.                 result.append(info)
  307.             return result
  308.         else:
  309.             self.__raiseError(response)
  310.        
  311.     def getUserInfo(self):
  312.         self.__checkSession()
  313.         data = urllib.urlencode([
  314.             ('api_option', 'userdetails'),
  315.             ('api_user_key', self.session),
  316.             ('api_dev_key', DEV_KEY)])
  317.         response = urllib2.urlopen(POST_URL, data).readlines()
  318.         if response[0].find(BAD_REQUEST) == -1:
  319.             info = {}
  320.             xml = minidom.parseString(''.join(response))
  321.             for node in [node for node in xml.childNodes[0].childNodes if node.nodeType == node.ELEMENT_NODE]:
  322.                 if node.hasChildNodes():
  323.                     info[node.tagName] = node.firstChild.data
  324.             return info
  325.         else:
  326.             self.__raiseError(response)
  327.        
  328.     def __raiseError(self, error):
  329.         match = re.match(r'^Bad API request,\s*(?P<error>.+)$', error)
  330.         if match:
  331.             raise BadRequestError(match)
  332.    
  333.     def __checkSession(self):
  334.         if not hasattr(self, 'session'):
  335.             raise RuntimeError('Session must be started before calling this operation')
Advertisement
Add Comment
Please, Sign In to add comment