Scripting way to upload videos to peertube and youtube
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

238 lines
7.2 KiB

  1. #!/usr/bin/python
  2. # coding: utf-8
  3. from ConfigParser import RawConfigParser, NoOptionError, NoSectionError
  4. from os.path import dirname, splitext, basename, isfile
  5. from os import devnull
  6. from subprocess import check_call, CalledProcessError, STDOUT
  7. import unicodedata
  8. import logging
  9. ### CATEGORIES ###
  10. YOUTUBE_CATEGORY = {
  11. "music": 10,
  12. "films": 1,
  13. "vehicles": 2,
  14. "sport": 17,
  15. "travels": 19,
  16. "gaming": 20,
  17. "people": 22,
  18. "comedy": 23,
  19. "entertainment": 24,
  20. "news": 25,
  21. "how to": 26,
  22. "education": 27,
  23. "activism": 29,
  24. "science & technology": 28,
  25. "science": 28,
  26. "technology": 28,
  27. "animals": 15
  28. }
  29. PEERTUBE_CATEGORY = {
  30. "music": 1,
  31. "films": 2,
  32. "vehicles": 3,
  33. "sport": 5,
  34. "travels": 6,
  35. "gaming": 7,
  36. "people": 8,
  37. "comedy": 9,
  38. "entertainment": 10,
  39. "news": 11,
  40. "how to": 12,
  41. "education": 13,
  42. "activism": 14,
  43. "science & technology": 15,
  44. "science": 15,
  45. "technology": 15,
  46. "animals": 16
  47. }
  48. ### LANGUAGES ###
  49. YOUTUBE_LANGUAGE = {
  50. "arabic": 'ar',
  51. "english": 'en',
  52. "french": 'fr',
  53. "german": 'de',
  54. "hindi": 'hi',
  55. "italian": 'it',
  56. "japanese": 'ja',
  57. "korean": 'ko',
  58. "mandarin": 'zh-CN',
  59. "portuguese": 'pt-PT',
  60. "punjabi": 'pa',
  61. "russian": 'ru',
  62. "spanish": 'es'
  63. }
  64. PEERTUBE_LANGUAGE = {
  65. "arabic": "ar",
  66. "english": "en",
  67. "french": "fr",
  68. "german": "de",
  69. "hindi": "hi",
  70. "italian": "it",
  71. "japanese": "ja",
  72. "korean": "ko",
  73. "mandarin": "zh",
  74. "portuguese": "pt",
  75. "punjabi": "pa",
  76. "russian": "ru",
  77. "spanish": "es"
  78. }
  79. ######################
  80. def getCategory(category, platform):
  81. if platform == "youtube":
  82. return YOUTUBE_CATEGORY[category.lower()]
  83. else:
  84. return PEERTUBE_CATEGORY[category.lower()]
  85. def getLanguage(language, platform):
  86. if platform == "youtube":
  87. return YOUTUBE_LANGUAGE[language.lower()]
  88. else:
  89. return PEERTUBE_LANGUAGE[language.lower()]
  90. # return the nfo as a RawConfigParser object
  91. def loadNFO(options):
  92. video_directory = dirname(options.get('--file')) + "/"
  93. if options.get('--nfo'):
  94. try:
  95. logging.info("Using " + options.get('--nfo') + " as NFO, loading...")
  96. if isfile(options.get('--nfo')):
  97. nfo = RawConfigParser()
  98. nfo.read(options.get('--nfo'))
  99. return nfo
  100. else:
  101. logging.error("Given NFO file does not exist, please check your path.")
  102. exit(1)
  103. except Exception as e:
  104. logging.error("Problem with NFO file: " + str(e))
  105. exit(1)
  106. else:
  107. if options.get('--name'):
  108. nfo_file = video_directory + options.get('--name') + ".txt"
  109. print nfo_file
  110. if isfile(nfo_file):
  111. try:
  112. logging.info("Using " + nfo_file + " as NFO, loading...")
  113. nfo = RawConfigParser()
  114. nfo.read(nfo_file)
  115. return nfo
  116. except Exception as e:
  117. logging.error("Problem with NFO file: " + str(e))
  118. exit(1)
  119. # if --nfo and --name does not exist, use --file as default
  120. video_file = splitext(basename(options.get('--file')))[0]
  121. nfo_file = video_directory + video_file + ".txt"
  122. if isfile(nfo_file):
  123. try:
  124. logging.info("Using " + nfo_file + " as NFO, loading...")
  125. nfo = RawConfigParser()
  126. nfo.read(nfo_file)
  127. return nfo
  128. except Exception as e:
  129. logging.error("Problem with nfo file: " + str(e))
  130. exit(1)
  131. logging.info("No suitable NFO found, skipping.")
  132. return False
  133. def parseNFO(options):
  134. nfo = loadNFO(options)
  135. if nfo:
  136. # We need to check all options and replace it with the nfo value if not defined (None or False)
  137. for key, value in options.iteritems():
  138. key = key.replace("-", "")
  139. try:
  140. # get string options
  141. if value is None and nfo.get('video', key):
  142. options['--' + key] = nfo.get('video', key)
  143. # get boolean options
  144. elif value is False and nfo.getboolean('video', key):
  145. options['--' + key] = nfo.getboolean('video', key)
  146. except NoOptionError:
  147. continue
  148. except NoSectionError:
  149. logging.error("Given NFO file miss section [video], please check syntax of your NFO.")
  150. exit(1)
  151. return options
  152. def upcaseFirstLetter(s):
  153. return s[0].upper() + s[1:]
  154. def publishAt(publishAt, oauth, url, idvideo, secret):
  155. try:
  156. FNULL = open(devnull, 'w')
  157. check_call(["at", "-V"], stdout=FNULL, stderr=STDOUT)
  158. except CalledProcessError:
  159. logging.error("You need to install the atd daemon to use the publishAt option.")
  160. exit(1)
  161. try:
  162. FNULL = open(devnull, 'w')
  163. check_call(["curl", "-V"], stdout=FNULL, stderr=STDOUT)
  164. except CalledProcessError:
  165. logging.error("You need to install the curl command line to use the publishAt option.")
  166. exit(1)
  167. try:
  168. FNULL = open(devnull, 'w')
  169. check_call(["jq", "-V"], stdout=FNULL, stderr=STDOUT)
  170. except CalledProcessError:
  171. logging.error("You need to install the jq command line to use the publishAt option.")
  172. exit(1)
  173. time = publishAt.split("T")
  174. # Remove leading seconds that atd does not manage
  175. if time[1].count(":") == 2:
  176. time[1] = time[1][:-3]
  177. atTime = time[1] + " " + time[0]
  178. refresh_token=str(oauth.__dict__['_client'].__dict__['refresh_token'])
  179. atFile = "/tmp/peertube_" + idvideo + "_" + publishAt + ".at"
  180. try:
  181. openfile = open(atFile,"w")
  182. openfile.write('token=$(curl -X POST -d "client_id=' + str(secret.get('peertube', 'client_id')) +
  183. '&client_secret=' + str(secret.get('peertube', 'client_secret')) +
  184. '&grant_type=refresh_token&refresh_token=' + str(refresh_token) +
  185. '" "' + url + '/api/v1/users/token" | jq -r .access_token)')
  186. openfile.write("\n")
  187. openfile.write('curl "' + url + '/api/v1/videos/' + idvideo +
  188. '" -X PUT -H "Authorization: Bearer ${token}"' +
  189. ' -H "Content-Type: multipart/form-data" -F "privacy=1"')
  190. openfile.write("\n ") # atd needs an empty line at the end of the file to load...
  191. openfile.close()
  192. except Exception as e:
  193. if hasattr(e, 'message'):
  194. logging.error("Error: " + str(e.message))
  195. else:
  196. logging.error("Error: " + str(e))
  197. try:
  198. FNULL = open(devnull, 'w')
  199. check_call(["at", "-M", "-f", atFile, atTime], stdout=FNULL, stderr=STDOUT)
  200. except Exception as e:
  201. if hasattr(e, 'message'):
  202. logging.error("Error: " + str(e.message))
  203. else:
  204. logging.error("Error: " + str(e))
  205. def mastodonTag(tag):
  206. tags = tag.split(' ')
  207. mtag = ''
  208. for s in tags:
  209. if s == '':
  210. continue
  211. strtag = unicodedata.normalize('NFKD', unicode (s, 'utf-8')).encode('ASCII', 'ignore')
  212. strtag = ''.join(e for e in strtag if e.isalnum())
  213. strtag = upcaseFirstLetter(strtag)
  214. mtag = mtag + strtag
  215. return mtag