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.

243 lines
9.7 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. """
  4. prismedia_upload - tool to upload videos to Peertube and Youtube
  5. Usage:
  6. prismedia_upload.py --file=<FILE> [options]
  7. prismedia_upload.py -f <FILE> --tags=STRING [options]
  8. prismedia_upload.py -h | --help
  9. prismedia_upload.py --version
  10. Options:
  11. -f, --file=STRING Path to the video file to upload in mp4
  12. --name=NAME Name of the video to upload. (default to video filename)
  13. --debug Trigger some debug information like options used (default: no)
  14. -d, --description=STRING Description of the video. (default: default description)
  15. -t, --tags=STRING Tags for the video. comma separated.
  16. WARN: tags with punctuation (!, ', ", ?, ...)
  17. are not supported by Mastodon to be published from Peertube
  18. -c, --category=STRING Category for the videos, see below. (default: Films)
  19. --cca License should be CreativeCommon Attribution (affects Youtube upload only)
  20. -p, --privacy=STRING Choose between public, unlisted or private. (default: private)
  21. --disable-comments Disable comments (Peertube only as YT API does not support) (default: comments are enabled)
  22. --nsfw Set the video as No Safe For Work (Peertube only as YT API does not support) (default: video is safe)
  23. --nfo=STRING Configure a specific nfo file to set options for the video.
  24. By default Prismedia search a .txt based on the video name and will
  25. decode the file as UTF-8 (so make sure your nfo file is UTF-8 encoded)
  26. See nfo_example.txt for more details
  27. --platform=STRING List of platform(s) to upload to, comma separated.
  28. Supported platforms are youtube and peertube (default is both)
  29. --language=STRING Specify the default language for video. See below for supported language. (default is English)
  30. --publishAt=DATE Publish the video at the given DATE using local server timezone.
  31. DATE should be on the form YYYY-MM-DDThh:mm:ss eg: 2018-03-12T19:00:00
  32. DATE should be in the future
  33. --thumbnail=STRING Path to a file to use as a thumbnail for the video.
  34. Supported types are jpg and jpeg.
  35. By default, prismedia search for an image based on video name followed by .jpg or .jpeg
  36. --channel=STRING Set the channel to use for the video (Peertube only)
  37. If the channel is not found, spawn an error except if --channelCreate is set.
  38. --channelCreate Create the channel if not exists. (Peertube only, default do not create)
  39. Only relevant if --channel is set.
  40. --playlist=STRING Set the playlist to use for the video.
  41. If the playlist is not found, spawn an error except if --playlistCreate is set.
  42. --playlistCreate Create the playlist if not exists. (default do not create)
  43. Only relevant if --playlist is set.
  44. -h --help Show this help.
  45. --version Show version.
  46. Categories:
  47. Category is the type of video you upload. Default is films.
  48. Here are available categories from Peertube and Youtube:
  49. music, films, vehicles,
  50. sports, travels, gaming, people,
  51. comedy, entertainment, news,
  52. how to, education, activism, science & technology,
  53. science, technology, animals
  54. Languages:
  55. Language of the video (audio track), choose one. Default is English
  56. Here are available languages from Peertube and Youtube:
  57. Arabic, English, French, German, Hindi, Italian,
  58. Japanese, Korean, Mandarin, Portuguese, Punjabi, Russian, Spanish
  59. """
  60. import sys
  61. if sys.version_info[0] < 3:
  62. raise Exception("Python 3 or a more recent version is required.")
  63. from os.path import dirname, realpath
  64. import datetime
  65. import locale
  66. import logging
  67. logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
  68. from docopt import docopt
  69. # Allows a relative import from the parent folder
  70. sys.path.insert(0, dirname(realpath(__file__)) + "/lib")
  71. import yt_upload
  72. import pt_upload
  73. import utils
  74. try:
  75. # noinspection PyUnresolvedReferences
  76. from schema import Schema, And, Or, Optional, SchemaError
  77. except ImportError:
  78. logging.error('This program requires that the `schema` data-validation library'
  79. ' is installed: \n'
  80. 'see https://github.com/halst/schema\n')
  81. exit(1)
  82. try:
  83. # noinspection PyUnresolvedReferences
  84. import magic
  85. except ImportError:
  86. logging.error('This program requires that the `python-magic` library'
  87. ' is installed, NOT the Python bindings to libmagic API \n'
  88. 'see https://github.com/ahupp/python-magic\n')
  89. exit(1)
  90. VERSION = "prismedia v0.8.0"
  91. VALID_PRIVACY_STATUSES = ('public', 'private', 'unlisted')
  92. VALID_CATEGORIES = (
  93. "music", "films", "vehicles",
  94. "sports", "travels", "gaming", "people",
  95. "comedy", "entertainment", "news",
  96. "how to", "education", "activism", "science & technology",
  97. "science", "technology", "animals"
  98. )
  99. VALID_PLATFORM = ('youtube', 'peertube', 'none')
  100. VALID_LANGUAGES = ('arabic', 'english', 'french',
  101. 'german', 'hindi', 'italian',
  102. 'japanese', 'korean', 'mandarin',
  103. 'portuguese', 'punjabi', 'russian', 'spanish')
  104. def validateVideo(path):
  105. supported_types = ['video/mp4']
  106. if magic.from_file(path, mime=True) in supported_types:
  107. return path
  108. else:
  109. return False
  110. def validateCategory(category):
  111. if category.lower() in VALID_CATEGORIES:
  112. return True
  113. else:
  114. return False
  115. def validatePrivacy(privacy):
  116. if privacy.lower() in VALID_PRIVACY_STATUSES:
  117. return True
  118. else:
  119. return False
  120. def validatePlatform(platform):
  121. for plfrm in platform.split(','):
  122. if plfrm.lower().replace(" ", "") not in VALID_PLATFORM:
  123. return False
  124. return True
  125. def validateLanguage(language):
  126. if language.lower() in VALID_LANGUAGES:
  127. return True
  128. else:
  129. return False
  130. def validatePublish(publish):
  131. # Check date format and if date is future
  132. try:
  133. now = datetime.datetime.now()
  134. publishAt = datetime.datetime.strptime(publish, '%Y-%m-%dT%H:%M:%S')
  135. if now >= publishAt:
  136. return False
  137. except ValueError:
  138. return False
  139. return True
  140. def validateThumbnail(thumbnail):
  141. supported_types = ['image/jpg', 'image/jpeg']
  142. if magic.from_file(thumbnail, mime=True) in supported_types:
  143. return thumbnail
  144. else:
  145. return False
  146. if __name__ == '__main__':
  147. options = docopt(__doc__, version=VERSION)
  148. schema = Schema({
  149. '--file': And(str, validateVideo, error='file is not supported, please use mp4'),
  150. Optional('--name'): Or(None, And(
  151. str,
  152. lambda x: not x.isdigit(),
  153. error="The video name should be a string")
  154. ),
  155. Optional('--description'): Or(None, And(
  156. str,
  157. lambda x: not x.isdigit(),
  158. error="The video description should be a string")
  159. ),
  160. Optional('--tags'): Or(None, And(
  161. str,
  162. lambda x: not x.isdigit(),
  163. error="Tags should be a string")
  164. ),
  165. Optional('--category'): Or(None, And(
  166. str,
  167. validateCategory,
  168. error="Category not recognized, please see --help")
  169. ),
  170. Optional('--language'): Or(None, And(
  171. str,
  172. validateLanguage,
  173. error="Language not recognized, please see --help")
  174. ),
  175. Optional('--privacy'): Or(None, And(
  176. str,
  177. validatePrivacy,
  178. error="Please use recognized privacy between public, unlisted or private")
  179. ),
  180. Optional('--nfo'): Or(None, str),
  181. Optional('--platform'): Or(None, And(str, validatePlatform, error="Sorry, upload platform not supported")),
  182. Optional('--publishAt'): Or(None, And(
  183. str,
  184. validatePublish,
  185. error="DATE should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  186. ),
  187. Optional('--debug'): bool,
  188. Optional('--cca'): bool,
  189. Optional('--disable-comments'): bool,
  190. Optional('--nsfw'): bool,
  191. Optional('--thumbnail'): Or(None, And(
  192. str, validateThumbnail, error='thumbnail is not supported, please use jpg/jpeg'),
  193. ),
  194. Optional('--channel'): Or(None, str),
  195. Optional('--channelCreate'): bool,
  196. Optional('--playlist'): Or(None, str),
  197. Optional('--playlistCreate'): bool,
  198. '--help': bool,
  199. '--version': bool
  200. })
  201. options = utils.parseNFO(options)
  202. if not options.get('--thumbnail'):
  203. options = utils.searchThumbnail(options)
  204. try:
  205. options = schema.validate(options)
  206. except SchemaError as e:
  207. exit(e)
  208. if options.get('--debug'):
  209. print(sys.version)
  210. print(options)
  211. if options.get('--platform') is None or "peertube" in options.get('--platform'):
  212. pt_upload.run(options)
  213. if options.get('--platform') is None or "youtube" in options.get('--platform'):
  214. yt_upload.run(options)