Advertisement
tzanany

SubSceneClient

Dec 20th, 2013
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.13 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #-*- coding:utf-8 -*-
  3. ########################################################
  4. # Name: Subscene Client
  5. # Site: http://RealGame.co.il
  6. __author__ = 'RealGame (Tomer Zait)'
  7. __license__ = 'GPL v3'
  8. __version__ = '1.0.0'
  9. __email__ = 'realgam3@gmail.com'
  10. ########################################################
  11.  
  12. from re import findall, DOTALL
  13. from requests import get
  14. from argparse import ArgumentParser
  15. from os import path
  16. from sys import argv, exit
  17.  
  18. ########################################################
  19. #Import PyQt4
  20. qt_error = False
  21. try:
  22.     from PyQt4.QtCore import *
  23.     from PyQt4.QtGui import *
  24.  
  25.     class DroppableLabel(QLabel):
  26.         fileDropped = pyqtSignal(list)
  27.  
  28.         def __init__(self, type, parent=None):
  29.             super(DroppableLabel, self).__init__(parent)
  30.             self.setAcceptDrops(True)
  31.  
  32.         def dragEnterEvent(self, event):
  33.             if event.mimeData().hasUrls:
  34.                 event.accept()
  35.             else:
  36.                 event.ignore()
  37.  
  38.         def dragMoveEvent(self, event):
  39.             if event.mimeData().hasUrls:
  40.                 event.setDropAction(Qt.CopyAction)
  41.                 event.accept()
  42.             else:
  43.                 event.ignore()
  44.  
  45.         def dropEvent(self, event):
  46.             if event.mimeData().hasUrls:
  47.                 event.setDropAction(Qt.CopyAction)
  48.                 event.accept()
  49.                 links = []
  50.                 for url in event.mimeData().urls():
  51.                     links.append(str(url.toLocalFile()))
  52.  
  53.                 self.fileDropped.emit(links)
  54.             else:
  55.                 event.ignore()
  56.  
  57.     class DroppableWidget(QWidget):
  58.         def __init__(self, parent=None):
  59.             super(DroppableWidget, self).__init__(parent)
  60.  
  61.             self.label = DroppableLabel(self)
  62.             self.label.fileDropped.connect(self.on_label_fileDropped)
  63.             self.label.setText("Please Drop Files / Directories.")
  64.             self.label.setMinimumSize(QSize(40, 100))
  65.  
  66.             self.verticalLayout = QVBoxLayout(self)
  67.             self.verticalLayout.addWidget(self.label)
  68.             self.verticalLayout.setMargin(0)
  69.  
  70.         @pyqtSlot(list)
  71.         def on_label_fileDropped(self, fileNames):
  72.             droppedFiles = [fileName for fileName in fileNames if path.exists(fileName)]
  73.             if droppedFiles:
  74.                 downloadFiles = list()
  75.  
  76.                 for file_path in droppedFiles:
  77.                     down_file = download_subtitle(file_path, SUB_LANG)
  78.                     if down_file:
  79.                         print down_file
  80.                         downloadFiles.append(down_file)
  81.  
  82.                 if downloadFiles:
  83.                     QMessageBox.about(self, "Downloaded Files", "\r\n".join(downloadFiles), )
  84. except ImportError:
  85.     qt_error = True
  86. ########################################################
  87.  
  88. #Base_URL
  89. BASE_URL = 'http://subscene.com'
  90. #HTTP Headers
  91. HEADERS = {
  92.     'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0'
  93. }
  94. #Regex String To Search
  95. REGEX_SEARCH = \
  96. r'<tr>\r\n' +\
  97. '\t+<td class="\w\d">\r\n' +\
  98. '\t+<a href="(.*?)">\r\n' +\
  99. '\t+<div class="visited">\r\n' +\
  100. '\t+<span class=".*?">\r\n\t*(.*?)\r\n\t+</span>\r\n' + \
  101. '\t+<span>\r\n\t*(.*?)\r\n\t+</span>\r\n' + \
  102. '\t+</div>\r\n.*?</tr>'
  103. #Subtitle Language
  104. SUB_LANG = 'English'
  105.  
  106.  
  107. def get_file_properties(full_path):
  108.     #File Properties Dictionary
  109.     properties = {
  110.         'base_dir': None,
  111.         'release_name': None
  112.     }
  113.  
  114.     #If Is File Path
  115.     if path.isfile(full_path):
  116.         properties['base_dir'] = path.dirname(full_path)
  117.         properties['release_name'] = path.splitext(path.basename(full_path))[0]
  118.     else:
  119.         properties['base_dir'] = full_path
  120.         properties['release_name'] = path.basename(full_path)
  121.  
  122.     properties['release_name'] = properties['release_name'].lower()
  123.     return properties
  124.  
  125.  
  126. def download_file(url, base_dir=''):
  127.     r = get(url, headers=HEADERS)
  128.     local_filename = findall(r'filename=(.*)', r.headers['content-disposition'])[0]
  129.  
  130.     with open(path.join(base_dir, local_filename), 'wb') as f:
  131.         for chunk in r.iter_content(chunk_size=1024):
  132.             # filter out keep-alive new chunks
  133.             if chunk:
  134.                 f.write(chunk)
  135.                 f.flush()
  136.     return local_filename
  137.  
  138.  
  139. def download_subtitle(release_path, sub_lang):
  140.     props = get_file_properties(release_path)
  141.  
  142.     search_res = get('{base_url}/subtitles/release.aspx'.format(base_url=BASE_URL),
  143.                      params={'q': props['release_name']},
  144.                      headers=HEADERS).content
  145.  
  146.     results = findall(REGEX_SEARCH, search_res, DOTALL)
  147.     for res in results:
  148.         if (sub_lang in res[1].lower()) and (props['release_name'] in res[2].lower()):
  149.             subtitle_res = get("{base_url}{sub_url}".format(base_url=BASE_URL, sub_url=res[0]), headers=HEADERS)
  150.             sub_res = findall(r'<div class="download">.*?<a href="(.*?)".*?>.*?</a>.*?</div>',
  151.                               subtitle_res.content,
  152.                               DOTALL)[0]
  153.             return download_file(BASE_URL + sub_res, base_dir=props['base_dir'])
  154.  
  155.  
  156. def main():
  157.     global SUB_LANG
  158.     parser = ArgumentParser(description='Subscene Client')
  159.     parser.add_argument('-r', '--release', nargs='?', help='Release Full Path', required=False)
  160.     parser.add_argument('-l', '--language', nargs='?', help='Subtitle Language', required=False, default=SUB_LANG)
  161.     args = vars(parser.parse_args())
  162.  
  163.     #To Lower Case
  164.     SUB_LANG = args['language'].lower()
  165.     #Console VS Gui
  166.     if args['release']:
  167.         """
  168.            Console - Args
  169.        """
  170.         print download_subtitle(args['release'], args['language'])
  171.     else:
  172.         """
  173.            Gui - Drag & Drop
  174.        """
  175.         parser.print_help()
  176.         print
  177.  
  178.         if not qt_error:
  179.             app = QApplication(argv)
  180.             main = DroppableWidget()
  181.             main.show()
  182.             exit(app.exec_())
  183.         else:
  184.             print 'Error: Before Using The GUI, Please Install PyQt4.'
  185.             exit(1)
  186.  
  187. if __name__ == "__main__":
  188.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement