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.2 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 python2
  2. # coding: utf-8
  3. """
  4. prismedia - 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 video name
  25. See nfo_example.txt for more details
  26. --platform=STRING List of platform(s) to upload to, comma separated.
  27. Supported platforms are youtube and peertube (default is both)
  28. --language=STRING Specify the default language for video. See below for supported language. (default is English)
  29. --publishAt=DATE Publish the video at the given DATE using local server timezone.
  30. DATE should be on the form YYYY-MM-DDThh:mm:ss eg: 2018-03-12T19:00:00
  31. DATE should be in the future
  32. For Peertube, requires the "atd" and "curl utilities installed on the system
  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. --playlist=STRING Set the playlist to use for the video. Also known as Channel for Peertube.
  37. If the playlist is not found, spawn an error except if --playlist-create is set.
  38. --playlistCreate Create the playlist if not exists. (default do not create)
  39. Only relevant if --playlist is set.
  40. -h --help Show this help.
  41. --version Show version.
  42. Categories:
  43. Category is the type of video you upload. Default is films.
  44. Here are available categories from Peertube and Youtube:
  45. music, films, vehicles,
  46. sports, travels, gaming, people,
  47. comedy, entertainment, news,
  48. how to, education, activism, science & technology,
  49. science, technology, animals
  50. Languages:
  51. Language of the video (audio track), choose one. Default is English
  52. Here are available languages from Peertube and Youtube:
  53. Arabic, English, French, German, Hindi, Italian,
  54. Japanese, Korean, Mandarin, Portuguese, Punjabi, Russian, Spanish
  55. """
  56. import datetime
  57. import locale
  58. import logging
  59. logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
  60. from docopt import docopt
  61. from . import yt_upload
  62. from . import pt_upload
  63. from . import utils
  64. try:
  65. # noinspection PyUnresolvedReferences
  66. from schema import Schema, And, Or, Optional, SchemaError
  67. except ImportError:
  68. logging.error('This program requires that the `schema` data-validation library'
  69. ' is installed: \n'
  70. 'see https://github.com/halst/schema\n')
  71. exit(1)
  72. try:
  73. # noinspection PyUnresolvedReferences
  74. import magic
  75. except ImportError:
  76. logging.error('This program requires that the `python-magic` library'
  77. ' is installed, NOT the Python bindings to libmagic API \n'
  78. 'see https://github.com/ahupp/python-magic\n')
  79. exit(1)
  80. VERSION = "prismedia v0.6.2"
  81. VALID_PRIVACY_STATUSES = ('public', 'private', 'unlisted')
  82. VALID_CATEGORIES = (
  83. "music", "films", "vehicles",
  84. "sports", "travels", "gaming", "people",
  85. "comedy", "entertainment", "news",
  86. "how to", "education", "activism", "science & technology",
  87. "science", "technology", "animals"
  88. )
  89. VALID_PLATFORM = ('youtube', 'peertube')
  90. VALID_LANGUAGES = ('arabic', 'english', 'french',
  91. 'german', 'hindi', 'italian',
  92. 'japanese', 'korean', 'mandarin',
  93. 'portuguese', 'punjabi', 'russian', 'spanish')
  94. def validateVideo(path):
  95. supported_types = ['video/mp4']
  96. if magic.from_file(path, mime=True) in supported_types:
  97. return path
  98. else:
  99. return False
  100. def validateCategory(category):
  101. if category.lower() in VALID_CATEGORIES:
  102. return True
  103. else:
  104. return False
  105. def validatePrivacy(privacy):
  106. if privacy.lower() in VALID_PRIVACY_STATUSES:
  107. return True
  108. else:
  109. return False
  110. def validatePlatform(platform):
  111. for plfrm in platform.split(','):
  112. if plfrm.lower().replace(" ", "") not in VALID_PLATFORM:
  113. return False
  114. return True
  115. def validateLanguage(language):
  116. if language.lower() in VALID_LANGUAGES:
  117. return True
  118. else:
  119. return False
  120. def validatePublish(publish):
  121. # Check date format and if date is future
  122. try:
  123. now = datetime.datetime.now()
  124. publishAt = datetime.datetime.strptime(publish, '%Y-%m-%dT%H:%M:%S')
  125. if now >= publishAt:
  126. return False
  127. except ValueError:
  128. return False
  129. return True
  130. def validateThumbnail(thumbnail):
  131. supported_types = ['image/jpg', 'image/jpeg']
  132. if magic.from_file(thumbnail, mime=True) in supported_types:
  133. return thumbnail
  134. else:
  135. return False
  136. def main():
  137. options = docopt(__doc__, version=VERSION)
  138. schema = Schema({
  139. '--file': And(str, validateVideo, error='file is not supported, please use mp4'),
  140. Optional('--name'): Or(None, And(
  141. basestring,
  142. lambda x: not x.isdigit(),
  143. error="The video name should be a string")
  144. ),
  145. Optional('--description'): Or(None, And(
  146. basestring,
  147. lambda x: not x.isdigit(),
  148. error="The video description should be a string")
  149. ),
  150. Optional('--tags'): Or(None, And(
  151. basestring,
  152. lambda x: not x.isdigit(),
  153. error="Tags should be a string")
  154. ),
  155. Optional('--category'): Or(None, And(
  156. str,
  157. validateCategory,
  158. error="Category not recognized, please see --help")
  159. ),
  160. Optional('--language'): Or(None, And(
  161. str,
  162. validateLanguage,
  163. error="Language not recognized, please see --help")
  164. ),
  165. Optional('--privacy'): Or(None, And(
  166. str,
  167. validatePrivacy,
  168. error="Please use recognized privacy between public, unlisted or private")
  169. ),
  170. Optional('--nfo'): Or(None, str),
  171. Optional('--platform'): Or(None, And(str, validatePlatform, error="Sorry, upload platform not supported")),
  172. Optional('--publishAt'): Or(None, And(
  173. str,
  174. validatePublish,
  175. error="DATE should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  176. ),
  177. Optional('--cca'): bool,
  178. Optional('--disable-comments'): bool,
  179. Optional('--nsfw'): bool,
  180. Optional('--thumbnail'): Or(None, And(
  181. str, validateThumbnail, error='thumbnail is not supported, please use jpg/jpeg'),
  182. ),
  183. Optional('--playlist'): Or(None, str),
  184. Optional('--playlistCreate'): bool,
  185. '--help': bool,
  186. '--version': bool
  187. })
  188. utils.decodeArgumentStrings(options, locale.getpreferredencoding())
  189. options = utils.parseNFO(options)
  190. if not options.get('--thumbnail'):
  191. options = utils.searchThumbnail(options)
  192. try:
  193. options = schema.validate(options)
  194. except SchemaError as e:
  195. exit(e)
  196. if options.get('--platform') is None or "youtube" in options.get('--platform'):
  197. yt_upload.run(options)
  198. if options.get('--platform') is None or "peertube" in options.get('--platform'):
  199. pt_upload.run(options)
  200. if __name__ == '__main__':
  201. import warnings
  202. warnings.warn("use 'python -m prismedia', not 'python -m prismedia.upload'", DeprecationWarning)
  203. main()