-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogram.py
1163 lines (987 loc) · 44.4 KB
/
program.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
# Copyright (C) Michael Still ([email protected]) 2006, 2007, 2008, 2009
# Copyright (C) Elkin Fricke ([email protected]) 2011, 2012, 2013, 2014
# Released under the terms of the GNU GPL v2
import commands
import datetime
import MySQLdb
import re
import os
import shutil
import stat
import socket
import sys
import tempfile
import time
import unicodedata
import fnmatch
import urlparse
import database
import gflags
import mythnettvcore
import proxyhandler
import utility
import series
import tvrage.api
import gmail
import notification
import UnRAR2
from datetime import timedelta
# Note that plugins aren't actually plugins at the moment, and that flags
# parsing will be a problem for plugins when we get there (I think).
from plugins import bittorrent
from plugins import streamingsites
# import MythTV bindings... we could test if you have them, but if you don't, why do you need this script?
from MythTV import OldRecorded, Recorded, RecordedProgram, Record, Channel, System, \
MythDB, Video, MythVideo, MythBE, MythError, MythLog, MythXML
from stat import *
# import a modified version from ffmpeg wrapper
from plugins import video_inspector
FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('force', False,
'Force downloads to run, even if they failed recently')
if(os.environ.get('HOME','') == ''):
os.environ['HOME'] = '/home/mythtv'
# Exceptions returned by this module
class StorageException(utility.LoggingException):
""" Errors with storage of programs """
class DownloadException(utility.LoggingException):
""" Errors in the download process """
class DirectoryException(utility.LoggingException):
""" Errors in importing a directory """
def addChannel(icon, channel_id, channel_num, callsign, channelname):
""" add a new dummy channel to the mythtvbackend """
try:
if Channel(channel_id):
return False
except:
pass
data={}
data['chanid'] = channel_id
data['channum'] = str(channel_num)
data['freqid'] = str(channel_num)
data['atsc_major_chan'] = int(channel_num)
data['icon'] = u''
if icon != u'':
data['icon'] = icon
data['callsign'] = callsign
data['name'] = channelname
data['last_record'] = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
try:
Channel().create(data)
except MythError, e:
return False
return True
def getAspectRatio(videoheight, videowidth):
"""getAspectRatio -- return MythTV compatible aspect ratio
"""
videoaspect = float(videowidth) / float(videoheight)
if videoheight >= 1080:
return '1080'
elif videoheight >= 720:
return '720'
elif videowidth >= 1280:
return 'HDTV'
elif videoaspect >= 1.4:
return 'WIDESCREEN'
else:
return ''
def aspectType(self, videoheight, videowidth, chanid, start, out=sys.stdout):
"""storeAspect -- writes aspect ratio to MythTV database
as the python bindings don't seem to have a solution to this
and MythWeb needs it.
"""
videoaspect = float(videowidth) / float(videoheight)
if videoaspect < 1.41:
return 11
elif videoaspect < 1.81:
return 12
elif videoaspect < 2.31:
return 13
def SafeForFilename(s):
"""SafeForFilename -- convert s into something which can be used for a
filename.
"""
for c in [' ', '(', ')', '{', '}', '[', ']', ':', '\'', '"', '!']:
s = s.replace(c, '_')
return s
def Prompt(prompt):
"""Prompt -- prompt for input from the user"""
sys.stdout.write('%s >> ' % prompt)
return sys.stdin.readline().rstrip('\n')
class MythNetTvProgram:
"""MythNetTvProgram -- a downloadable program.
This class embodies everything we can do with a program. The existance
of this class does not mean that the show has been fully downloaded and
made available in MythTV yet. Instances of this class persist to the MySQL
database.
"""
def __init__(self, db):
self.persistant = {}
self.db = db
def FromUrl(self, url, guid):
"""FromUrl -- start a program based on its URL"""
new_video = True
# Some URLs have the ampersand escaped
url = url.replace('&', '&')
# Persist what we know now
self.persistant['url'] = url
self.persistant[u'filename'] = SafeForFilename(self.GetFilename(url))
self.persistant['guid'] = guid
try:
if self.db.GetOneRow('select guid from mythnettv_programs '
'where guid="%s";' % guid).keys() != []:
new_video = False
except:
pass
self.Store()
self.db.Log('Updated show from %s with guid %s' %(url, guid))
return new_video
def FromInteractive(self, url, title, subtitle, description):
"""FromInteractive -- create a program by prompting the user for input
for all the bits we need. We check if we have the data first, so that
we're not too annoying.
"""
if url:
self.persistant['url'] = url
if title:
self.persistant['title'] = title
if subtitle:
self.persistant['subtitle'] = subtitle
if description:
self.persistant['description'] = description
for key in ['url', 'title', 'subtitle', 'description']:
if not self.persistant.has_key(key):
self.persistant[key] = Prompt(key)
# The GUID is now generated as the hex value of a hash of title and Subtitle
# we make sure we therefore only have one download per title and subtitle
self.persistant['guid'] = utility.hashtitlesubtitle(title, subtitle)
self.persistant['filename'] = SafeForFilename(self.GetFilename(
self.persistant['url']))
self.Store()
def GetFilename(self, url, out=sys.stdout):
"""GetFilename -- return the filename portion of a URL"""
# Some URLs have the ampersand escaped
re_filename = re.compile('.*/([^/\?]*).*')
m = re_filename.match(url)
if m:
return m.group(1)
if not '/' in url:
return url
raise(self.db, 'Could not determine local filename for %s\n' % url)
def GetTitle(self):
"""GetTitle -- return the title of the program"""
return self.persistant['title']
def GetSubtitle(self):
"""GetSubtitle -- return the subtitle of the program"""
return self.persistant['subtitle']
def GetDate(self):
"""GetDate -- return the date of the program"""
return self.persistant['unparsed_date']
def SetDate(self, date):
"""SetDate -- set the date of the program"""
self.persistant['date'] = date.strftime('%a, %d %b %Y %H:%M:%S')
self.persistant['unparsed_date'] = date.strftime('%a, %d %b %Y %H:%M:%S')
self.persistant['parsed_date'] = date
def GetMime(self):
"""GetMime -- return the program's mime type"""
return self.persistant['mime_type']
def SetMime(self, mime):
"""SetMime -- set the program's mime type"""
self.persistant['mime_type'] = mime
def Load(self, guid):
"""Load -- load information based on a GUID from the DB"""
self.persistant = self.db.GetOneRow('select * from mythnettv_programs '
'where guid="%s";' % guid)
def Store(self):
"""Store -- persist to MySQL"""
# We store the date of the entry a lot of different ways
if not self.persistant.has_key('date'):
self.SetDate(datetime.datetime.utcnow())
try:
self.db.WriteOneRow('mythnettv_programs', 'guid', self.persistant)
except MySQLdb.Error, (errno, errstr):
if errno != 1064:
raise StorageException(self.db, 'Could not store program %s: %s "%s"'
%(self.persistant['guid'], errno, errstr))
except database.FormatException, e:
raise e
except Exception, e:
raise StorageException(self.db,
'Could not store program: %s: "%s" (%s)\n\n%s'
%(self.persistant['guid'], e, type(e),
repr(self.persistant)))
def SetUrl(self, url):
"""SetUrl -- set just the URL for the program"""
self.persistant['url'] = url
def SetShowInfo(self, title, subtitle, description, date, date_parsed):
"""SetShowInfo -- set show meta data"""
self.persistant['title'] = title
self.persistant['subtitle'] = subtitle
self.persistant['description'] = utility.massageDescription(description)
self.persistant['date'] = date
self.persistant['unparsed_date'] = date
self.persistant['parsed_date'] = repr(date_parsed)
self.Store()
self.db.Log('Set show info for guid %s' % self.persistant['guid'])
def TemporaryFilename(self, datadir, out=sys.stdout):
"""TemporaryFilename -- calculate the filename to use in the temporary
directory
"""
# put filename from url in database
try:
self.persistant['filename'] = SafeForFilename(self.GetFilename(self.persistant['url']))
except:
pass
filename = '%s/%s' %(datadir, self.persistant['filename'])
# Store in database
#self.persistant['tmp_name'] = filename
out.write('Destination directory will be %s\n' % datadir)
self.db.Log('Downloading %s to %s' %(self.persistant['guid'], filename))
return filename
def DownloadMPlayer(self, filename):
"""DownloadRTSP -- download a show using mplayer"""
datadir = self.db.GetSettingWithDefault('datadir', FLAGS.datadir)
(status, out) = commands.getstatusoutput('cd %s; '
'mplayer -dumpstream "%s"'
%(datadir,
self.persistant['url']))
if status != 0:
raise DownloadException('MPlayer download failed')
shutil.move(datadir + '/stream.dump', filename)
return os.stat(filename)[ST_SIZE]
def DownloadAVconv(self, filename):
"""Downloadm3u8 -- download a show using avconv"""
datadir = self.db.GetSettingWithDefault('datadir', FLAGS.datadir)
(status, out) = commands.getstatusoutput('cd %s; '
'avconv -i "%s" -c copy stream.avi'
%(datadir,
self.persistant['url']))
if status != 0:
raise DownloadException('avconv download failed')
shutil.move(datadir + '/stream.avi', filename)
return os.stat(filename)[ST_SIZE]
def DownloadHTTP(self, filename, force_proxy=None, force_budget=-1,
out=sys.stdout):
"""DownloadHTTP -- download a show, using HTTP"""
out.write('Download URL is "%s"\n' % self.persistant['url'])
done = self.persistant.get('download_finished', '0')
if done != '1':
proxy = proxyhandler.HttpHandler(self.db)
try:
remote = proxy.Open(self.persistant['url'], force_proxy=force_proxy,
force_budget=force_budget, out=out)
out.write('Downloading %s\n' % self.persistant['url'])
except Exception, e:
raise DownloadException(self.db, 'HTTP download failed: %s' % e)
local = open(filename, 'w')
total = int(self.persistant.get('transfered', 0))
this_attempt_total = proxyhandler.HTTPCopy(self.db, proxy, remote, local,
out=out)
total += this_attempt_total
self.persistant['transfered'] = repr(total)
self.persistant['size'] = repr(total)
self.persistant['last_attempt'] = datetime.datetime.utcnow()
self.Store()
remote.close()
local.close()
return total
def Info(self, s):
"""Info -- A callback for download status information"""
sys.stdout.write('%s: %s --> %s\n' %(self.persistant['title'],
self.persistant['subtitle'],
s))
self.persistant['last_attempt'] = datetime.datetime.utcnow()
self.Store()
def Download(self, datadir, force_proxy=None, force_budget=-1, out=sys.stdout):
"""Download -- download the show"""
#to-do: where the f%ck is this being used?
one_hour = datetime.timedelta(hours=1)
if self.persistant['url'].endswith('torrent') \
or self.persistant.get('mime_type', '').endswith('torrent'):
# give torrents more time to download, set to 6 hours
one_hour = datetime.timedelta(hours=6)
one_hour_ago = datetime.datetime.now() - one_hour
if FLAGS.verbose:
out.write('Considering %s: %s\n' %(self.persistant['title'],
self.persistant['subtitle']))
if 'last_attempt' in self.persistant and \
self.persistant['last_attempt'] > one_hour_ago:
out.write('Last attempt was too recent. It was at %s\n'
% self.persistant['last_attempt'])
if not FLAGS.force:
return False
else:
out.write('Download forced\n')
self.persistant['last_attempt'] = datetime.datetime.utcnow()
filename = self.TemporaryFilename(datadir, out=out)
self.persistant['download_started'] = '1'
self.Store()
out.write('Downloading %s: %s\n\n'
%(self.persistant['title'],
self.persistant['subtitle']))
if 'attempts' in self.persistant and self.persistant['attempts']:
max_attempts = int(self.db.GetSettingWithDefault('attempts', 3))
print ('This is a repeat attempt (%d attempts so far, max is %d)'
%(self.persistant['attempts'], max_attempts))
if self.persistant['attempts'] > max_attempts:
out.write('Too many failed attempts, giving up on this program\n')
self.persistant['download_finished'] = 0
self.persistant['imported'] = 0
self.persistant['failed'] = 1
self.Store()
gmail.send_email('Too many failed attempts for show %s - %s.\n'
%(self.persistant['title'],
self.persistant['subtitle']))
return False
self.persistant.setdefault('attempts', 0)
self.persistant['attempts'] += 1
self.Store()
total = 0
#deal with torrent downloads but not magnet links
if self.persistant['url'].endswith('torrent') \
or (self.persistant.get('mime_type', '').endswith('torrent')
and not self.persistant['url'].startswith('magnet')):
total = self.DownloadHTTP(filename, force_proxy=force_proxy, out=out)
if total == 0:
self.Store()
return False
# DownloadHTTP thinks everything is complete because the HTTP download
# finished OK. That's wrong.
self.persistant['download_finished'] = None
self.persistant['imported'] = None
self.Store()
if self.persistant.get('tmp_name', '') == '':
(tmpfd, tmpname) = tempfile.mkstemp(dir=datadir)
os.close(tmpfd)
os.unlink(tmpname)
self.persistant['tmp_name'] = tmpname
self.Store()
else:
tmpname = self.persistant['tmp_name']
# Upload rate can either be the shipped default, a new default from
# the settings tables, or a temporary override
# TODO(mikal): this needs to be some sort of more generic settings
# passing thing
if FLAGS.uploadrate:
upload_rate = FLAGS.uploadrate
else:
upload_rate = self.db.GetSettingWithDefault('uploadrate', 100)
total = bittorrent.Download(filename, tmpname, self.Info,
upload_rate=upload_rate,
verbose=FLAGS.verbose, out=out)
if total > 0:
self.persistant['filename'] = tmpname.split('/')[-1]
total += int(self.persistant.get('transfered', 0))
# Now deal with magnet links
elif self.persistant['url'].startswith('magnet'):
#TODO do we realy need this for magnet links?
if self.persistant.get('tmp_name', '') == '':
(tmpfd, tmpname) = tempfile.mkstemp(dir=datadir)
os.close(tmpfd)
os.unlink(tmpname)
self.persistant['tmp_name'] = tmpname
self.Store()
else:
tmpname = self.persistant['tmp_name']
# Upload rate can either be the shipped default, a new default from
# the settings tables, or a temporary override
if FLAGS.uploadrate:
upload_rate = FLAGS.uploadrate
else:
upload_rate = self.db.GetSettingWithDefault('uploadrate', 100)
total = bittorrent.Download(self.persistant['url'], tmpname, self.Info,
upload_rate=upload_rate,
verbose=FLAGS.verbose, out=out)
# deal with Vimeo downloads
elif self.persistant['url'].startswith('http://vimeo'):
vimeoid = re.search('clip_id=(\d+)', self.persistant['url'])
out.write('VimeoID: %s\n' % vimeoid.group(1))
total = streamingsites.Download('Vimeo', vimeoid.group(1), datadir)
self.persistant['filename'] = total
# deal with Xvideo downloads
elif self.persistant['url'].startswith('http://www.xvideo'):
xvideoid = self.persistant['url']
out.write('XvideoID: %s\n' % xvideoid)
total = streamingsites.Download('xvideos', xvideoid, datadir)
self.persistant['filename'] = total
# deal with XnXX downloads
elif self.persistant['url'].startswith('http://video.xnxx'):
xvideoid = self.persistant['url']
out.write('XnXXID: %s\n' % xvideoid)
total = streamingsites.Download('xnxx', xvideoid, datadir)
self.persistant['filename'] = total
# deal with YouPorn downloads
elif self.persistant['url'].startswith('http://www.youporn'):
xvideoid = self.persistant['url']
out.write('YouPornID: %s\n' % xvideoid)
total = streamingsites.Download('YouPorn', xvideoid, datadir)
self.persistant['filename'] = total
# deal with Comedians in CArs downloads
elif self.persistant['url'].startswith('http://comediansincars'):
videoid = self.persistant['url']
out.write('CommediansID: %s\n' % videoid)
total = streamingsites.Download('', videoid, datadir)
self.persistant['filename'] = total
# deal with ZDF downloads
elif self.persistant['url'].startswith('http://www.zdf'):
xvideoid = self.persistant['url']
out.write('ZDFID: %s\n' % xvideoid)
total = streamingsites.Download('ZDF', xvideoid, datadir)
self.persistant['filename'] = total
# deal with TeamCoco downloads
elif self.persistant['url'].startswith('http://teamcoco'):
xvideoid = self.persistant['url']
out.write('TeamCocoID: %s\n' % xvideoid)
total = u''
total = streamingsites.Download('teamcoco', xvideoid, datadir)
self.persistant[u'filename'] = total
# deal with The Daily Show downloads
elif self.persistant['url'].startswith('http://www.thedaily'):
xvideoid = self.persistant['url']
out.write('TheDailyID: %s\n' % xvideoid)
total = streamingsites.Download('ComedyCentral', xvideoid, datadir)
self.persistant['filename'] = total
#deal with YouTube downloads
elif self.persistant['url'].startswith('http://www.youtube') or self.persistant['url'].startswith('https://www.youtube'):
#url_data = urlparse.urlparse(self.persistant['url'])
#query = urlparse.parse_qs(url_data.query)
#youtubeid = query["v"][0]
youtubeid = self.persistant['url']
out.write('YouTubeID: %s\n' % youtubeid)
total = streamingsites.Download('YouTube', youtubeid, datadir)
out.write('%s/n' % total)
self.persistant['filename'] = total
elif self.persistant['url'].endswith('m3u8'):
total = self.DownloadAVconv(filename)
out.write('%s/n' % total)
elif self.persistant['url'].startswith('http://'):
total = self.DownloadHTTP(filename, force_proxy=force_proxy,
force_budget=force_budget)
else:
total = filename
if total == 0:
return False
self.persistant['last_attempt'] = datetime.datetime.utcnow()
self.persistant['download_finished'] = '1'
self.persistant['transfered'] = repr(total)
self.persistant['size'] = repr(total)
self.Store()
out.write('Download complete...\n')
self.db.Log('Download of %s done' % self.persistant['guid'])
return True
def CopyLocalFile(self, datadir, out=sys.stdout):
"""CopyLocalFile -- copy a local file to the temporary directory, and
treat it as if it was a download"""
filename = self.TemporaryFilename(datadir, out=out)
self.persistant['download_started'] = '1'
self.Store()
if self.persistant['url'] != filename:
shutil.copyfile(self.persistant['url'], filename)
self.persistant['download_finished'] = '1'
size = os.stat(filename)[ST_SIZE]
self.persistant['transfered'] = repr(size)
self.persistant['size'] = repr(size)
self.Store()
self.db.Log('Download of %s done' % self.persistant['guid'])
def Import(self, out=sys.stdout):
"""Import -- import a downloaded show into the MythTV user interface"""
# Determine meta data
self.db.Log('Importing %s' % self.persistant['guid'])
datadir = self.db.GetSettingWithDefault('datadir', FLAGS.datadir)
chanid = self.db.GetOneRow('select chanid from mythnettv_subscriptions where '
'title="%s";' % self.persistant['title'])
if not chanid:
chanid = self.db.GetSetting('chanid')
else:
chanid = chanid['chanid']
filename = '%s/%s' %(datadir, self.persistant['filename'])
if FLAGS.verbose:
out.write('Importing %s\n' % filename)
try:
if os.path.isdir(self.persistant['tmp_name']):
utility.recursive_file_permissions(filename,-1,-1,0o777)
# go through all subdirectories to find RAR files
for root, dirnames, ents in os.walk(self.persistant['tmp_name']):
for counter in fnmatch.filter(ents, '*'):
# only pick those files that are single rars or the first part of a rar
if (counter.endswith('.rar') or counter.endswith('zip')) and not (re.search('part[1-9][0-9]', counter) or re.search('part0[2-9]', counter)):
if FLAGS.verbose:
out.write('Extracting RARs, please wait... ')
UnRAR2.RarFile(os.path.join(root, counter)).extract(path=self.persistant['tmp_name'])
if FLAGS.verbose:
out.write('Extracted %s\n' % counter)
handled = False
# go through all sundirectories again, to find video files
if FLAGS.verbose:
out.write('Searching for videofiles in %s\n' % self.persistant['tmp_name'])
for root, dirnames, ents in os.walk(self.persistant['tmp_name']):
for counter in fnmatch.filter(ents, '*'):
for extn in ['.avi', '.wmv', '.mp4', '.mkv']:
if counter.endswith(extn) and not fnmatch.fnmatch(counter, '*ample*'):
filename = '%s/%s' %(root, counter)
if FLAGS.verbose:
out.write(' Picked %s from the directory\n' % counter)
#self.persistant['filename'] = filename
handled = True
if not handled:
raise DirectoryException(self.db,
'Don\'t know how to handle this directory')
except:
pass
videodir = utility.GetVideoDir()
out.write(' Videodir %s\n' % videodir)
out.write(' Filename %s\n' % filename)
try:
vid = video_inspector.VideoInspector(filename)
if FLAGS.verbose:
out.write(' Videometadata: %s, %s\n' % (vid.width(),vid.height()))
except:
out.write("No video metadata could be detected")
pass
# Try to use the publish time of the RSS entry as the start time...
try:
start = datetime.datetime.strptime(str(self.persistant['date']), '%Y-%m-%d %H:%M:%S')
#start = datetime.datetime.strptime(self.persistant['unparsed_date'], '%a, %d %b %Y %H:%M:%S')
if FLAGS.verbose:
out.write(' Using database time as timestamp for recording\n')
except:
start = datetime.datetime.now()
if FLAGS.verbose:
out.write(' Using now as timestamp for recording - %s\n' % start)
# Ensure uniqueness for the start time
interval = datetime.timedelta(seconds = 1)
if FLAGS.verbose:
out.write(' %s %s\n' %(chanid, start))
while self.db.GetOneRow('select basename from recorded where starttime = %s and chanid = %s' \
%(self.db.FormatSqlValue('', start),
chanid)):
if FLAGS.verbose:
out.write(' %s %s\n' %(chanid, start))
start += interval
# Determine the duration of the video
duration = datetime.timedelta(seconds = 60)
try:
duration = datetime.timedelta(seconds = vid.duration())
except:
#Could not determine the real length of the video.
#Instead we will just pretend its only one minute long.
pass
finish = start + duration
realseason = 0
realepisode = 0
inetref = ''
# get show and episode details from TV-Rage, if possible
#try if we can get TVRage or TTVDB information back
try:
se = series.ExtractSeasonEpisode(self.persistant['subtitle'])
tvrage = series.TVRageSeasonEpisode(self.persistant['title'], se[0], se[1])
ttvdb = series.TTVDBSeasonEpisode(self.persistant['title'], se[0], se[1])
# if ttvdb did not return correct date take tvrage (mythtv likes ttvdb)
if ttvdb:
titledescription = ttvdb
else:
titledescription = tvrage
self.persistant['subtitle'] = titledescription[0]
self.persistant['description'] = titledescription[1]
realseason = se[0]
realepisode = se[1]
inetref = titledescription[4]
if FLAGS.verbose:
out.write("Found on TVRage or TTVDB: S%sE%s inetref:%s\n" % (realseason, realepisode, inetref))
except:
pass
# do the same to check if we can find the date in the subtitle
try:
se = series.ExtractDate(self.persistant['subtitle'])
tvrage = series.TVRageDate(self.persistant['title'], se[0], se[1], se[2])
ttvdb = series.TTVDBDate(self.persistant['title'], se[0], se[1], se[2])
if ttvdb:
titledescription = ttvdb
else:
titledescription = tvrage
self.persistant['subtitle'] = titledescription[0]
self.persistant['description'] = titledescription[1]
realseason = titledescription[2]
realepisode = titledescription[3]
# update start and finish if we have the correct date from TVRage
start = start.replace (year=se[0], month=se[1], day=se[2])
finish = finish.replace (year=se[0], month=se[1], day=se[2])
inetref = titledescription[4]
if FLAGS.verbose:
out.write("Found on TVRage or TTVDB: S%sE%s inetref:%s\n" % (realseason, realepisode, inetref))
except:
pass
# store aspect ratio
audioprop = ''
# Determine the audioproperties of the video
try:
audioprop = vid.audio_channels_string().upper()
if audioprop == '5.1':
audioprop = 'SURROUND'
except:
pass
# Determine the subtitles of the video
subtitletypes = ''
try:
if vid.subtitle_stream():
subtitletypes = 'NORMAL'
except:
pass
videoprop = ''
try:
videoprop = getAspectRatio(vid.height(), vid.width())
except:
pass
# Archive the original version of the video
archiverow = self.db.GetOneRow('select * from mythnettv_archive '
'where title="%s"'
% self.persistant['title'])
if archiverow:
archive_location = ('%s/%s_%s'
%(archiverow['path'],
SafeForFilename(self.persistant['title']),
SafeForFilename(self.persistant['subtitle'])))
out.write('Possible archive location: %s\n' % archive_location)
if self.persistant['url'].startswith(archiverow['path']):
out.write('File was imported from the archive location, '
'not archiving\n')
elif not os.path.exists(archive_location):
out.write('Archiving the original\n')
shutil.copyfile(filename, archive_location)
else:
out.write('Archive destination already exists\n')
transcoded_filename = filename.split('/')[-1]
out.write('Importing video %s...\n' % self.persistant['guid'])
epoch = time.mktime(datetime.datetime.utcnow().timetuple())
dest_file = '%d_%s' %(epoch, transcoded_filename.replace(' ', '_'))
# moving is better than copying as it uses less space and
# once the file is gone, it can not be imported again
try:
shutil.move('%s' % filename,
'%s/%s' %(videodir, dest_file))
except:
out.write('Problem: moving %s did not work, please check file permissions.\n Will copy instead.' % filename)
shutil.copy('%s' % filename,
'%s/%s' %(videodir, dest_file))
# clean up after us...
try:
if self.persistant['mime_type'] == 'application/x-bittorrent':
if FLAGS.verbose:
out.write('deleting temporary directory %s...\n' % self.persistant['tmp_name'])
try:
shutil.rmtree(self.persistant['tmp_name'])
except:
out.write('Error: deleting temporary directory %s. Delete manually.\n' % self.persistant['tmp_name'])
except:
pass
# Ensure sensible permissions on the recording that MythTV stores
os.chmod('%s/%s' %(videodir, dest_file),
stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP |
stat.S_IROTH | stat.S_IWOTH)
filestats = os.stat('%s/%s' %(videodir, dest_file))
self.persistant['size'] = filestats [stat.ST_SIZE]
try:
if not self.persistant['description']:
self.persistant['description'] = ''
if FLAGS.verbose:
out.write('Empty description field\n')
if not self.persistant['subtitle']:
if FLAGS.verbose:
out.write('Empty subtitle field\n')
self.persistant['subtitle'] = ''
except:
self.persistant['description'] = ''
self.persistant['subtitle'] = ''
pass
# add the recording to the database using the MythTV python bindings
tmp_recorded={} # we need a place to store
tmp_recorded[u'chanid'] = chanid
tmp_recorded[u'starttime'] = start
tmp_recorded[u'endtime'] = finish
tmp_recorded[u'title'] = self.persistant['title']
tmp_recorded[u'subtitle'] = self.persistant['subtitle']
tmp_recorded[u'season'] = realseason
tmp_recorded[u'episode'] = realepisode
if self.persistant['description'] == ' ':
tmp_recorded[u'description'] = ''
else:
tmp_recorded[u'description'] = self.persistant['description']
tmp_recorded[u'progstart'] = start
tmp_recorded[u'progend'] = finish
tmp_recorded[u'basename'] = dest_file
tmp_recorded[u'filesize'] = self.persistant['size']
tmp_recorded[u'lastmodified'] = datetime.datetime.utcnow()
# tmp_recorded[u'hostname'] = socket.gethostname()
# If Recgroup add to database
row = self.db.GetOneRow('select * from mythnettv_group where '
'title="%s";'
% self.persistant['title'])
if row:
if FLAGS.verbose:
out.write('Setting recording group to %s\n' % row['recgroup'])
tmp_recorded[u'recgroup'] = row['recgroup']
tmp_recorded[u'category'] = row['recgroup']
# If there is a category set for this subscription, then set that as well
#row = self.db.GetOneRow('select * from mythnettv_category where '
# 'title="%s";'
# % self.persistant['title'])
#if row:
# if FLAGS.verbose:
# out.write('Setting category to %s\n' % row['category'])
# tmp_recorded[u'category'] = row['category']
# Ditto the inetref
row = self.db.GetOneRow('select * from mythnettv_subscriptions where '
'title="%s";'
% self.persistant['title'])
# if we got an inetref from the TTVDB use it
if inetref:
if FLAGS.verbose:
out.write('Setting the inetref to %s\n' % inetref)
tmp_recorded[u'inetref'] = inetref
# else use the one provided by the subscription
elif row:
if FLAGS.verbose:
out.write('Setting the inetref to %s\n' % row['inetref'])
tmp_recorded[u'inetref'] = row['inetref']
# stet the playgroup if available
if row:
if FLAGS.verbose:
out.write('Setting the playgroup to %s\n' % row['playgroup'])
try:
tmp_recorded[u'playgroup'] = row['playgroup']
except:
pass
tmp_recorded[u'audioprop'] = audioprop
tmp_recorded[u'subtitletypes'] = subtitletypes
tmp_recorded[u'videoprop'] = videoprop
#FIXME: we could get this from TTVDB
tmp_recorded[u'originalairdate'] = '0000-00-00'
try:
new_rec = Recorded().create(tmp_recorded)
# add recordedprogram information using the MythTV python bindings
new_recprog = RecordedProgram().create(tmp_recorded)
new_oldrec = OldRecorded().create(tmp_recorded)
except:
start = datetime.datetime.now()
tmp_recorded[u'starttime'] = start
new_rec = Recorded().create(tmp_recorded)
# add recordedprogram information using the MythTV python bindings
new_recprog = RecordedProgram().create(tmp_recorded)
new_oldrec = OldRecorded().create(tmp_recorded)
#bug! the python bindings do not parse the chanid and start time to _refdat correcty.
# do it manually. Needs to be corrected!!
#fixedstart = datetime.datetime.fromtimestamp(time.mktime(time.gmtime(time.mktime(start.timetuple()))))
fixedstart = start + 1 * timedelta(seconds=time.timezone) # Fix for database correcting timezone
new_rec.markup._refdat = (chanid, fixedstart.strftime("%Y-%m-%d %H:%M:%S"))
# just to see how the _refdat is wrong:
if FLAGS.verbose:
print(new_rec.markup._refdat)
#if we can get the right aspect ratio store it to maruptable
if vid.height() and vid.width():
new_rec.markup.add(1,aspectType(self, vid.height(), vid.width(), chanid, start), None)
# if the height and/or width of the recording is known, store it in the markuptable
if vid.height():
if FLAGS.verbose:
out.write(' Storing height: %s\n' % vid.height())
new_rec.markup.add(1,31,vid.height())
if vid.width():
if FLAGS.verbose:
out.write(' Storing width: %s\n' % vid.width())
new_rec.markup.add(1,30,vid.width())
new_rec.markup.commit()
# and now store markup to database
new_rec.update()
self.SetImported()
#notification.notify(socket.gethostbyname(socket.gethostname()),'MythNetTV show imported', 'A new show was imported. %s. %s. %s.' % (tmp_recorded[u'title'], tmp_recorded[u'subtitle'], tmp_recorded[u'description']), tmp_recorded[u'recgroup'])
out.write('Finished\n\n')
# And now mark the video as imported
return
def SetImported(self):
"""SetImported -- flag this program as having been imported"""
self.persistant['download_finished'] = 1
self.persistant['imported'] = 1
self.Store()
def SetNew(self):
"""SetNew -- make a program look like its new"""
for field in ['download_started', 'download_finished', 'imported',
'imported', 'transfered', 'size', 'filename',
'inactive', 'attempts', 'failed']:
self.persistant[field] = None
self.Store()
def SetAttempts(self, count):
"""SetAttempts -- set the attempt count"""
self.persistant['attempts'] = count
self.Store()
def Unfail(self):
"""Unfail -- unmark a program as failed"""
self.persistant['download_finished'] = None
self.persistant['failed'] = None
self.persistant['attempts'] = 0
self.persistant['last_attempt'] = None
self.Store()
def TVRage(self, showtitle, out=sys.stdout):
"""TVRage -- Get episode information from TVRage"""
try:
show = tvrage.api.Show(showtitle)
except:
return
#out.write('Show Name: ' + show.name + '\n')
#out.write('Seasons: ' + str(show.seasons) + '\n')
#out.write('Last episode: ' + str(show.latest_episode) + '\n')
#showtitle = "The Daily Show with Jon Stewart"
season = 0
#loop for all recordings in the database that have the same show name