Advertisement
Guest User

Import Videos to MythTV

a guest
Jun 28th, 2016
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.67 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import sys
  5. import imaplib
  6. import email
  7. import datetime
  8. import re
  9. import subprocess
  10. import os
  11. import shutil
  12. import socket
  13. import glob
  14. import json
  15. from pprint import pprint
  16. from stat import *
  17. import urllib2
  18. import xml.etree.ElementTree as ET
  19.  
  20. import MythTV
  21. from MythTV import MythDB, Recorded
  22. from MythTV.database import DBDataWrite
  23.  
  24. reURLs = re.compile(r"""((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.‌​][a-z]{2,4}/)(?:[^\s()<>]+|(([^\s()<>]+|(([^\s()<>]+)))*))+(?:(([^\s()<>]+|(‌​([^\s()<>]+)))*)|[^\s`!()[]{};:'".,<>?«»“”‘’]))""", re.DOTALL)
  25. reHTTP = re.compile('^http.*(youtu.?be|vimeo)')
  26. reSPAM = re.compile('.*email_spam.*')
  27. rePlus = re.compile('[+]([^@]+)')
  28.  
  29. defaultTitle = "Whatever"
  30. gmailUserID = "Someone@gmail.com"
  31. gmailPassword = "very secret"
  32.  
  33.  
  34. def GetURLs(M):
  35.  
  36. videoURLs = { }
  37. msgIDs = [ ]
  38.  
  39. rv, data = M.uid("search", None, "ALL")
  40. if rv != 'OK':
  41. print "No messages found!"
  42. return videoURLs
  43.  
  44. for num in data[0].split():
  45.  
  46. print "Message", num
  47.  
  48. msgIDs.append(num)
  49. rv, data = M.uid("fetch", num, '(RFC822)')
  50. if rv != 'OK':
  51. print "ERROR getting message", num
  52. return videoURLs
  53.  
  54. msg = email.message_from_string(data[0][1])
  55. msgTo = email.utils.parseaddr(msg["To"])[1]
  56. msgPluss = rePlus.findall(msgTo)
  57. msgPlus = msgPluss[0] if len(msgPluss) > 0 else defaultTitle
  58. if not msgPlus in videoURLs:
  59. videoURLs[msgPlus] = set([])
  60. M.store(num, "+X-GM-LABELS", msgPlus)
  61. date_tuple = email.utils.parsedate_tz(msg['Date'])
  62. print msgPlus, msg["Subject"]
  63. for section in msg.walk():
  64. if section.get_content_maintype() == "text":
  65. text = section.get_payload(decode=True)
  66. urls = [ url[0].split('"')[0] for url in reURLs.findall(text) if reHTTP.match(url[0]) and not reSPAM.match(url[0]) ]
  67. if len(urls) > 0:
  68. print " ", urls
  69. videoURLs[msgPlus].update(set(urls))
  70.  
  71. return msgIDs, videoURLs
  72.  
  73.  
  74. def dbRowFromJason(json):
  75. startTime = datetime.datetime.fromtimestamp(vid["modTime"])
  76. endTime = datetime.datetime.fromtimestamp(vid["modTime"] + vid["duration"])
  77.  
  78. row = {
  79. "chanid" : 1000,
  80. "starttime" : startTime.isoformat(),
  81. "endtime" : endTime.isoformat(),
  82. "progstart" : startTime.isoformat(),
  83. "progend" : endTime.isoformat(),
  84. "originalairdate" : startTime.date(),
  85. "lastmodified" : endTime.isoformat(),
  86.  
  87. "category" : 'Podcast',
  88. "seriesid" : json["extractor"],
  89. "programid" : json["display_id"],
  90. "season" : 0,
  91. "episode" : 0,
  92. "inetref" : 0,
  93. "hostname" : socket.gethostname().split(".")[0],
  94. "recgroup" : "Default",
  95. "playgroup" : "Default",
  96. "previouslyshown" : False,
  97. "stars" : 5,
  98. "preserve" : True,
  99. "watched" : False,
  100. "storagegroup" : "Default",
  101. "inputname" : "Internet",
  102.  
  103. "title" : json["EmailTitle"],
  104. "subtitle" : json["fulltitle"],
  105. "description" : json["description"],
  106. "basename" : json["FileName"],
  107. "filesize" : json["FileSize"],
  108.  
  109. "autoexpire" : False
  110. }
  111. return row
  112.  
  113.  
  114. def TargetDisk():
  115. def bumpOne():
  116. TargetDisk.curDisk = (TargetDisk.curDisk % 10) + 1
  117. def target():
  118. return "/disks/d%d/tv" % TargetDisk.curDisk
  119. bumpOne()
  120. while not os.path.exists(target()):
  121. bumpOne()
  122. return target()
  123. TargetDisk.curDisk = 0
  124.  
  125.  
  126. M = imaplib.IMAP4_SSL('imap.gmail.com')
  127.  
  128. try:
  129. M.login(gmailUserID, gmailPassword)
  130. except imaplib.IMAP4.error:
  131. print "LOGIN FAILED!!!"
  132. exit
  133.  
  134. rv, data = M.select("inbox")
  135. if rv == 'OK':
  136. msgIDs, urls = GetURLs(M)
  137.  
  138. if len(urls) > 0:
  139.  
  140. for pref in urls:
  141. dir = "DL/" + pref
  142. if not os.path.exists(dir):
  143. os.makedirs(dir)
  144. cmd = ["youtube-dl", "--write-description", "--write-info-json", "--write-annotations", "--download-archive", "mcDownload.history", "--ignore-errors"]
  145. cmd.extend(["--output", dir + "/%(id)s.%(ext)s"])
  146. cmd.extend(urls[pref])
  147. print cmd
  148. subprocess.call(cmd)
  149.  
  150. resp = urllib2.urlopen("http://localhost:6544/Dvr/GetRecordedList")
  151. tree = ET.parse(resp)
  152. xml = tree.getroot()
  153. existingPrograms = set([ prog.text for prog in list(xml.iter("ProgramId")) if prog.text ])
  154. #existingPrograms = set([ ])
  155.  
  156. if not os.path.exists("Processed"):
  157. os.makedirs("Processed")
  158.  
  159. mythdb = MythDB()
  160.  
  161. for dir in glob.glob("DL/*"):
  162. title = os.path.basename(dir)
  163. print dir, title
  164. if os.path.isdir(dir):
  165. for jsonFile in glob.glob(dir + "/*.info.json"):
  166. print " ", jsonFile
  167. with open(jsonFile) as j:
  168. vid = json.load(j)
  169. vid["FileName"] = vid["display_id"] + "." + vid["ext"]
  170. vid["FullName"] = dir + "/" + vid["FileName"]
  171. print " ", vid["FullName"]
  172. if os.path.exists(vid["FullName"]) and vid["display_id"] not in existingPrograms:
  173. vid["EmailTitle"] = title
  174. fstat = os.stat(vid["FullName"])
  175. vid["modTime"] = fstat.st_mtime
  176. vid["modTimeString"] = datetime.datetime.fromtimestamp(vid["modTime"]).strftime('%Y-%m-%d %H:%M:%S')
  177. vid["FileSize"] = fstat.st_size
  178. print " ", vid["FileName"]
  179. done = False
  180. while not done:
  181. try:
  182. Recorded().create(dbRowFromJason(vid))
  183. done = True
  184. except MythTV.exceptions.MythDBError:
  185. vid["modTime"] += 1
  186. shutil.move(vid["FullName"], TargetDisk())
  187. subprocess.call(["mythcommflag", "--rebuild", "--queue", "--file", vid["FileName"]])
  188. #print dbRowFromJason(vid)
  189. existingPrograms.update([vid["display_id"]])
  190. for supportingFile in glob.glob(dir + "/" + vid["display_id"] + ".*"):
  191. shutil.move(supportingFile, "Processed")
  192.  
  193.  
  194. # gmail doesn't delete with the Deleted flag, it archives
  195. for msgID in msgIDs:
  196. print "archive", msgID
  197. M.store(msgID, "+FLAGS", "\\Deleted")
  198.  
  199.  
  200. M.close()
  201. M.logout()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement