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.

340 lines
14 KiB

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. Strict options:
  49. Strict options allow you to force some option to be present when uploading a video. It's useful to be sure you do not
  50. forget something when uploading a video, for example if you use multiples NFO. You may force the presence of description,
  51. tags, thumbnail, ...
  52. All strict option are optionals and are provided only to avoid errors when uploading :-)
  53. All strict options can be specified in NFO directly, the only strict option mandatory on cli is --withNFO
  54. All strict options are off by default
  55. --withNFO Prevent the upload without a NFO, either specified via cli or found in the directory
  56. --withThumbnail Prevent the upload without a thumbnail
  57. --withName Prevent the upload if no name are found
  58. --withDescription Prevent the upload without description
  59. --withTags Prevent the upload without tags
  60. --withPlaylist Prevent the upload if no playlist
  61. --withPublishAt Prevent the upload if no schedule
  62. --withPlatform Prevent the upload if at least one platform is not specified
  63. --withCategory Prevent the upload if no category
  64. --withLanguage Prevent upload if no language
  65. --withChannel Prevent upload if no channel
  66. Categories:
  67. Category is the type of video you upload. Default is films.
  68. Here are available categories from Peertube and Youtube:
  69. music, films, vehicles,
  70. sports, travels, gaming, people,
  71. comedy, entertainment, news,
  72. how to, education, activism, science & technology,
  73. science, technology, animals
  74. Languages:
  75. Language of the video (audio track), choose one. Default is English
  76. Here are available languages from Peertube and Youtube:
  77. Arabic, English, French, German, Hindi, Italian,
  78. Japanese, Korean, Mandarin, Portuguese, Punjabi, Russian, Spanish
  79. """
  80. import sys
  81. if sys.version_info[0] < 3:
  82. raise Exception("Python 3 or a more recent version is required.")
  83. import os
  84. import datetime
  85. import logging
  86. logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
  87. from docopt import docopt
  88. from . import yt_upload
  89. from . import pt_upload
  90. from . import utils
  91. try:
  92. # noinspection PyUnresolvedReferences
  93. from schema import Schema, And, Or, Optional, SchemaError, Hook
  94. except ImportError:
  95. logging.error('This program requires that the `schema` data-validation library'
  96. ' is installed: \n'
  97. 'see https://github.com/halst/schema\n')
  98. exit(1)
  99. try:
  100. # noinspection PyUnresolvedReferences
  101. import magic
  102. except ImportError:
  103. logging.error('This program requires that the `python-magic` library'
  104. ' is installed, NOT the Python bindings to libmagic API \n'
  105. 'see https://github.com/ahupp/python-magic\n')
  106. exit(1)
  107. VERSION = "prismedia v0.9.1"
  108. VALID_PRIVACY_STATUSES = ('public', 'private', 'unlisted')
  109. VALID_CATEGORIES = (
  110. "music", "films", "vehicles",
  111. "sports", "travels", "gaming", "people",
  112. "comedy", "entertainment", "news",
  113. "how to", "education", "activism", "science & technology",
  114. "science", "technology", "animals"
  115. )
  116. VALID_PLATFORM = ('youtube', 'peertube', 'none')
  117. VALID_LANGUAGES = ('arabic', 'english', 'french',
  118. 'german', 'hindi', 'italian',
  119. 'japanese', 'korean', 'mandarin',
  120. 'portuguese', 'punjabi', 'russian', 'spanish')
  121. def validateVideo(path):
  122. supported_types = ['video/mp4']
  123. detected_type = magic.from_file(path, mime=True)
  124. if detected_type not in supported_types:
  125. print("File", path, "detected type is", detected_type, "which is not one of", supported_types)
  126. force_file = ['y', 'yes']
  127. is_forcing = input("Are you sure you selected the correct file? (y/N)")
  128. if is_forcing.lower() not in force_file:
  129. return False
  130. return path
  131. def validateCategory(category):
  132. if category.lower() in VALID_CATEGORIES:
  133. return True
  134. else:
  135. return False
  136. def validatePrivacy(privacy):
  137. if privacy.lower() in VALID_PRIVACY_STATUSES:
  138. return True
  139. else:
  140. return False
  141. def validatePlatform(platform):
  142. for plfrm in platform.split(','):
  143. if plfrm.lower().replace(" ", "") not in VALID_PLATFORM:
  144. return False
  145. return True
  146. def validateLanguage(language):
  147. if language.lower() in VALID_LANGUAGES:
  148. return True
  149. else:
  150. return False
  151. def validatePublish(publish):
  152. # Check date format and if date is future
  153. try:
  154. now = datetime.datetime.now()
  155. publishAt = datetime.datetime.strptime(publish, '%Y-%m-%dT%H:%M:%S')
  156. if now >= publishAt:
  157. return False
  158. except ValueError:
  159. return False
  160. return True
  161. def validateThumbnail(thumbnail):
  162. supported_types = ['image/jpg', 'image/jpeg']
  163. if os.path.exists(thumbnail) and \
  164. magic.from_file(thumbnail, mime=True) in supported_types:
  165. return thumbnail
  166. else:
  167. return False
  168. def _optionnalOrStrict(key, scope, error):
  169. option = key.replace('-', '')
  170. option = option[0].upper() + option[1:]
  171. if scope["--with" + option] is True and scope[key] is None:
  172. logging.error("Prismedia: you have required the strict presence of " + key + " but none is found")
  173. exit(1)
  174. return True
  175. def main():
  176. options = docopt(__doc__, version=VERSION)
  177. strictoptionSchema = Schema({
  178. Optional('--withNFO', default=False): bool,
  179. Optional('--withThumbnail', default=False): bool,
  180. Optional('--withName', default=False): bool,
  181. Optional('--withDescription', default=False): bool,
  182. Optional('--withTags', default=False): bool,
  183. Optional('--withPlaylist', default=False): bool,
  184. Optional('--withPublishAt', default=False): bool,
  185. Optional('--withPlatform', default=False): bool,
  186. Optional('--withCategory', default=False): bool,
  187. Optional('--withLanguage', default=False): bool,
  188. Optional('--withChannel', default=False): bool,
  189. object: object # This allow to return all other options for further use: https://github.com/keleshev/schema#extra-keys
  190. })
  191. schema = Schema({
  192. '--file': And(str, os.path.exists, validateVideo, error='file is not supported, please use mp4'),
  193. # Strict option checks - at the moment Schema needs to check Hook and Optional separately #
  194. Hook('--name', handler=_optionnalOrStrict): object,
  195. Hook('--description', handler=_optionnalOrStrict): object,
  196. Hook('--tags', handler=_optionnalOrStrict): object,
  197. Hook('--category', handler=_optionnalOrStrict): object,
  198. Hook('--language', handler=_optionnalOrStrict): object,
  199. Hook('--platform', handler=_optionnalOrStrict): object,
  200. Hook('--publishAt', handler=_optionnalOrStrict): object,
  201. Hook('--thumbnail', handler=_optionnalOrStrict): object,
  202. Hook('--channel', handler=_optionnalOrStrict): object,
  203. Hook('--playlist', handler=_optionnalOrStrict): object,
  204. # Validate checks #
  205. Optional('--name'): Or(None, And(
  206. str,
  207. lambda x: not x.isdigit(),
  208. error="The video name should be a string")
  209. ),
  210. Optional('--description'): Or(None, And(
  211. str,
  212. lambda x: not x.isdigit(),
  213. error="The video description should be a string")
  214. ),
  215. Optional('--tags'): Or(None, And(
  216. str,
  217. lambda x: not x.isdigit(),
  218. error="Tags should be a string")
  219. ),
  220. Optional('--category'): Or(None, And(
  221. str,
  222. validateCategory,
  223. error="Category not recognized, please see --help")
  224. ),
  225. Optional('--language'): Or(None, And(
  226. str,
  227. validateLanguage,
  228. error="Language not recognized, please see --help")
  229. ),
  230. Optional('--privacy'): Or(None, And(
  231. str,
  232. validatePrivacy,
  233. error="Please use recognized privacy between public, unlisted or private")
  234. ),
  235. Optional('--nfo'): Or(None, str),
  236. Optional('--platform'): Or(None, And(str, validatePlatform, error="Sorry, upload platform not supported")),
  237. Optional('--publishAt'): Or(None, And(
  238. str,
  239. validatePublish,
  240. error="DATE should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  241. ),
  242. Optional('--peertubeAt'): Or(None, And(
  243. str,
  244. validatePublish,
  245. error="DATE should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  246. ),
  247. Optional('--youtubeAt'): Or(None, And(
  248. str,
  249. validatePublish,
  250. error="DATE should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  251. ),
  252. Optional('--debug'): bool,
  253. Optional('--cca'): bool,
  254. Optional('--disable-comments'): bool,
  255. Optional('--nsfw'): bool,
  256. Optional('--thumbnail'): Or(None, And(
  257. str, validateThumbnail, error='thumbnail is not supported, please use jpg/jpeg'),
  258. ),
  259. Optional('--channel'): Or(None, str),
  260. Optional('--channelCreate'): bool,
  261. Optional('--playlist'): Or(None, str),
  262. Optional('--playlistCreate'): bool,
  263. '--help': bool,
  264. '--version': bool,
  265. object: object # This allow to return all other options for further use: https://github.com/keleshev/schema#extra-keys
  266. })
  267. # We need to validate strict options first as withNFO should be validated before NFO parsing
  268. try:
  269. options = strictoptionSchema.validate(options)
  270. except SchemaError as e:
  271. exit(e)
  272. options = utils.parseNFO(options)
  273. # Once NFO are loaded, we need to revalidate strict options in case some were in NFO
  274. try:
  275. options = strictoptionSchema.validate(options)
  276. except SchemaError as e:
  277. exit(e)
  278. if not options.get('--thumbnail'):
  279. options = utils.searchThumbnail(options)
  280. try:
  281. options = schema.validate(options)
  282. except SchemaError as e:
  283. exit(e)
  284. if options.get('--debug'):
  285. print("Python " + sys.version)
  286. print(options)
  287. if options.get('--platform') is None or "peertube" in options.get('--platform'):
  288. pt_upload.run(options)
  289. if options.get('--platform') is None or "youtube" in options.get('--platform'):
  290. yt_upload.run(options)
  291. if __name__ == '__main__':
  292. import warnings
  293. warnings.warn("use 'python -m prismedia', not 'python -m prismedia.upload'", DeprecationWarning)
  294. main()