forked from evilhero/harpoon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
harpoon.py
executable file
·1410 lines (1214 loc) · 76.4 KB
/
harpoon.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# This file is part of Harpoon.
#
# Harpoon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Harpoon is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Harpoon. If not, see <http://www.gnu.org/licenses/>.
import sys, os
sys.path.insert(1, os.path.join(os.path.dirname(__file__), 'lib'))
import Queue
import subprocess
import optparse
import re
import time
import json
import requests
import datetime
import socket as checksocket
from contextlib import closing
import hashlib
import bencode
import threading
import shutil
from StringIO import StringIO
import harpoon
from harpoon import rtorrent, sabnzbd, unrar, logger, sonarr, radarr, plex, sickrage, mylar, lazylibrarian, lidarr, webStart
from harpoon import HQUEUE as HQUEUE
from harpoon import config
from harpoon import hashfile as hf
from harpoon.threadedtcp import ThreadedTCPRequestHandler, ThreadedTCPServer
from apscheduler.scheduler import Scheduler
#global variables
#this is required here to get the log path below
class QueueR(object):
def __init__(self):
#accept parser options for cli usage
description = ("Harpoon. "
"A python-based CLI daemon application that will monitor a remote location "
"(ie.seedbox) & then download from the remote location to the local "
"destination which is running an automation client. "
"Unrar, cleanup and client-side post-processing as required. "
"Also supports direct dropping of .torrent files into a watch directory. "
"Supported client-side applications: "
"Sonarr, Radarr, Lidarr, Mylar, LazyLibrarian, SickRage")
self.server = None
self.server_thread = None
self.ARGS = sys.argv[:]
self.FULL_PATH = os.path.abspath(sys.executable)
parser = optparse.OptionParser(description=description)
parser.add_option('-a', '--add', dest='add', help='Specify a filename to snatch from specified torrent client when monitor is running already.')
parser.add_option('-s', '--hash', dest='hash', help='Specify a HASH to snatch from specified torrent client.')
parser.add_option('-l', '--label', dest='label', help='For use ONLY with -t, specify a label that the HASH has that harpoon can check against when querying the torrent client.')
parser.add_option('-t', '--exists', dest='exists', action='store_true', help='In combination with -s (Specify a HASH) & -l (Specify a label) with this enabled and it will not download the torrent (it must exist in the designated location already')
parser.add_option('-f', '--file', dest='file', help='Specify an exact filename to snatch from specified torrent client. (Will do recursive if more than one file)')
parser.add_option('-i', '--issueid', dest='issueid', help='In conjunction with -s,-l allows you to specify an exact issueid post-process against (MYLAR ONLY).')
parser.add_option('-b', '--partial', dest='partial', action='store_true', help='Grab the torrent regardless of completion status (for cherrypicked torrents)')
parser.add_option('-m', '--monitor', dest='monitor', action='store_true', help='Monitor a designated file location for new files to harpoon.')
parser.add_option('-d', '--daemon', dest='daemon', action='store_true', help='Daemonize the complete program so it runs in the background.')
parser.add_option('-p', '--pidfile', dest='pidfile', help='specify a pidfile location to store pidfile for daemon usage.')
(options, args) = parser.parse_args()
self.restart = False
if options.daemon:
if sys.platform == 'win32':
print "Daemonize not supported under Windows, starting normally"
self.daemon = False
else:
self.daemon = True
options.monitor = True
else:
self.daemon = False
if options.monitor:
self.monitor = True
else:
self.monitor = False
if options.exists:
self.exists = True
else:
self.exists = False
if options.issueid:
self.issueid = options.issueid
else:
self.issueid = None
if options.partial:
self.partial = True
else:
self.partial = False
if options.pidfile:
self.pidfile = str(options.pidfile)
# If the pidfile already exists, harpoon may still be running, so exit
if os.path.exists(self.pidfile):
sys.exit("PID file '" + self.pidfile + "' already exists. Exiting.")
# The pidfile is only useful in daemon mode, make sure we can write the file properly
if self.daemon:
self.createpid = True
try:
file(self.pidfile, 'w').write("pid\n")
except IOError, e:
raise SystemExit("Unable to write PID file: %s [%d]" % (e.strerror, e.errno))
else:
self.createpid = False
logger.warn("Not running in daemon mode. PID file creation disabled.")
else:
self.pidfile = None
self.createpid = False
self.file = options.file
self.hash = options.hash
self.working_hash = None
self.hash_reload = False
self.not_loaded = 0
self.extensions = ['mkv', 'avi', 'mp4', 'mpg', 'mov', 'cbr', 'cbz', 'flac', 'mp3', 'alac', 'epub', 'mobi', 'pdf', 'azw3', '4a', 'm4b', 'm4a']
if config.GENERAL['newextensions'] is not None:
for x in newextensions.split(","):
if x != "":
self.extensions.append(x)
if options.daemon:
self.daemonize()
logger.info("Initializing background worker thread for queue manipulation.")
#for multiprocessing (would cause some problems)
#self.SNQUEUE = Queue()
#harpoon.SNPOOL = Process(target=self.worker_main, args=(self.SNQUEUE,))
#harpoon.SNPOOL.daemon = True
#harpoon.SNPOOL.start()
#for threading
self.HQUEUE = HQUEUE
self.SNPOOL = threading.Thread(target=self.worker_main, args=(self.HQUEUE,))
self.SNPOOL.setdaemon = True
self.SNPOOL.start()
harpoon.MAINTHREAD = threading.current_thread()
logger.debug("Threads: %s" % threading.enumerate())
logger.info('TV-Client set to : %s' % config.GENERAL['tv_choice'])
if self.daemon is True:
#if it's daemonized, fire up the soccket listener to listen for add requests.
logger.info('[HARPOON] Initializing the API-AWARE portion of Harpoon.')
#socketlisten.listentome(self.SNQUEUE,)
#sockme = threading.Thread(target=socketlisten.listentome, args=(self.SNQUEUE,))
#sockme.setdaemon = True
#sockme.start()
HOST, PORT = "localhost", 50007
port_open = True
while port_open:
with closing(checksocket.socket(checksocket.AF_INET, checksocket.SOCK_STREAM)) as sock:
res = sock.connect_ex((HOST, PORT))
if res == 0:
pass
else:
logger.debug('[API] Socket available. Continuing.')
port_open = False
time.sleep(2)
self.server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
logger.debug('Class Server: %s' % self.server)
server_thread = threading.Thread(target=self.server.serve_forever)
logger.debug('Server Thread: %s' % server_thread)
server_thread.daemon = True
server_thread.start()
logger.info('Started...')
if self.monitor:
self.SCHED = Scheduler()
logger.info('Setting directory scanner to monitor %s every 2 minutes for new files to harpoon' % config.GENERAL['torrentfile_dir'])
self.scansched = self.ScheduleIt(self.HQUEUE, self.working_hash)
job = self.SCHED.add_interval_job(func=self.scansched.Scanner, minutes=2)
# start the scheduler now
self.SCHED.start()
#run the scanner immediately on startup.
self.scansched.Scanner()
elif self.file is not None:
logger.info('Adding file to queue via FILE %s [label:%s]' % (self.file, options.label))
self.HQUEUE.put({'mode': 'file-add',
'item': self.file,
'label': options.label})
elif self.hash is not None:
logger.info('Adding file to queue via HASH %s [label:%s]' % (self.hash, options.label))
self.HQUEUE.put({'mode': 'hash-add',
'item': self.hash,
'label': options.label})
else:
logger.info('Not enough information given - specify hash / filename')
return
if options.add:
logger.info('Adding file to queue %s' % options.add)
self.HQUEUE.put(options.add)
return
logger.info('Web: %s' % config.WEB)
if config.WEB['http_enable']:
logger.debug("Starting web server")
webStart.initialize(options=config.WEB, basepath=harpoon.DATADIR, parent=self)
while True:
if self.restart:
logger.info('Restarting')
try:
popen_list = [self.FULL_PATH]
popen_list += self.ARGS
logger.debug("Args: %s" % (popen_list))
if self.server:
self.server.shutdown()
self.server.server_close()
while not self.server.is_shut_down():
logger.debug("Running? %s" % self.server.is_running())
time.sleep(1)
os.remove(self.pidfile)
po = subprocess.Popen(popen_list, cwd=os.getcwd(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
logger.debug("Process: %s" % po.poll())
os._exit(0)
except Exception as e:
logger.debug("Failed to restart: %s" % e)
else:
self.worker_main(self.HQUEUE)
def worker_main(self, queue):
while True:
if self.monitor:
if not len(self.SCHED.get_jobs()):
logger.debug('Restarting Scanner Job')
job = self.SCHED.add_interval_job(func=self.scansched.Scanner, minutes=2)
self.SCHED.start()
if self.hash_reload is False:
if queue.empty():
#do a time.sleep here so we don't use 100% cpu
time.sleep(5)
return #continue
item = queue.get(True)
if item['mode'] == 'exit':
logger.info('Cleaning up workers for shutdown')
return self.shutdown()
if item['item'] == self.working_hash and item['mode'] == 'current':
#file is currently being processed...ignore.
logger.warn('hash item from queue ' + item['item'] + ' is already being processed as [' + str(self.working_hash) + ']')
return #continue
else:
logger.info('_hash to [' + item['item'] + ']')
queue.ckupdate(item['item'], {'stage': 'current'})
# ck = [x for x in queue.ckqueue() if x['hash'] == item['item']]
# if not ck:
# queue.ckappend({'hash': item['item'],
# 'stage': 'current'})
self.working_hash = item['item']
logger.info('[' + item['mode'] +'] Now loading from queue: %s (%s items remaining in queue)' % (item['item'], queue.qsize()))
else:
self.hash_reload = False
# Check for client type. If no client set, assume rtorrent.
if 'client' not in item.keys():
item['client'] = 'rtorrent'
#Sonarr stores torrent names without the extension which throws things off.
#use the below code to reference Sonarr to poll the history and get the hash from the given torrentid
if item['client'] == 'sabnzbd':
sa_params = {}
sa_params['nzo_id'] = item['item']
sa_params['apikey'] = config.SAB['sab_apikey']
try:
sab = sabnzbd.SABnzbd(params=sa_params, saburl=config.SAB['sab_url'])
snstat = sab.query()
except Exception as e:
logger.info('ERROR - %s' %e)
snstat = None
else:
try:
if any([item['mode'] == 'file', item['mode'] == 'file-add']):
logger.info('sending to rtorrent as file...')
rt = rtorrent.RTorrent(file=item['item'], label=item['label'], partial=self.partial)
else:
logger.info('checking rtorrent...')
rt = rtorrent.RTorrent(hash=item['item'], label=item['label'])
snstat = rt.main()
except Exception as e:
logger.info('ERROR - %s' % e)
snstat = None
#import torrent.clients.deluge as delu
#dp = delu.TorrentClient()
#if not dp.connect():
# logger.warn('Not connected to Deluge!')
#snstat = dp.get_torrent(torrent_hash)
logger.info('---')
logger.info(snstat)
logger.info('---')
if (snstat is None or not snstat['completed']) and self.partial is False:
if snstat is None:
ckqueue_entry = queue.ckqueue()[item['item']]
if 'retry_count' in ckqueue_entry.keys():
retry_count = ckqueue_entry['retry_count'] + 1
else:
retry_count = 1
logger.warn('[Current attempt: ' + str(retry_count) + '] Cannot locate torrent on client. Ignoring this result for up to 5 retries / 2 minutes')
if retry_count > 5:
logger.warn('Unable to locate torrent on client. Removing item from queue.')
try:
os.remove(os.path.join(config.GENERAL['torrentfile_dir'], item['label'],
item['item'] + '.' + item['mode']))
logger.info('[HARPOON] File removed')
except:
logger.warn(
'[HARPOON] Unable to remove file from snatch queue directory [' + item['item'] + '.' +
item['mode'] + ']. You should delete it manually to avoid re-downloading')
queue.ckupdate(item['item'], {'stage': 'failed', 'status': 'Failed'})
self.not_loaded = 0
continue
else:
queue.put({'mode': item['mode'],
'item': item['item'],
'label': item['label'],
'client': item['client']})
queue.ckupdate(item['item'],{'stage': 'to-do', 'status': 'Not found in client. Attempt %s' % retry_count, 'retry_count': retry_count})
else:
logger.info('Still downloading in client....let\'s try again in 30 seconds.')
time.sleep(30)
#we already popped the item out of the queue earlier, now we need to add it back in.
queue.put({'mode': item['mode'],
'item': item['item'],
'label': item['label'],
'client': item['client']})
queue.ckupdate(item['item'],{'stage': 'to-do', 'status': 'Still downloading in client'})
elif snstat and 'failed' in snstat.keys() and snstat['failed']:
logger.info('Torrent or NZB returned status of "failed". Removing queue item.')
if item['client'] == 'sabnzbd' and config.SAB['sab_cleanup']:
sa_params = {}
sa_params['nzo_id'] = item['item']
sa_params['apikey'] = config.SAB['sab_apikey']
try:
sab = sabnzbd.SABnzbd(params=sa_params, saburl=config.SAB['sab_url'])
snstat = sab.cleanup()
except Exception as e:
logger.info('ERROR - %s' % e)
snstat = None
try:
os.remove(os.path.join(config.GENERAL['torrentfile_dir'], item['label'],
item['item'] + '.' + item['mode']))
logger.info('[HARPOON] File removed')
except:
logger.warn(
'[HARPOON] Unable to remove file from snatch queue directory [' + item['item'] + '.' + item[
'mode'] + ']. You should delete it manually to avoid re-downloading')
queue.ckupdate(item['item'], {'stage': 'failed', 'status': 'Failed'})
else:
if self.exists is False:
import shlex, subprocess
logger.info('Torrent is completed and status is currently Snatched. Attempting to auto-retrieve.')
tmp_script = os.path.join(harpoon.DATADIR, 'snatcher', 'getlftp.sh')
with open(tmp_script, 'r') as f:
first_line = f.readline()
if tmp_script.endswith('.sh'):
shell_cmd = re.sub('#!', '', first_line)
if shell_cmd == '' or shell_cmd is None:
shell_cmd = '/bin/bash'
else:
shell_cmd = sys.executable
curScriptName = shell_cmd + ' ' + str(tmp_script).decode("string_escape")
if snstat['mirror'] is True:
#downlocation = snstat['folder']
logger.info('trying to convert : %s' % snstat['folder'])
try:
downlocation = snstat['folder'].encode('utf-8')
logger.info('[HARPOON] downlocation: %s' % downlocation)
except Exception as e:
logger.info('utf-8 error: %s' % e)
else:
try:
tmpfolder = snstat['folder'].encode('utf-8')
tmpname = snstat['name'].encode('utf-8')
logger.info('[UTF-8 SAFETY] tmpfolder, tmpname: %s' % os.path.join(tmpfolder, tmpname))
except:
pass
logger.info('snstat[files]: %s' % snstat['files'][0])
#if it's one file in a sub-directory vs one-file in the root...
#if os.path.join(snstat['folder'], snstat['name']) != snstat['files'][0]:
if os.path.join(tmpfolder, tmpname) != snstat['files'][0]:
downlocation = snstat['files'][0].encode('utf-8')
else:
#downlocation = os.path.join(snstat['folder'], snstat['files'][0])
downlocation = os.path.join(tmpfolder, snstat['files'][0].encode('utf-8'))
downlocation = re.sub(",", "\\,", downlocation)
labelit = None
if config.GENERAL['applylabel'] is True:
if any([snstat['label'] != 'None', snstat['label'] is not None]):
labelit = snstat['label']
if snstat['multiple'] is None:
multiplebox = '0'
else:
multiplebox = snstat['multiple']
harpoon_env = os.environ.copy()
harpoon_env['conf_location'] = harpoon.CONF_LOCATION
harpoon_env['harpoon_location'] = re.sub("'", "\\'", downlocation)
harpoon_env['harpoon_location'] = re.sub("!", "\\!", downlocation)
harpoon_env['harpoon_label'] = labelit
harpoon_env['harpoon_applylabel'] = str(config.GENERAL['applylabel']).lower()
harpoon_env['harpoon_defaultdir'] = config.GENERAL['defaultdir']
harpoon_env['harpoon_multiplebox'] = multiplebox
if any([downlocation.endswith(ext) for ext in self.extensions]) or snstat['mirror'] is False:
combined_lcmd = 'pget -n %s \"%s\"' % (config.GENERAL['lcmdsegments'], downlocation)
logger.debug('[HARPOON] file lcmd: %s' % combined_lcmd)
else:
combined_lcmd = 'mirror -P %s --use-pget-n=%s \"%s\"' % (config.GENERAL['lcmdparallel'],config.GENERAL['lcmdsegments'], downlocation)
logger.debug('[HARPOON] folder lcmd: %s' % combined_lcmd)
harpoon_env['harpoon_lcmd'] = combined_lcmd
if any([multiplebox == '1', multiplebox == '0']):
harpoon_env['harpoon_pp_host'] = config.PP['pp_host']
harpoon_env['harpoon_pp_sshport'] = str(config.PP['pp_sshport'])
harpoon_env['harpoon_pp_user'] = config.PP['pp_user']
if config.PP['pp_keyfile'] is not None:
harpoon_env['harpoon_pp_keyfile'] = config.PP['pp_keyfile']
else:
harpoon_env['harpoon_pp_keyfile'] = ''
if config.PP['pp_passwd'] is not None:
harpoon_env['harpoon_pp_passwd'] = config.PP['pp_passwd']
else:
harpoon_env['harpoon_pp_passwd'] = ''
else:
harpoon_env['harpoon_pp_host'] = config.PP['pp_host2']
harpoon_env['harpoon_pp_sshport'] = config.PP['pp_sshport2']
harpoon_env['harpoon_pp_user'] = config.PP['pp_user2']
if config.PP['pp_keyfile2'] is not None:
harpoon_env['harpoon_pp_keyfile'] = config.PP['pp_keyfile2']
else:
harpoon_env['harpoon_pp_keyfile'] = ''
if config.PP['pp_passwd2'] is not None:
harpoon_env['harpoon_pp_passwd'] = config.PP['pp_passwd2']
else:
harpoon_env['harpoon_pp_passwd'] = ''
logger.info('Downlocation: %s' % re.sub("'", "\\'", downlocation))
logger.info('Label: %s' % labelit)
logger.info('Multiple Seedbox: %s' % multiplebox)
script_cmd = shlex.split(curScriptName)# + [downlocation, labelit, multiplebox]
logger.info(u"Executing command " + str(script_cmd))
try:
queue.ckupdate(item['item'], {'status': 'Fetching', 'stage': 'current'})
p = subprocess.Popen(script_cmd, env=dict(harpoon_env), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output, error = p.communicate()
if error:
logger.warn('[ERROR] %s' % error)
if output:
logger.info('[OUTPUT] %s'% output)
except Exception as e:
logger.warn('Exception occured: %s' % e)
continue
else:
snatch_status = 'COMPLETED'
queue.ckupdate(item['item'], {'status': 'Processing', 'stage': 'current'})
if all([snstat['label'] == config.SONARR['sonarr_label'], config.GENERAL['tv_choice'] == 'sonarr']): #probably should be sonarr_label instead of 'tv'
logger.debug('[HARPOON] - Sonarr Detected')
#unrar it, delete the .rar's and post-process against the items remaining in the given directory.
cr = unrar.UnRAR(os.path.join(config.GENERAL['defaultdir'], config.SONARR['sonarr_label'] ,snstat['name']))
chkrelease = cr.main()
if all([len(chkrelease) == 0, len(snstat['files']) > 1, not os.path.isdir(os.path.join(config.GENERAL['defaultdir'], config.SONARR['sonarr_label'], snstat['name']))]):
#if this hits, then the retrieval from the seedbox failed probably due to another script moving into a finished/completed directory (ie. race-condition)
logger.warn('[SONARR] Problem with snatched files - nothing seems to have downloaded. Retrying the snatch again in case the file was moved from a download location to a completed location on the client.')
time.sleep(10)
self.hash_reload = True
continue
logger.info('[SONARR] Placing call to update Sonarr')
sonarr_info = {'snstat': snstat}
ss = sonarr.Sonarr(sonarr_info)
sonarr_process = ss.post_process()
if not any([item['mode'] == 'hash-add', item['mode'] == 'file-add']):
logger.info('[HARPOON] Removing completed file from queue directory.')
try:
os.remove(os.path.join(config.GENERAL['torrentfile_dir'], config.SONARR['sonarr_label'], item['item'] + '.' + item['mode']))
logger.info('[HARPOON] File removed')
except:
logger.warn('[HARPOON] Unable to remove file from snatch queue directory [' + item['item'] + '.' + item['mode'] + ']. You should delete it manually to avoid re-downloading')
if sonarr_process is True:
logger.info('[SONARR] Successfully post-processed : ' + snstat['name'])
if config.SAB['sab_enable'] is True:
self.cleanup_check(item, script_cmd, downlocation, snstat)
else:
logger.info('[SONARR] Unable to confirm successful post-processing - this could be due to running out of hdd-space, an error, or something else occuring to halt post-processing of the episode.')
logger.info('[SONARR] HASH: %s / label: %s' % (snstat['hash'], snstat['label']))
queue.ckupdate(snstat['hash'],{'hash': snstat['hash'],
'stage': 'completed', 'status': 'Finished'})
if all([config.PLEX['plex_update'] is True, sonarr_process is True]):
#sonarr_file = os.path.join(self.torrentfile_dir, self.sonarr_label, str(snstat['hash']) + '.hash')
#with open(filepath, 'w') as outfile:
# json_sonarr = json.load(sonarr_file)
#root_path = json_sonarr['path']
logger.info('[PLEX-UPDATE] Now submitting update library request to plex')
plexit = plex.Plex({'plex_label': snstat['label'],
'root_path': None,})
pl = plexit.connect()
if pl['status'] is True:
logger.info('[HARPOON-PLEX-UPDATE] Completed (library is currently being refreshed)')
else:
logger.warn('[HARPOON-PLEX-UPDATE] Failure - library could NOT be refreshed')
elif all([snstat['label'] == config.SICKRAGE['sickrage_label'], config.GENERAL['tv_choice'] == 'sickrage']):
logger.debug('[HARPOON] - Sickrage Detected')
#unrar it, delete the .rar's and post-process against the items remaining in the given directory.
cr = unrar.UnRAR(os.path.join(config.GENERAL['defaultdir'], config.SICKRAGE['sickrage_label'], snstat['name']))
chkrelease = cr.main()
if all([len(chkrelease) == 0, len(snstat['files']) > 1, not os.path.isdir(os.path.join(config.GENERAL['defaultdir'], config.SICKRAGE['sickrage_label'], snstat['name']))]):
#if this hits, then the retrieval from the seedbox failed probably due to another script moving into a finished/completed directory (ie. race-condition)
logger.warn('[SICKRAGE] Problem with snatched files - nothing seems to have downloaded. Retrying the snatch again in case the file was moved from a download location to a completed location on the client.')
time.sleep(10)
self.hash_reload = True
continue
logger.info('[SICKRAGE] Placing call to update Sickrage')
sickrage_info = {'snstat': snstat}
sr = sickrage.Sickrage(sickrage_info)
sickrage_process = sr.post_process()
if not any([item['mode'] == 'hash-add', item['mode'] == 'file-add']):
logger.info('[HARPOON] Removing completed file from queue directory.')
try:
os.remove(os.path.join(config.GENERAL['torrentfile_dir'], config.SICKRAGE['sickrage_label'], item['item'] + '.' + item['mode']))
logger.info('[HARPOON] File removed')
except:
logger.warn('[HARPOON] Unable to remove file from snatch queue directory [' + item['item'] + '.' + item['mode'] + ']. You should delete it manually to avoid re-downloading')
if sickrage_process is True:
logger.info('[SICKRAGE] Successfully post-processed : ' + snstat['name'])
self.cleanup_check(item, script_cmd, downlocation, snstat)
else:
logger.info('[SICKRAGE] Unable to confirm successful post-processing - this could be due to running out of hdd-space, an error, or something else occuring to halt post-processing of the episode.')
logger.info('[SICKRAGE] HASH: %s / label: %s' % (snstat['hash'], snstat['label']))
queue.ckupdate(snstat['hash'],{'hash': snstat['hash'],
'stage': 'completed', 'status': 'Finished'})
if all([config.PLEX['plex_update'] is True, sickrage_process is True]):
logger.info('[PLEX-UPDATE] Now submitting update library request to plex')
plexit = plex.Plex({'plex_label': snstat['label'],
'root_path': None,})
pl = plexit.connect()
if pl['status'] is True:
logger.info('[HARPOON-PLEX-UPDATE] Completed (library is currently being refreshed)')
else:
logger.warn('[HARPOON-PLEX-UPDATE] Failure - library could NOT be refreshed')
elif snstat['label'] == config.RADARR['radarr_label']:
logger.debug('[HARPOON] - Radarr Detected')
#check list of files for rar's here...
cr = unrar.UnRAR(os.path.join(config.GENERAL['defaultdir'], config.RADARR['radarr_label'] ,snstat['name']))
chkrelease = cr.main()
if all([len(chkrelease) == 0, len(snstat['files']) > 1, not os.path.isdir(os.path.join(config.GENERAL['defaultdir'], config.RADARR['radarr_label'], snstat['name']))]):
#if this hits, then the retrieval from the seedbox failed probably due to another script moving into a finished/completed directory (ie. race-condition)
logger.warn('[RADARR] Problem with snatched files - nothing seems to have downloaded. Retrying the snatch again in case the file was moved from a download location to a completed location on the client.')
time.sleep(60)
self.hash_reload = True
continue
logger.info('[RADARR] UNRAR - %s' % chkrelease)
logger.info('[RADARR] Placing call to update Radarr')
radarr_info = {'radarr_id': None,
'radarr_movie': None,
'snstat': snstat}
rr = radarr.Radarr(radarr_info)
radarr_process = rr.post_process()
if not any([item['mode'] == 'hash-add', item['mode'] == 'file-add']):
logger.info('[HARPOON] Removing completed file from queue directory.')
try:
os.remove(os.path.join(config.GENERAL['torrentfile_dir'], config.RADARR['radarr_label'], item['item'] + '.' + item['mode']))
logger.info('[HARPOON] File removed')
except:
logger.warn('[HARPOON] Unable to remove file from snatch queue directory [' + item['item'] + '.' + item['mode'] + ']. You should delete it manually to avoid re-downloading.')
if config.RADARR['radarr_keep_original_foldernames'] is True:
logger.info('[HARPOON] Keep Original FolderNames are enabled for Radarr. Altering paths ...')
radarr_info['radarr_id'] = radarr_process['radarr_id']
radarr_info['radarr_movie'] = radarr_process['radarr_movie']
rof = radarr.Radarr(radarr_info)
radarr_keep_og = rof.og_folders()
if radarr_process['status'] is True:
logger.info('[RADARR] Successfully post-processed : ' + snstat['name'])
self.cleanup_check(item, script_cmd, downlocation, snstat)
else:
logger.info('[RADARR] Unable to confirm successful post-processing - this could be due to running out of hdd-space, an error, or something else occuring to halt post-processing of the movie.')
logger.info('[RADARR] HASH: %s / label: %s' % (snstat['hash'], snstat['label']))
logger.info('[RADARR] Successfully completed post-processing of ' + snstat['name'])
queue.ckupdate(snstat['hash'],{'hash': snstat['hash'],
'stage': 'completed', 'status': 'Finished'})
if all([config.PLEX['plex_update'] is True, radarr_process['status'] is True]):
logger.info('[PLEX-UPDATE] Now submitting update library request to plex')
plexit = plex.Plex({'plex_label': snstat['label'],
'root_path': radarr_process['radarr_root']})
pl = plexit.connect()
if pl['status'] is True:
logger.info('[HARPOON-PLEX-UPDATE] Completed (library is currently being refreshed)')
else:
logger.warn('[HARPOON-PLEX-UPDATE] Failure - library could NOT be refreshed')
elif snstat['label'] == config.LIDARR['lidarr_label']:
logger.debug('[HARPOON] - Lidarr Detected')
#check list of files for rar's here...
cr = unrar.UnRAR(os.path.join(config.GENERAL['defaultdir'], config.LIDARR['lidarr_label'] ,snstat['name']))
chkrelease = cr.main()
if all([len(chkrelease) == 0, len(snstat['files']) > 1, not os.path.isdir(os.path.join(config.GENERAL['defaultdir'], config.LIDARR['lidarr_label'], snstat['name']))]):
#if this hits, then the retrieval from the seedbox failed probably due to another script moving into a finished/completed directory (ie. race-condition)
logger.warn('[LIDARR] Problem with snatched files - nothing seems to have downloaded. Retrying the snatch again in case the file was moved from a download location to a completed location on the client.')
time.sleep(60)
self.hash_reload = True
continue
logger.info('[LIDARR] UNRAR - %s' % chkrelease)
logger.info('[LIDARR] Placing call to update Lidarr')
lidarr_info = {'snstat': snstat}
lr = lidarr.Lidarr(lidarr_info)
lidarr_process = lr.post_process()
if not any([item['mode'] == 'hash-add', item['mode'] == 'file-add']):
logger.info('[HARPOON] Removing completed file from queue directory.')
try:
os.remove(os.path.join(config.GENERAL['torrentfile_dir'], config.LIDARR['lidarr_label'], item['item'] + '.' + item['mode']))
logger.info('[HARPOON] File removed')
except:
logger.warn('[HARPOON] Unable to remove file from snatch queue directory [' + item['item'] + '.' + item['mode'] + ']. You should delete it manually to avoid re-downloading.')
if lidarr_process is True:
logger.info('[LIDARR] Successfully post-processed : ' + snstat['name'])
self.cleanup_check(item, script_cmd, downlocation, snstat)
else:
logger.info('[LIDARR] Unable to confirm successful post-processing - this could be due to running out of hdd-space, an error, or something else occuring to halt post-processing of the movie.')
logger.info('[LIDARR] HASH: %s / label: %s' % (snstat['hash'], snstat['label']))
logger.info('[LIDARR] Successfully completed post-processing of ' + snstat['name'])
queue.ckupdate(snstat['hash'],{'hash': snstat['hash'],
'stage': 'completed', 'status': 'Finished'})
if all([config.PLEX['plex_update'] is True, lidarr_process is True]):
logger.info('[PLEX-UPDATE] Now submitting update library request to plex')
plexit = plex.Plex({'plex_label': snstat['label']})
pl = plexit.connect()
if pl['status'] is True:
logger.info('[HARPOON-PLEX-UPDATE] Completed (library is currently being refreshed)')
else:
logger.warn('[HARPOON-PLEX-UPDATE] Failure - library could NOT be refreshed')
elif snstat['label'] == config.LAZYLIBRARIAN['lazylibrarian_label']:
logger.debug('[HARPOON] - Lazylibrarian Detected')
#unrar it, delete the .rar's and post-process against the items remaining in the given directory.
cr = unrar.UnRAR(os.path.join(config.GENERAL['defaultdir'], config.LAZYLIBRARIAN['lazylibrarian_label'] ,snstat['name']))
chkrelease = cr.main()
if all([len(chkrelease) == 0, len(snstat['files']) > 1, not os.path.isdir(os.path.join(config.GENERAL['defaultdir'], config.LAZYLIBRARIAN['lazylibrarian_label'], snstat['name']))]):
#if this hits, then the retrieval from the seedbox failed probably due to another script moving into a finished/completed directory (ie. race-condition)
logger.warn('[LAZYLIBRARIAN] Problem with snatched files - nothing seems to have downloaded. Retrying the snatch again in case the file was moved from a download location to a completed location on the client.')
time.sleep(10)
self.hash_reload = True
continue
logger.info('[LAZYLIBRARIAN] Placing call to update LazyLibrarian')
ll_file = os.path.join(config.GENERAL['torrentfile_dir'], config.LAZYLIBRARIAN['lazylibrarian_label'], item['item'] + '.' + item['mode'])
if os.path.isfile(ll_file):
ll_filedata = json.load(open(ll_file))
logger.info('[LAZYLIBRARIAN] File data loaded.')
else:
ll_filedata = None
logger.info('[LAZYLIBRARIAN] File data NOT loaded.')
ll_info = {'snstat': snstat,
'filedata': ll_filedata}
ll = lazylibrarian.LazyLibrarian(ll_info)
logger.info('[LAZYLIBRARIAN] Processing')
lazylibrarian_process = ll.post_process()
if not any([item['mode'] == 'hash-add', item['mode'] == 'file-add']):
logger.info('[HARPOON] Removing completed file from queue directory.')
try:
os.remove(os.path.join(config.GENERAL['torrentfile_dir'], config.LAZYLIBRARIAN['lazylibrarian_label'], item['item'] + '.' + item['mode']))
logger.info('[HARPOON] File removed')
except:
logger.warn('[HARPOON] Unable to remove file from snatch queue directory [' + item['item'] + '.' + item['mode'] + ']. You should delete it manually to avoid re-downloading')
if lazylibrarian_process is True:
logger.info('[LAZYLIBRARIAN] Successfully post-processed : ' + snstat['name'])
self.cleanup_check(item, script_cmd, downlocation, snstat)
else:
logger.info('[LAZYLIBRARIAN] Unable to confirm successful post-processing - this could be due to running out of hdd-space, an error, or something else occuring to halt post-processing of the episode.')
logger.info('[LAZYLIBRARIAN] HASH: %s / label: %s' % (snstat['hash'], snstat['label']))
queue.ckupdate(snstat['hash'], {'hash': snstat['hash'],
'stage': 'completed', 'status': 'Finished'})
if all([config.PLEX['plex_update'] is True, lazylibrarian_process is True]):
logger.info('[PLEX-UPDATE] Now submitting update library request to plex')
plexit = plex.Plex({'plex_label': snstat['label'],
'root_path': None,})
pl = plexit.connect()
if pl['status'] is True:
logger.info('[HARPOON-PLEX-UPDATE] Completed (library is currently being refreshed)')
else:
logger.warn('[HARPOON-PLEX-UPDATE] Failure - library could NOT be refreshed')
elif snstat['label'] == 'music':
logger.debug('[HARPOON] - Music Detected')
logger.info('[MUSIC] Successfully auto-snatched!')
self.cleanup_check(item, script_cmd, downlocation, snstat)
if not any([item['mode'] == 'hash-add', item['mode'] == 'file-add']):
logger.info('[MUSIC] Removing completed file from queue directory.')
try:
os.remove(os.path.join(config.GENERAL['torrentfile_dir'], snstat['label'], item['item'] + '.' + item['mode']))
logger.info('[MUSIC] File removed from system so no longer queuable')
except:
try:
os.remove(os.path.join(config.GENERAL['torrentfile_dir'], snstat['label'], snstat['hash'] + '.hash'))
logger.info('[MUSIC] File removed by hash from system so no longer queuable')
except:
logger.warn('[MUSIC] Unable to remove file from snatch queue directory [' + item['item'] + '.' + item['mode'] + ']. You should delete it manually to avoid re-downloading.')
else:
logger.info('[MUSIC] Completed status returned for manual post-processing of file.')
queue.ckupdate(snstat['hash'],{'hash': snstat['hash'],
'stage': 'completed', 'status': 'Finished'})
logger.info('Auto-Snatch of torrent completed.')
elif snstat['label'] == 'xxx':
logger.debug('[HARPOON] - XXX Detected')
logger.info('[XXX] Successfully auto-snatched!')
self.cleanup_check(item, script_cmd, downlocation, snstat)
if not any([item['mode'] == 'hash-add', item['mode'] == 'file-add']):
logger.info('[XXX] Removing completed file from queue directory.')
try:
os.remove(os.path.join(config.GENERAL['torrentfile_dir'], snstat['label'], item['item'] + '.' + item['mode']))
logger.info('[XXX] File removed')
except:
try:
os.remove(os.path.join(config.GENERAL['torrentfile_dir'], snstat['label'], snstat['hash'] + '.hash'))
logger.info('[XXX] File removed by hash from system so no longer queuable')
except:
logger.warn('[XXX] Unable to remove file from snatch queue directory [' + item['item'] + '.' + item['mode'] + ']. You should delete it manually to avoid re-downloading.')
else:
logger.info('[XXX] Completed status returned for manual post-processing of file.')
queue.ckupdate(snstat['hash'], {'hash': snstat['hash'],
'stage': 'completed', 'status': 'Finished'})
logger.info('Auto-Snatch of torrent completed.')
elif snstat['label'] == config.MYLAR['mylar_label']:
logger.debug('[HARPOON] - Mylar Detected')
logger.info('[MYLAR] Placing call to update Mylar')
mylar_info = {'issueid': self.issueid,
'snstat': snstat}
my = mylar.Mylar(mylar_info)
mylar_process = my.post_process()
logger.info('[MYLAR] Successfully auto-snatched!')
self.cleanup_check(item, script_cmd, downlocation, snstat)
if not any([item['mode'] == 'hash-add', item['mode'] == 'file-add']):
logger.info('[MYLAR] Removing completed file from queue directory.')
try:
os.remove(os.path.join(config.GENERAL['torrentfile_dir'], snstat['label'], item['item'] + '.' + item['mode']))
logger.info('[MYLAR] File removed')
except:
logger.warn('[MYLAR] Unable to remove file from snatch queue directory [' + item['item'] + '.' + item['mode'] + ']. Trying possible alternate naming.')
try:
os.remove(os.path.join(self.torrentfile_dir, snstat['label'], snstat['hash'] + '.mylar.hash'))
logger.info('[MYLAR] File removed by hash from system so no longer queuable')
except:
logger.warn('[MYLAR] Unable to remove file from snatch queue directory [' + item['item'] + '.mylar.' + item['mode'] + ']. You should delete it manually to avoid re-downloading.')
else:
logger.info('[MYLAR] Completed status returned for manual post-processing of file.')
if mylar_process is True:
logger.info('[MYLAR] Successfully post-processed : ' + snstat['name'])
self.cleanup_check(item, script_cmd, downlocation, snstat)
else:
logger.info('[MYLAR] Unable to confirm successful post-processing - this could be due to running out of hdd-space, an error, or something else occuring to halt post-processing of the issue.')
logger.info('[MYLAR] HASH: %s / label: %s' % (snstat['hash'], snstat['label']))
queue.ckupdate(snstat['hash'],{'hash': snstat['hash'],
'stage': 'completed', 'status': 'Finished'})
logger.info('Auto-Snatch of torrent completed.')
else:
logger.debug('[HARPOON] - Other Detected')
logger.info('Successfully auto-snatched!')
self.cleanup_check(item, script_cmd, downlocation, snstat)
if not any([item['mode'] == 'hash-add', item['mode'] == 'file-add']):
logger.info('Removing completed file from queue directory.')
try:
os.remove(os.path.join(config.GENERAL['torrentfile_dir'], snstat['label'], item['item'] + '.' + item['mode']))
logger.info('File removed')
except:
try:
os.remove(os.path.join(config.GENERAL['torrentfile_dir'], snstat['label'], snstat['hash'] + '.hash'))
logger.info('File removed by hash from system so no longer queuable')
except:
logger.warn('Unable to remove file from snatch queue directory [' + item['item'] + '.' + item['mode'] + ']. You should delete it manually to avoid re-downloading.')
else:
logger.info('Completed status returned for manual post-processing of file.')
queue.ckupdate(snstat['hash'], {'hash': snstat['hash'],
'stage': 'completed', 'status': 'Finished'})
logger.info('Auto-Snatch of torrent completed.')
if any([item['mode'] == 'hash-add', item['mode'] == 'file-add']) and self.daemon is False:
queue.put({'mode': 'exit',
'item': 'None'})
def cleanup_check(self, item, script_cmd, downlocation, snstat):
logger.info('[CLEANUP-CHECK] item: %s' % item)
if 'client' in item.keys() and config.SAB['sab_cleanup'] and item['client'] == 'sabnzbd':
import subprocess
logger.info('[HARPOON] Triggering cleanup')
sa_params = {}
sa_params['nzo_id'] = item['item']
sa_params['apikey'] = config.SAB['sab_apikey']
try:
sab = sabnzbd.SABnzbd(params=sa_params, saburl=config.SAB['sab_url'])
cleanup = sab.cleanup()
except Exception as e:
logger.info('ERROR - %s' % e)
cleanup = None
labelit = None
if config.GENERAL['applylabel'] is True:
if any([snstat['label'] != 'None', snstat['label'] is not None]):
labelit = snstat['label']
if snstat['multiple'] is None:
multiplebox = '0'
else:
multiplebox = snstat['multiple']
harpoon_env = os.environ.copy()
harpoon_env['conf_location'] = harpoon.CONF_LOCATION
harpoon_env['harpoon_location'] = re.sub("'", "\\'", downlocation)
harpoon_env['harpoon_location'] = re.sub("!", "\\!", downlocation)
harpoon_env['harpoon_label'] = labelit
harpoon_env['harpoon_applylabel'] = str(config.GENERAL['applylabel']).lower()
harpoon_env['harpoon_defaultdir'] = config.GENERAL['defaultdir']
harpoon_env['harpoon_lcmd'] = 'rm -r \"%s\"' % downlocation
if any([multiplebox == '1', multiplebox == '0']):
harpoon_env['harpoon_pp_host'] = config.PP['pp_host']
harpoon_env['harpoon_pp_sshport'] = str(config.PP['pp_sshport'])
harpoon_env['harpoon_pp_user'] = config.PP['pp_user']
if config.PP['pp_keyfile'] is not None:
harpoon_env['harpoon_pp_keyfile'] = config.PP['pp_keyfile']
else:
harpoon_env['harpoon_pp_keyfile'] = ''
if config.PP['pp_passwd'] is not None:
harpoon_env['harpoon_pp_passwd'] = config.PP['pp_passwd']
else:
harpoon_env['harpoon_pp_passwd'] = ''
else:
harpoon_env['harpoon_pp_host'] = config.PP['pp_host2']
harpoon_env['harpoon_pp_sshport'] = config.PP['pp_sshport2']
harpoon_env['harpoon_pp_user'] = config.PP['pp_user2']
if config.PP['pp_keyfile2'] is not None:
harpoon_env['harpoon_pp_keyfile'] = config.PP['pp_keyfile2']
else:
harpoon_env['harpoon_pp_keyfile'] = ''
if config.PP['pp_passwd2'] is not None:
harpoon_env['harpoon_pp_passwd'] = config.PP['pp_passwd2']
else:
harpoon_env['harpoon_pp_passwd'] = ''
logger.debug('Params: %s' % harpoon_env)
try:
p = subprocess.Popen(script_cmd, env=dict(harpoon_env), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output, error = p.communicate()
if error:
logger.warn('[ERROR] %s' % error)
if output:
logger.info('[OUTPUT] %s' % output)
except Exception as e:
logger.warn('Exception occured: %s' % e)
def sizeof_fmt(self, num, suffix='B'):
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
def moviecheck(self, movieinfo):
movie_type = None
filename = movieinfo['movieFile']['relativePath']
vsize = str(movieinfo['movieFile']['mediaInfo']['width'])
for webdl in config.RADARR['web_movies_defs']:
if webdl.lower() in filename.lower():
logger.info('[RADARR] HD - WEB-DL Movie detected')
movie_type = 'WEBDL' #movie_type = hd - will store the hd def (ie. 720p, 1080p)
break
if movie_type is None or movie_type == 'HD': #check the hd to get the match_type since we already know it's HD.
for hd in config.RADARR['hd_movies_defs']:
if hd.lower() in filename.lower():
logger.info('[MOVIE] HD - Movie detected')
movie_type = 'HD' #movie_type = hd - will store the hd def (ie. 720p, 1080p)
break
if movie_type is None:
for sd in config.RADARR['sd_movies_defs']:
if sd.lower() in filename.lower():
logger.info('[MOVIE] SD - Movie detected')
movie_type = 'SD' #movie_type = sd
break
#not sure if right spot, we can determine movie_type (HD/SD) by checking video dimensions.
#1920/1280 = HD
#720/640 = SD
SD_Dimensions = ('720', '640')