Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- #-*- coding:utf-8 -*-
- ########################################################
- # Name: Subscene Client
- # Site: http://RealGame.co.il
- __author__ = 'RealGame (Tomer Zait)'
- __license__ = 'GPL v3'
- __version__ = '1.0.0'
- __email__ = 'realgam3@gmail.com'
- ########################################################
- from re import findall, DOTALL
- from requests import get
- from argparse import ArgumentParser
- from os import path
- from sys import argv, exit
- ########################################################
- #Import PyQt4
- qt_error = False
- try:
- from PyQt4.QtCore import *
- from PyQt4.QtGui import *
- class DroppableLabel(QLabel):
- fileDropped = pyqtSignal(list)
- def __init__(self, type, parent=None):
- super(DroppableLabel, self).__init__(parent)
- self.setAcceptDrops(True)
- def dragEnterEvent(self, event):
- if event.mimeData().hasUrls:
- event.accept()
- else:
- event.ignore()
- def dragMoveEvent(self, event):
- if event.mimeData().hasUrls:
- event.setDropAction(Qt.CopyAction)
- event.accept()
- else:
- event.ignore()
- def dropEvent(self, event):
- if event.mimeData().hasUrls:
- event.setDropAction(Qt.CopyAction)
- event.accept()
- links = []
- for url in event.mimeData().urls():
- links.append(str(url.toLocalFile()))
- self.fileDropped.emit(links)
- else:
- event.ignore()
- class DroppableWidget(QWidget):
- def __init__(self, parent=None):
- super(DroppableWidget, self).__init__(parent)
- self.label = DroppableLabel(self)
- self.label.fileDropped.connect(self.on_label_fileDropped)
- self.label.setText("Please Drop Files / Directories.")
- self.label.setMinimumSize(QSize(40, 100))
- self.verticalLayout = QVBoxLayout(self)
- self.verticalLayout.addWidget(self.label)
- self.verticalLayout.setMargin(0)
- @pyqtSlot(list)
- def on_label_fileDropped(self, fileNames):
- droppedFiles = [fileName for fileName in fileNames if path.exists(fileName)]
- if droppedFiles:
- downloadFiles = list()
- for file_path in droppedFiles:
- down_file = download_subtitle(file_path, SUB_LANG)
- if down_file:
- print down_file
- downloadFiles.append(down_file)
- if downloadFiles:
- QMessageBox.about(self, "Downloaded Files", "\r\n".join(downloadFiles), )
- except ImportError:
- qt_error = True
- ########################################################
- #Base_URL
- BASE_URL = 'http://subscene.com'
- #HTTP Headers
- HEADERS = {
- 'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0'
- }
- #Regex String To Search
- REGEX_SEARCH = \
- r'<tr>\r\n' +\
- '\t+<td class="\w\d">\r\n' +\
- '\t+<a href="(.*?)">\r\n' +\
- '\t+<div class="visited">\r\n' +\
- '\t+<span class=".*?">\r\n\t*(.*?)\r\n\t+</span>\r\n' + \
- '\t+<span>\r\n\t*(.*?)\r\n\t+</span>\r\n' + \
- '\t+</div>\r\n.*?</tr>'
- #Subtitle Language
- SUB_LANG = 'English'
- def get_file_properties(full_path):
- #File Properties Dictionary
- properties = {
- 'base_dir': None,
- 'release_name': None
- }
- #If Is File Path
- if path.isfile(full_path):
- properties['base_dir'] = path.dirname(full_path)
- properties['release_name'] = path.splitext(path.basename(full_path))[0]
- else:
- properties['base_dir'] = full_path
- properties['release_name'] = path.basename(full_path)
- properties['release_name'] = properties['release_name'].lower()
- return properties
- def download_file(url, base_dir=''):
- r = get(url, headers=HEADERS)
- local_filename = findall(r'filename=(.*)', r.headers['content-disposition'])[0]
- with open(path.join(base_dir, local_filename), 'wb') as f:
- for chunk in r.iter_content(chunk_size=1024):
- # filter out keep-alive new chunks
- if chunk:
- f.write(chunk)
- f.flush()
- return local_filename
- def download_subtitle(release_path, sub_lang):
- props = get_file_properties(release_path)
- search_res = get('{base_url}/subtitles/release.aspx'.format(base_url=BASE_URL),
- params={'q': props['release_name']},
- headers=HEADERS).content
- results = findall(REGEX_SEARCH, search_res, DOTALL)
- for res in results:
- if (sub_lang in res[1].lower()) and (props['release_name'] in res[2].lower()):
- subtitle_res = get("{base_url}{sub_url}".format(base_url=BASE_URL, sub_url=res[0]), headers=HEADERS)
- sub_res = findall(r'<div class="download">.*?<a href="(.*?)".*?>.*?</a>.*?</div>',
- subtitle_res.content,
- DOTALL)[0]
- return download_file(BASE_URL + sub_res, base_dir=props['base_dir'])
- def main():
- global SUB_LANG
- parser = ArgumentParser(description='Subscene Client')
- parser.add_argument('-r', '--release', nargs='?', help='Release Full Path', required=False)
- parser.add_argument('-l', '--language', nargs='?', help='Subtitle Language', required=False, default=SUB_LANG)
- args = vars(parser.parse_args())
- #To Lower Case
- SUB_LANG = args['language'].lower()
- #Console VS Gui
- if args['release']:
- """
- Console - Args
- """
- print download_subtitle(args['release'], args['language'])
- else:
- """
- Gui - Drag & Drop
- """
- parser.print_help()
- print
- if not qt_error:
- app = QApplication(argv)
- main = DroppableWidget()
- main.show()
- exit(app.exec_())
- else:
- print 'Error: Before Using The GUI, Please Install PyQt4.'
- exit(1)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement