Advertisement
RayWilliams

SkyInstaller 1.1

Feb 25th, 2018
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.68 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Sun Feb 25 21:06:26 2018
  5.  
  6. @author: MacBook
  7. """
  8. import requests
  9. import os
  10. import sys
  11.  
  12. api_dev_key = 'd679fba2731eb2b81f080788e4ad0f6e'
  13. username = 'skyinstaller'
  14. password = 'skyinstaller'
  15.  
  16.  
  17. # PARAMS
  18. def paste(file_name,content,session=''):
  19.     global api_dev_key
  20.     paste_name = "#[PYLIB]#" + file_name
  21.     # PARAMS
  22.     data = str(content)
  23.     url = 'https://pastebin.com/api/api_post.php'
  24.     pastebin_vars = {'api_dev_key': api_dev_key,'api_paste_code': data,'api_user_key': session,'api_paste_private':'0',
  25.                  'api_option' : 'paste','api_paste_name': paste_name}
  26.  
  27.     r = requests.post(url,pastebin_vars)
  28.     return r.text
  29.  
  30. def login():
  31.     login_url = 'https://pastebin.com/api/api_login.php'
  32.     api_user_name = username
  33.     api_user_password = password
  34.     r = requests.post(login_url,{'api_dev_key':api_dev_key,'api_user_name':api_user_name,'api_user_password':api_user_password})
  35.     if r.ok:
  36.         return r.text
  37.     else:
  38.         return None
  39.    
  40. def get_list(session):
  41.     import xml.etree.ElementTree as ET
  42.     global api_dev_key
  43.     api_results_limit = 100;
  44.     list_url = 'https://pastebin.com/api/api_post.php';
  45.     r = requests.post(list_url,{'api_dev_key':api_dev_key, 'api_user_key':session, 'api_results_limit':api_results_limit, 'api_option': 'list'})
  46.     paste_list = r.text
  47.     #parse tree
  48.     t = "<root>" + paste_list + "</root>"
  49.     root = ET.fromstring(t)
  50.     content_list = []
  51.     for paste in root:
  52.         one_post = {}
  53.         for element in paste:
  54.             if element.tag.strip() == 'paste_key':
  55.                 one_post['key'] = str(element.text).strip()
  56.             elif element.tag.strip() == 'paste_title':
  57.                 one_post['title'] = str(element.text).strip()
  58.             elif element.tag.strip() == 'paste_size':
  59.                 one_post['size'] = str(element.text).strip()
  60.         content_list.append(one_post)
  61.     return content_list
  62.  
  63.  
  64. def paste_by_user(title,content,session=''):
  65.     if content is None:
  66.         content = ''
  67.     #print 'paste_by_user', title,content,session
  68.     paste_url = paste(file_name=title,content=content,session=session)
  69.     if paste_url.strip().startswith('http'):
  70.         return paste_url
  71.     return None
  72.  
  73. def get_content_from_key(key):
  74.     r = requests.get('https://pastebin.com/raw/' + str(key).strip())
  75.     return r.text
  76.  
  77. def get_content_from_url(url):
  78.     r = requests.get(url)
  79.     return r.text
  80.  
  81. def generate_project_structure(folderpath,suffix=['.py','.txt']):
  82.     root_file = {}
  83.     fname_content = {}
  84.     if folderpath.strip() == '.':
  85.         folderpath = os.path.abspath('.')
  86.     basefolder = os.path.basename(folderpath)
  87.     print "Project Structure"
  88.     print '#' * 10
  89.     for root, dirs, files in os.walk(folderpath):
  90.         filtered_files = []
  91.         for _file in files:
  92.             filename, file_extension = os.path.splitext(_file)
  93.             if file_extension.lower() in suffix:
  94.                 filtered_files.append(_file)
  95.                 path = os.path.join(root,_file)
  96.                 with open(path,'r') as f:
  97.                     fname_content[_file] = f.read()
  98.         root_file[root.replace(folderpath,basefolder)] = filtered_files
  99.         level = root.replace(folderpath, '').count(os.sep)
  100.         indent = ' ' * 4 * (level)
  101.         print('{}{}/'.format(indent, os.path.basename(root)))
  102.         subindent = ' ' * 4 * (level + 1)
  103.         for f in files:
  104.             sign = '[x]'
  105.             for fmt in suffix:
  106.                 if f.lower().endswith(fmt):
  107.                     sign = '[o]'
  108.                     break
  109.             print('{}{}{}'.format(subindent, f, sign))
  110.     return root_file, fname_content
  111.            
  112. def jsonify_content(root_file, fname_content):
  113.     import json
  114.     ret = {}
  115.     ret['rf'] = root_file
  116.     ret['fc'] = fname_content
  117.     output = json.dumps(ret)
  118.     return output
  119.  
  120. def push(folderpath,suffix=['.py','.txt']):
  121.     rf,fc = generate_project_structure(folderpath,suffix)
  122.     output = jsonify_content(rf,fc)
  123.     basefolder = os.path.basename(folderpath)
  124.     url = paste_by_user(basefolder,output)
  125.     if url is not None:
  126.         print 'created at:', url
  127.         return url
  128.     print 'failed to create'
  129.     return None
  130.  
  131. def get_resource(url,folderpath='.'):
  132.     import json
  133.     if url.startswith('http') and url.find('raw') < 0:
  134.         url = url.replace('https://pastebin.com/','https://pastebin.com/raw/').strip()
  135.     else:
  136.         url = 'https://pastebin.com/raw/' + url.strip()
  137.     content = get_content_from_url(url)
  138.     raw_dict = json.loads(content)
  139.     root_file = raw_dict['rf']
  140.     fname_content = raw_dict['fc']
  141.     return root_file,fname_content
  142.  
  143. def build(url,folderpath='.'):
  144.     if not os.path.exists(folderpath):
  145.         os.makedirs(folderpath)
  146.     rf,fc = get_resource(url,folderpath)
  147.     for folder_route,files_in_side in rf.iteritems():
  148.         full_folder_route = os.path.join(folderpath,folder_route)
  149.         if not os.path.exists(full_folder_route):
  150.             os.makedirs(full_folder_route)
  151.             print 'folder created:',full_folder_route
  152.         for f in files_in_side:
  153.             full_file_path = os.path.join(folderpath,folder_route,f)
  154.             if f not in fc.keys():
  155.                 raise Exception('FileContentMissing','Cannot find the content of file' + str(f))
  156.             content = fc[f]
  157.             content = content.encode("utf-8")
  158.             print 'file_path',full_file_path
  159.             with open(full_file_path,'w') as fw:
  160.                 fw.write(content)
  161.     print 'All done! Contents are located in ' + os.path.abspath(folderpath)
  162.  
  163. def parse_type_list(type_list_str):
  164.     types = type_list_str.split(',')
  165.     types_ = []
  166.     for t in types:
  167.         if not t.strip().startswith('.'):
  168.             types_.append('.' + t.strip())
  169.         else:
  170.             types_.append(t.strip())
  171.     return types_
  172.  
  173. def interactive_push():
  174.     print 'Please input the local folder you want to push to cloud.'
  175.     folder_path = raw_input('>')
  176.     while not os.path.isdir(folder_path):
  177.         print '{} is not a valid folder, please reinput the local folder.'.format(folder_path)
  178.         print '[example]/Users/Test/MyProject'
  179.         folder_path = raw_input('>')
  180.     folder_path = folder_path.strip()
  181.     print 'Please input the target text file extensions, separated by commar.'
  182.     print '[example] txt,py,md,xml'
  183.     list_str = raw_input('>')
  184.     type_list = parse_type_list(list_str)
  185.     print 'Please wait for seconds..'
  186.     push(folder_path,type_list)
  187.     return True
  188.  
  189. def interactive_pull():
  190.     print 'Please input the project pastebin key or url.'
  191.     url = raw_input('>')
  192.     if sys.platform == 'darwin' or sys.platform.startswith('win'):
  193.         print 'Please input the existing destination folder path.'
  194.         dest = raw_input('>')
  195.         while not os.path.isdir(dest):
  196.             print 'Destination folder path not found, please reinput.'
  197.             dest = raw_input('>')
  198.         print 'Please wait for seconds..'
  199.         build(url,dest)
  200.     else:
  201.         print 'Choose your current platform:\n[1]Android\n[2]Linux PC'
  202.         choice = raw_input('>')
  203.         choice = choice.strip()
  204.         while choice != '1' and choice != '2':
  205.             print 'Choose your current platform:\n[1]Android\n[2]Linux PC'
  206.             choice = raw_input('>')
  207.             choice = choice.strip()
  208.         if choice == '1':
  209.             default_root_path = '/storage/emulated/0/PyApps'
  210.             if not os.path.isdir(default_root_path):
  211.                 os.makedirs(default_root_path)
  212.             build(url,default_root_path)
  213.         elif choice == '2':
  214.             print 'Please input the existing destination folder path.'
  215.             dest = raw_input('>')
  216.             while not os.path.isdir(dest):
  217.                 print 'Destination folder path not found, please reinput.'
  218.                 dest = raw_input('>')
  219.                 print 'Please wait for seconds..'
  220.                 build(url,dest)
  221.     return True
  222.  
  223. def interactive_command():
  224.     print 'Please choose action:\n[1]Push/Upload\n[2]Pull/Download'
  225.     choice = raw_input('>')
  226.     if choice.strip() == '1':
  227.         return interactive_push()
  228.     elif choice.strip() == '2':
  229.         return interactive_pull()
  230.     return interactive_command()
  231.        
  232.  
  233. if __name__ == '__main__':
  234.     if len(sys.argv) == 1:
  235.         print '\n'
  236.         print 'Sky Installer 2.0'
  237.         print '\n'
  238.         print '#' * 20
  239.         print "You can upload/push your app to the cloud using:"
  240.         print '--push <app_folder> <type_list> or --upload <app_folder> <type_list>'
  241.         print "Or, you can download app from the cloud using:"
  242.         print '--pull <url> <destination_path> or --download <url> <destination_path>'
  243.         print '#' * 20
  244.         print '\n' * 2
  245.         print 'Examples:'
  246.         print './skyinstaller.py --push /Users/Test/MyLocalApp py,txt,md'
  247.         print './skyinstaller.py --pull https://pastebin.com/h3eeRJcP /Users/Test/MyApp'
  248.         #print 'You can create a file named ignore.txt to list the files you do not want to include'
  249.         print 'Happy Using!'
  250.         print '#' * 20
  251.         success = interactive_command()
  252.         if success:
  253.             print 'Successful.'
  254.        
  255.     if len(sys.argv) == 4:
  256.         if sys.argv[1].strip() == '--push' or sys.argv[1].strip() == '--upload':
  257.             #do the push
  258.             app_folder = sys.argv[2]
  259.             type_list = parse_type_list(sys.argv[3])
  260.             push(app_folder,type_list)
  261.         elif sys.argv[1].strip() == '--pull' or sys.argv[1].strip() == '--download':
  262.             #do the pull
  263.             url = sys.argv[2].strip()
  264.             dest = sys.argv[3].strip()
  265.             build(url,dest)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement