-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
378 lines (238 loc) · 12.7 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import os
from src.design_files.ui_mainWindow import Ui_MainWindow
from src.ui_utils import *
from src.utils import *
from src.scrapers import *
from datetime import datetime
# Global Variables
ROOT_DIR = f"{os.sep}".join(os.path.abspath(__file__).split(os.sep)[:-1])
## Global Functions
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
class MainApp(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
## Variables
self.settings = {}
self.movie_titles = []
self.show_titles = []
self.movies_and_shows = {}
self.eztv_scraper = EZTV(self)
self.threadpool = QThreadPool()
## Setup functions
self.initial_setup()
self.initial_ui_setup()
self.setup_ui_connections()
def initial_setup(self):
## Setup the icons
icon = QIcon()
icon.addFile(resource_path("src/imgs/scrape.png"), QSize(), QIcon.Normal, QIcon.Off)
self.ui.start_scraping_button.setIcon(icon)
icon.addFile(resource_path("src/imgs/stop.png"), QSize(), QIcon.Normal, QIcon.Off)
self.ui.stop_scraping_button.setIcon(icon)
icon = QIcon()
icon.addFile(resource_path("src/imgs/torrent_icon.png"), QSize(), QIcon.Normal, QIcon.Off)
self.setWindowIcon(icon)
## Load the settings
with open(resource_path("src/settings.json"), "r") as fo: self.settings = json.load(fo)
## Load the movie titles
with open(resource_path("src/title_scrapers/yifi_movie_titles.json"), "r") as fo: self.movie_titles = list(json.load(fo).keys())
with open(resource_path("src/title_scrapers/tvmaze_show_titles.json"), 'r') as fo: self.show_titles = list(json.load(fo).keys())
suggestions_list = self.movie_titles + self.show_titles
movie_completer = QCompleter(suggestions_list, self)
movie_completer.setCaseSensitivity(Qt.CaseInsensitive)
movie_completer.setMaxVisibleItems(10)
movie_completer.setFilterMode(Qt.MatchContains)
self.ui.keyword_edit.setCompleter(movie_completer)
## Load all the locally available movie and show titles
with open(resource_path("src/title_scrapers/yifi_movie_titles.json"), "r") as fo: self.movies_and_shows.update(json.load(fo))
with open(resource_path("src/title_scrapers/tvmaze_show_titles.json"), 'r') as fo: self.movies_and_shows.update(json.load(fo))
## Load the previous data to table
with open(resource_path("src/results.json"), "r") as fo: previous_movie_data = json.load(fo)
self.tabulate_data(previous_movie_data)
## Load the title from previous result
self.ui.currnet_database_label.setText(self.settings['previous_title'])
self.ui.more_information_button.setText(f"More Information on {self.settings['previous_title']}")
def initial_ui_setup(self):
## Verify root path
if not os.path.isdir(ROOT_DIR): show_error(self, "Could not get the root path. Report this as a bug and try Re-Installing the Application.")
## Remove focus from the keyword edit
if self.settings['keywordFocus']: self.ui.start_scraping_button.setFocus()
## Clear the keyword and search term edits
self.ui.keyword_edit.clear()
self.ui.search_term_edit.clear()
## Set the default values for the season and episode spin boxes
self.ui.season_spin.setValue(1)
self.ui.episode_spin.setValue(1)
## Set the scraper combo values
scrapers = list(dict(self.settings['tv-scrapers']).keys()) + ["All Sites"]
self.ui.scrape_from_combo.setCurrentIndex(0)
self.ui.scrape_from_combo.clear()
self.ui.scrape_from_combo.addItems(scrapers)
## Set up the first page on stack
self.ui.stackedWidget.setCurrentIndex(0)
## Initial search check state
self.ui.search_term_check.setChecked(False)
self.ui.search_term_edit.setEnabled(False)
## Reset the name of the more option button
self.ui.more_information_button.setText("More Information")
## Setup the default auto scroll state
self.ui.auto_scroll.setChecked(True)
## Setup table column resize policy
header = self.ui.results_table.horizontalHeader()
header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
def setup_ui_connections(self):
## Combo Boxes
self.ui.scrape_for_combo.currentIndexChanged.connect(self.change_scrapers_in_combo)
## buttons
self.ui.back_button.clicked.connect(self.back_button_command)
self.ui.display_all_data_check.clicked.connect(self.display_all_data_handler)
self.ui.start_scraping_button.clicked.connect(self.start_scraping_operation)
## Combo box
self.ui.show_status_check.toggled.connect(self.show_details_handler)
def change_scrapers_in_combo(self):
"""This function changes the scraper options available for use when changing the 'scrape for' combo box options"""
if self.ui.scrape_for_combo.currentText().lower() == "Tv-Shows".lower():
log("[APPLICATION] Changed to the scrape for option to TV-Show")
scrapers = list(dict(self.settings['tv-scrapers']).keys()) + ["All Sites"]
self.ui.scrape_from_combo.clear()
self.ui.scrape_from_combo.addItems(scrapers)
elif self.ui.scrape_for_combo.currentText().lower() == "Movies".lower():
log("[APPLICATION] Changed to the scrape for option to Movies")
scrapers = list(dict(self.settings['movie-scrapers']).keys()) + ["All Sites"]
self.ui.scrape_from_combo.clear()
self.ui.scrape_from_combo.addItems(scrapers)
elif self.ui.scrape_for_combo.currentText().lower() == "Subtitles".lower():
log("[APPLICATION] Changed to the scrape for option to Subtitles")
scrapers = list(dict(self.settings['subtitle-scrapers']).keys()) + ["All Sites"]
self.ui.scrape_from_combo.clear()
self.ui.scrape_from_combo.addItems(scrapers)
elif self.ui.scrape_for_combo.currentText().lower() == "Soccer-Streams".lower():
log("[APPLICATION] Changed to the scrape for option to Soccer-Streams")
scrapers = list(dict(self.settings['soccer-scrapers']).keys()) + ["All Sites"]
self.ui.scrape_from_combo.clear()
self.ui.scrape_from_combo.addItems(scrapers)
elif self.ui.scrape_for_combo.currentText().lower() == "Anime".lower():
log("[APPLICATION] Changed to the scrape for option to Anime")
scrapers = list(dict(self.settings['anime-scrapers']).keys()) + ["All Sites"]
self.ui.scrape_from_combo.clear()
self.ui.scrape_from_combo.addItems(scrapers)
elif self.ui.scrape_for_combo.currentText().lower() == "General".lower():
log("[APPLICATION] Changed to the scrape for option to General")
scrapers = list(dict(self.settings['general-scrapers']).keys()) + ["All Sites"]
self.ui.scrape_from_combo.clear()
self.ui.scrape_from_combo.addItems(scrapers)
def show_details_handler(self):
if self.ui.show_status_check.isChecked():
self.ui.stackedWidget.setCurrentIndex(1)
else:
self.ui.stackedWidget.setCurrentIndex(0)
def back_button_command(self):
self.ui.stackedWidget.setCurrentIndex(0)
self.ui.show_status_check.setChecked(False)
def display_all_data_handler(self):
## Disable the relevant widgets
if self.ui.display_all_data_check.isChecked():
self.ui.season_check.setEnabled(False)
self.ui.season_spin.setEnabled(False)
self.ui.episode_check.setEnabled(False)
self.ui.episode_spin.setEnabled(False)
## TODO: Show all the data scraped in the table
else:
self.ui.season_check.setEnabled(True)
self.ui.season_spin.setEnabled(True)
self.ui.episode_check.setEnabled(True)
self.ui.episode_spin.setEnabled(True)
## TODO: Clear all the data from the table
def log_to_widget(self, message: str):
log_text = f">>> [{datetime.now().strftime('%H:%M:%S')}] {str(message).title().strip()}\n"
if self.ui.auto_scroll.isChecked():
self.ui.log_text.moveCursor(QTextCursor.End)
self.ui.log_text.insertPlainText(log_text)
else:
self.ui.log_text.insertPlainText(log_text)
def update_current_database_title(self, title: str):
self.settings['previous_title'] = title
with open(os.path.join(ROOT_DIR, "src/settings.json"), "w") as fo:
json.dump(self.settings, fo, indent=2)
self.ui.currnet_database_label.setText(self.settings['previous_title'])
self.ui.more_information_button.setText(f"More Information on {self.settings['previous_title']}")
def tabulate_data(self, data: list):
## Clear the table
self.ui.results_table.setRowCount(0)
for item in data:
## populate the data
table = self.ui.results_table
rowPosition = table.rowCount()
table.insertRow(rowPosition)
## Set column data
table.setItem(rowPosition, 0, QTableWidgetItem(str(item['title']))) # Title
table.setItem(rowPosition, 1, QTableWidgetItem(str(item['size_bytes']))) # Size
table.setItem(rowPosition, 2, QTableWidgetItem(str(item['seeds']))) # Seeds
table.setItem(rowPosition, 3, QTableWidgetItem(str(item['magnet_url']))) # Magnet link
self.ui.start_scraping_button.setEnabled(True)
def finished_scraping(self):
self.ui.show_status_check.toggle()
self.ui.start_scraping_button.setEnabled(True)
def start_scraping_operation(self):
## Get the title
search_keyword = self.ui.keyword_edit.text()
search_imdb_id = self.movies_and_shows.get(search_keyword)
## Get the selected scraper
scrape_from = self.ui.scrape_from_combo.currentText()
print(scrape_from)
## Choose the right scraper
if scrape_from == "EZTV":
if search_imdb_id is not None:
## Move the page
self.ui.show_status_check.toggle()
## Disable the widgets
self.ui.start_scraping_button.setEnabled(False)
## Start the search queue
worker = SigWorker(lambda sigs: self.eztv_scraper.get_show_by_imdb_id(search_imdb_id, sigs, search_keyword))
worker.signals.message_signal.connect(put_toast)
worker.signals.log_data.connect(self.log_to_widget)
worker.signals.finished.connect(self.finished_scraping)
worker.signals.finished_tabulate.connect(lambda table_data: self.tabulate_data(sort_filter(table_data)))
worker.signals.finished_tabulate.connect(lambda: self.update_current_database_title(search_keyword.title()))
## Start thread
self.threadpool.start(worker)
else:
## Move the page
self.ui.show_status_check.toggle()
## Disable the widgets
self.ui.start_scraping_button.setEnabled(False)
## Start the search queue
worker = SigWorker(lambda sigs: self.eztv_scraper.get_show_by_name(search_keyword, sigs))
worker.signals.message_signal.connect(put_toast)
worker.signals.log_data.connect(self.log_to_widget)
worker.signals.finished.connect(self.finished_scraping)
worker.signals.finished_tabulate.connect(lambda table_data: self.tabulate_data(sort_filter(table_data)))
worker.signals.finished_tabulate.connect(lambda: self.update_current_database_title(search_keyword.title()))
## Start thread
self.threadpool.start(worker)
class SigWorker(QRunnable):
def __init__(self, func, *args, **kwargs):
super(SigWorker, self).__init__()
self.func = func
self.args = args
self.kwargs = kwargs
self.signals = WorkerSignals()
@Slot()
def run(self):
self.func(self.signals)
if __name__ == "__main__":
w = QApplication([])
app = MainApp()
app.show()
w.exec()