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.

263 lines
10 KiB

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 - tool to upload videos to Peertube and Youtube
  5. Usage:
  6. prismedia --file=<FILE> [options]
  7. prismedia -f <FILE> --tags=STRING [options]
  8. prismedia -h | --help
  9. prismedia --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. --peertubeAt=DATE
  34. --youtubeAt=DATE Override publishAt for the corresponding platform. Allow to create preview on specific platform
  35. --thumbnail=STRING Path to a file to use as a thumbnail for the video.
  36. Supported types are jpg and jpeg.
  37. By default, prismedia search for an image based on video name followed by .jpg or .jpeg
  38. --channel=STRING Set the channel to use for the video (Peertube only)
  39. If the channel is not found, spawn an error except if --channelCreate is set.
  40. --channelCreate Create the channel if not exists. (Peertube only, default do not create)
  41. Only relevant if --channel is set.
  42. --playlist=STRING Set the playlist to use for the video.
  43. If the playlist is not found, spawn an error except if --playlistCreate is set.
  44. --playlistCreate Create the playlist if not exists. (default do not create)
  45. Only relevant if --playlist is set.
  46. -h --help Show this help.
  47. --version Show version.
  48. Categories:
  49. Category is the type of video you upload. Default is films.
  50. Here are available categories from Peertube and Youtube:
  51. music, films, vehicles,
  52. sports, travels, gaming, people,
  53. comedy, entertainment, news,
  54. how to, education, activism, science & technology,
  55. science, technology, animals
  56. Languages:
  57. Language of the video (audio track), choose one. Default is English
  58. Here are available languages from Peertube and Youtube:
  59. Arabic, English, French, German, Hindi, Italian,
  60. Japanese, Korean, Mandarin, Portuguese, Punjabi, Russian, Spanish
  61. """
  62. import sys
  63. if sys.version_info[0] < 3:
  64. raise Exception("Python 3 or a more recent version is required.")
  65. import datetime
  66. import logging
  67. logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
  68. from docopt import docopt
  69. from . import yt_upload
  70. from . import pt_upload
  71. from . import utils
  72. try:
  73. # noinspection PyUnresolvedReferences
  74. from schema import Schema, And, Or, Optional, SchemaError
  75. except ImportError:
  76. logging.error('This program requires that the `schema` data-validation library'
  77. ' is installed: \n'
  78. 'see https://github.com/halst/schema\n')
  79. exit(1)
  80. try:
  81. # noinspection PyUnresolvedReferences
  82. import magic
  83. except ImportError:
  84. logging.error('This program requires that the `python-magic` library'
  85. ' is installed, NOT the Python bindings to libmagic API \n'
  86. 'see https://github.com/ahupp/python-magic\n')
  87. exit(1)
  88. VERSION = "prismedia v0.9.0"
  89. VALID_PRIVACY_STATUSES = ('public', 'private', 'unlisted')
  90. VALID_CATEGORIES = (
  91. "music", "films", "vehicles",
  92. "sports", "travels", "gaming", "people",
  93. "comedy", "entertainment", "news",
  94. "how to", "education", "activism", "science & technology",
  95. "science", "technology", "animals"
  96. )
  97. VALID_PLATFORM = ('youtube', 'peertube', 'none')
  98. VALID_LANGUAGES = ('arabic', 'english', 'french',
  99. 'german', 'hindi', 'italian',
  100. 'japanese', 'korean', 'mandarin',
  101. 'portuguese', 'punjabi', 'russian', 'spanish')
  102. def validateVideo(path):
  103. supported_types = ['video/mp4']
  104. if magic.from_file(path, mime=True) in supported_types:
  105. return path
  106. else:
  107. return False
  108. def validateCategory(category):
  109. if category.lower() in VALID_CATEGORIES:
  110. return True
  111. else:
  112. return False
  113. def validatePrivacy(privacy):
  114. if privacy.lower() in VALID_PRIVACY_STATUSES:
  115. return True
  116. else:
  117. return False
  118. def validatePlatform(platform):
  119. for plfrm in platform.split(','):
  120. if plfrm.lower().replace(" ", "") not in VALID_PLATFORM:
  121. return False
  122. return True
  123. def validateLanguage(language):
  124. if language.lower() in VALID_LANGUAGES:
  125. return True
  126. else:
  127. return False
  128. def validatePublish(publish):
  129. # Check date format and if date is future
  130. try:
  131. now = datetime.datetime.now()
  132. publishAt = datetime.datetime.strptime(publish, '%Y-%m-%dT%H:%M:%S')
  133. if now >= publishAt:
  134. return False
  135. except ValueError:
  136. return False
  137. return True
  138. def validateThumbnail(thumbnail):
  139. supported_types = ['image/jpg', 'image/jpeg']
  140. if magic.from_file(thumbnail, mime=True) in supported_types:
  141. return thumbnail
  142. else:
  143. return False
  144. def main():
  145. options = docopt(__doc__, version=VERSION)
  146. schema = Schema({
  147. '--file': And(str, validateVideo, error='file is not supported, please use mp4'),
  148. Optional('--name'): Or(None, And(
  149. str,
  150. lambda x: not x.isdigit(),
  151. error="The video name should be a string")
  152. ),
  153. Optional('--description'): Or(None, And(
  154. str,
  155. lambda x: not x.isdigit(),
  156. error="The video description should be a string")
  157. ),
  158. Optional('--tags'): Or(None, And(
  159. str,
  160. lambda x: not x.isdigit(),
  161. error="Tags should be a string")
  162. ),
  163. Optional('--category'): Or(None, And(
  164. str,
  165. validateCategory,
  166. error="Category not recognized, please see --help")
  167. ),
  168. Optional('--language'): Or(None, And(
  169. str,
  170. validateLanguage,
  171. error="Language not recognized, please see --help")
  172. ),
  173. Optional('--privacy'): Or(None, And(
  174. str,
  175. validatePrivacy,
  176. error="Please use recognized privacy between public, unlisted or private")
  177. ),
  178. Optional('--nfo'): Or(None, str),
  179. Optional('--platform'): Or(None, And(str, validatePlatform, error="Sorry, upload platform not supported")),
  180. Optional('--publishAt'): Or(None, And(
  181. str,
  182. validatePublish,
  183. error="DATE should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  184. ),
  185. Optional('--peertubeAt'): Or(None, And(
  186. str,
  187. validatePublish,
  188. error="DATE should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  189. ),
  190. Optional('--youtubeAt'): Or(None, And(
  191. str,
  192. validatePublish,
  193. error="DATE should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  194. ),
  195. Optional('--debug'): bool,
  196. Optional('--cca'): bool,
  197. Optional('--disable-comments'): bool,
  198. Optional('--nsfw'): bool,
  199. Optional('--thumbnail'): Or(None, And(
  200. str, validateThumbnail, error='thumbnail is not supported, please use jpg/jpeg'),
  201. ),
  202. Optional('--channel'): Or(None, str),
  203. Optional('--channelCreate'): bool,
  204. Optional('--playlist'): Or(None, str),
  205. Optional('--playlistCreate'): bool,
  206. '--help': bool,
  207. '--version': bool
  208. })
  209. options = utils.parseNFO(options)
  210. if not options.get('--thumbnail'):
  211. options = utils.searchThumbnail(options)
  212. try:
  213. options = schema.validate(options)
  214. except SchemaError as e:
  215. exit(e)
  216. if options.get('--debug'):
  217. print(sys.version)
  218. print(options)
  219. if options.get('--platform') is None or "peertube" in options.get('--platform'):
  220. pt_upload.run(options)
  221. if options.get('--platform') is None or "youtube" in options.get('--platform'):
  222. yt_upload.run(options)
  223. if __name__ == '__main__':
  224. import warnings
  225. warnings.warn("use 'python -m prismedia', not 'python -m prismedia.upload'", DeprecationWarning)
  226. main()