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.

239 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
6 years ago
  1. #!/usr/bin/env python3
  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. -d, --description=STRING Description of the video. (default: default description)
  14. -t, --tags=STRING Tags for the video. comma separated.
  15. WARN: tags with space and special characters (!, ', ", ?, ...)
  16. are not supported by Mastodon to be published from Peertube
  17. use mastodon compatibility below
  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. For Peertube, requires the "atd" and "curl utilities installed on the system
  34. --thumbnail=STRING Path to a file to use as a thumbnail for the video.
  35. Supported types are jpg and jpeg.
  36. By default, prismedia search for an image based on video name followed by .jpg or .jpeg
  37. --channel=STRING Set the channel to use for the video (Peertube only)
  38. If the channel is not found, spawn an error except if --channelCreate is set.
  39. --channelCreate Create the channel if not exists. (Peertube only, default do not create)
  40. Only relevant if --channel is set.
  41. --playlist=STRING Set the playlist to use for the video. Also known as Channel for Peertube.
  42. If the playlist is not found, spawn an error except if --playlistCreate is set.
  43. --playlistCreate Create the playlist if not exists. (default do not create)
  44. Only relevant if --playlist is set.
  45. -h --help Show this help.
  46. --version Show version.
  47. Categories:
  48. Category is the type of video you upload. Default is films.
  49. Here are available categories from Peertube and Youtube:
  50. music, films, vehicles,
  51. sports, travels, gaming, people,
  52. comedy, entertainment, news,
  53. how to, education, activism, science & technology,
  54. science, technology, animals
  55. Languages:
  56. Language of the video (audio track), choose one. Default is English
  57. Here are available languages from Peertube and Youtube:
  58. Arabic, English, French, German, Hindi, Italian,
  59. Japanese, Korean, Mandarin, Portuguese, Punjabi, Russian, Spanish
  60. """
  61. from os.path import dirname, realpath
  62. import sys
  63. import datetime
  64. import locale
  65. import logging
  66. logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
  67. from docopt import docopt
  68. # Allows a relative import from the parent folder
  69. sys.path.insert(0, dirname(realpath(__file__)) + "/lib")
  70. import yt_upload
  71. import pt_upload
  72. import utils
  73. try:
  74. # noinspection PyUnresolvedReferences
  75. from schema import Schema, And, Or, Optional, SchemaError
  76. except ImportError:
  77. logging.error('This program requires that the `schema` data-validation library'
  78. ' is installed: \n'
  79. 'see https://github.com/halst/schema\n')
  80. exit(1)
  81. try:
  82. # noinspection PyUnresolvedReferences
  83. import magic
  84. except ImportError:
  85. logging.error('This program requires that the `python-magic` library'
  86. ' is installed, NOT the Python bindings to libmagic API \n'
  87. 'see https://github.com/ahupp/python-magic\n')
  88. exit(1)
  89. if sys.version_info[0] < 3:
  90. raise Exception("Python 3 or a more recent version is required.")
  91. VERSION = "prismedia v0.7.1"
  92. VALID_PRIVACY_STATUSES = ('public', 'private', 'unlisted')
  93. VALID_CATEGORIES = (
  94. "music", "films", "vehicles",
  95. "sports", "travels", "gaming", "people",
  96. "comedy", "entertainment", "news",
  97. "how to", "education", "activism", "science & technology",
  98. "science", "technology", "animals"
  99. )
  100. VALID_PLATFORM = ('youtube', 'peertube')
  101. VALID_LANGUAGES = ('arabic', 'english', 'french',
  102. 'german', 'hindi', 'italian',
  103. 'japanese', 'korean', 'mandarin',
  104. 'portuguese', 'punjabi', 'russian', 'spanish')
  105. def validateVideo(path):
  106. supported_types = ['video/mp4']
  107. if magic.from_file(path, mime=True) in supported_types:
  108. return path
  109. else:
  110. return False
  111. def validateCategory(category):
  112. if category.lower() in VALID_CATEGORIES:
  113. return True
  114. else:
  115. return False
  116. def validatePrivacy(privacy):
  117. if privacy.lower() in VALID_PRIVACY_STATUSES:
  118. return True
  119. else:
  120. return False
  121. def validatePlatform(platform):
  122. for plfrm in platform.split(','):
  123. if plfrm.lower().replace(" ", "") not in VALID_PLATFORM:
  124. return False
  125. return True
  126. def validateLanguage(language):
  127. if language.lower() in VALID_LANGUAGES:
  128. return True
  129. else:
  130. return False
  131. def validatePublish(publish):
  132. # Check date format and if date is future
  133. try:
  134. now = datetime.datetime.now()
  135. publishAt = datetime.datetime.strptime(publish, '%Y-%m-%dT%H:%M:%S')
  136. if now >= publishAt:
  137. return False
  138. except ValueError:
  139. return False
  140. return True
  141. def validateThumbnail(thumbnail):
  142. supported_types = ['image/jpg', 'image/jpeg']
  143. if magic.from_file(thumbnail, mime=True) in supported_types:
  144. return thumbnail
  145. else:
  146. return False
  147. if __name__ == '__main__':
  148. options = docopt(__doc__, version=VERSION)
  149. schema = Schema({
  150. '--file': And(str, validateVideo, error='file is not supported, please use mp4'),
  151. Optional('--name'): Or(None, And(
  152. str,
  153. lambda x: not x.isdigit(),
  154. error="The video name should be a string")
  155. ),
  156. Optional('--description'): Or(None, And(
  157. str,
  158. lambda x: not x.isdigit(),
  159. error="The video description should be a string")
  160. ),
  161. Optional('--tags'): Or(None, And(
  162. str,
  163. lambda x: not x.isdigit(),
  164. error="Tags should be a string")
  165. ),
  166. Optional('--category'): Or(None, And(
  167. str,
  168. validateCategory,
  169. error="Category not recognized, please see --help")
  170. ),
  171. Optional('--language'): Or(None, And(
  172. str,
  173. validateLanguage,
  174. error="Language not recognized, please see --help")
  175. ),
  176. Optional('--privacy'): Or(None, And(
  177. str,
  178. validatePrivacy,
  179. error="Please use recognized privacy between public, unlisted or private")
  180. ),
  181. Optional('--nfo'): Or(None, str),
  182. Optional('--platform'): Or(None, And(str, validatePlatform, error="Sorry, upload platform not supported")),
  183. Optional('--publishAt'): Or(None, And(
  184. str,
  185. validatePublish,
  186. error="DATE should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  187. ),
  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('--platform') is None or "youtube" in options.get('--platform'):
  209. yt_upload.run(options)
  210. if options.get('--platform') is None or "peertube" in options.get('--platform'):
  211. pt_upload.run(options)