Guest User

Untitled

a guest
Nov 16th, 2017
468
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.33 KB | None | 0 0
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3.  
  4. import os
  5. import sys
  6. import json
  7. import struct
  8. import subprocess
  9.  
  10. VERSION = '7.0'
  11.  
  12. try:
  13.         sys.stdin.buffer
  14.  
  15.         # Python 3.x version
  16.         # Read a message from stdin and decode it.
  17.         def getMessage():
  18.                 rawLength = sys.stdin.buffer.read(4)
  19.                 if len(rawLength) == 0:
  20.                         sys.exit(0)
  21.                 messageLength = struct.unpack('@I', rawLength)[0]
  22.                 message = sys.stdin.buffer.read(messageLength).decode('utf-8')
  23.                 return json.loads(message)
  24.  
  25.         # Send an encoded message to stdout
  26.         def sendMessage(messageContent):
  27.                 encodedContent = json.dumps(messageContent).encode('utf-8')
  28.                 encodedLength = struct.pack('@I', len(encodedContent))
  29.  
  30.                 sys.stdout.buffer.write(encodedLength)
  31.                 sys.stdout.buffer.write(encodedContent)
  32.                 sys.stdout.buffer.flush()
  33.  
  34. except AttributeError:
  35.         # Python 2.x version (if sys.stdin.buffer is not defined)
  36.         # Read a message from stdin and decode it.
  37.         def getMessage():
  38.                 rawLength = sys.stdin.read(4)
  39.                 if len(rawLength) == 0:
  40.                         sys.exit(0)
  41.                 messageLength = struct.unpack('@I', rawLength)[0]
  42.                 message = sys.stdin.read(messageLength)
  43.                 return json.loads(message)
  44.  
  45.         # Send an encoded message to stdout
  46.         def sendMessage(messageContent):
  47.                 encodedContent = json.dumps(messageContent)
  48.                 encodedLength = struct.pack('@I', len(encodedContent))
  49.  
  50.                 sys.stdout.write(encodedLength)
  51.                 sys.stdout.write(encodedContent)
  52.                 sys.stdout.flush()
  53.  
  54.  
  55. def install():
  56.         home_path = os.getenv('HOME')
  57.  
  58.         manifest = {
  59.                 'name': 'open_with',
  60.                 'description': 'Open With native host',
  61.                 'path': os.path.realpath(__file__),
  62.                 'type': 'stdio',
  63.         }
  64.         locations = {
  65.                 'chrome': os.path.join(home_path, '.config', 'google-chrome', 'NativeMessagingHosts'),
  66.                 'chromium': os.path.join(home_path, '.config', 'chromium', 'NativeMessagingHosts'),
  67.                 'firefox': os.path.join(home_path, '.mozilla', 'native-messaging-hosts'),
  68.         }
  69.         filename = 'open_with.json'
  70.  
  71.         for browser, location in locations.items():
  72.                 if os.path.exists(os.path.dirname(location)):
  73.                         if not os.path.exists(location):
  74.                                 os.mkdir(location)
  75.  
  76.                         browser_manifest = manifest.copy()
  77.                         if browser == 'firefox':
  78.                                 browser_manifest['allowed_extensions'] = ['[email protected]']
  79.                         else:
  80.                                 browser_manifest['allowed_origins'] = ['chrome-extension://cogjlncmljjnjpbgppagklanlcbchlno/']
  81.  
  82.                         with open(os.path.join(location, filename), 'w') as file:
  83.                                 file.write(
  84.                                         json.dumps(browser_manifest, indent=2, separators=(',', ': '), sort_keys=True).replace('  ', '\t') + '\n'
  85.                                 )
  86.  
  87.  
  88. def _read_desktop_file(path):
  89.         with open(path, 'r') as desktop_file:
  90.                 current_section = None
  91.                 name = None
  92.                 command = None
  93.                 for line in desktop_file:
  94.                         if line[0] == '[':
  95.                                 current_section = line[1:-2]
  96.                         if current_section != 'Desktop Entry':
  97.                                 continue
  98.  
  99.                         if line.startswith('Name='):
  100.                                 name = line[5:].strip()
  101.                         elif line.startswith('Exec='):
  102.                                 command = line[5:].strip()
  103.  
  104.                 return {
  105.                         'name': name,
  106.                         'command': command
  107.                 }
  108.  
  109.  
  110. def find_browsers():
  111.         apps = [
  112.                 'Chrome',
  113.                 'Chromium',
  114.                 'chromium-browser',
  115.                 'firefox',
  116.                 'Firefox',
  117.                 'Google Chrome',
  118.                 'google-chrome',
  119.                 'opera',
  120.                 'Opera',
  121.                 'SeaMonkey',
  122.                 'seamonkey',
  123.         ]
  124.         paths = [
  125.                 os.path.join(os.getenv('HOME'), '.local/share/applications'),
  126.                 '/usr/local/share/applications',
  127.                 '/usr/share/applications'
  128.         ]
  129.         suffix = '.desktop'
  130.  
  131.         results = []
  132.         for p in paths:
  133.                 for a in apps:
  134.                         fp = os.path.join(p, a) + suffix
  135.                         if os.path.exists(fp):
  136.                                 results.append(_read_desktop_file(fp))
  137.         return results
  138.  
  139.  
  140. def listen():
  141.         receivedMessage = getMessage()
  142.         if receivedMessage == 'ping':
  143.                 sendMessage({
  144.                         'version': VERSION,
  145.                         'file': os.path.realpath(__file__)
  146.                 })
  147.         elif receivedMessage == 'find':
  148.                 sendMessage(find_browsers())
  149.         else:
  150.                 for k, v in os.environ.items():
  151.                         if k.startswith('MOZ_'):
  152.                                 try:
  153.                                         os.unsetenv(k)
  154.                                 except:
  155.                                         os.environ[k] = ''
  156.  
  157.                 devnull = open(os.devnull, 'w')
  158.                 subprocess.Popen(receivedMessage, stdout=devnull, stderr=devnull)
  159.                 sendMessage(None)
  160.  
  161.  
  162. if __name__ == '__main__':
  163.         if len(sys.argv) == 2:
  164.                 if sys.argv[1] == 'install':
  165.                         install()
  166.                         sys.exit(0)
  167.                 elif sys.argv[1] == 'find_browsers':
  168.                         print(find_browsers())
  169.                         sys.exit(0)
  170.  
  171.         if '[email protected]' in sys.argv or 'chrome-extension://cogjlncmljjnjpbgppagklanlcbchlno/' in sys.argv:
  172.                 listen()
  173.                 sys.exit(0)
  174.  
  175.         print('Open With native helper, version %s.' % VERSION)
Advertisement
Add Comment
Please, Sign In to add comment