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.

407 lines
17 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. This is the only mandatory option.
  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 punctuation (!, ', ", ?, ...)
  16. are not supported by Mastodon to be published from Peertube
  17. -c, --category=STRING Category for the videos, see below. (default: Films)
  18. --cca License should be CreativeCommon Attribution (affects Youtube upload only)
  19. -p, --privacy=STRING Choose between public, unlisted or private. (default: private)
  20. --disable-comments Disable comments (Peertube only as YT API does not support) (default: comments are enabled)
  21. --nsfw Set the video as No Safe For Work (Peertube only as YT API does not support) (default: video is safe)
  22. --nfo=STRING Configure a specific nfo file to set options for the video.
  23. By default Prismedia search a .txt based on the video name and will
  24. decode the file as UTF-8 (so make sure your nfo file is UTF-8 encoded)
  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. --peertubeAt=DATE
  33. --youtubeAt=DATE Override publishAt for the corresponding platform. Allow to create preview on specific platform
  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.
  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. Logging options
  48. -q --quiet Suppress any log except Critical (alias for --log=critical).
  49. --log=STRING Log level, between debug, info, warning, error, critical. Ignored if --quiet is set (default to info)
  50. -u --url-only Display generated URL after upload directly on stdout, implies --quiet
  51. --batch Display generated URL after upload with platform information for easier parsing. Implies --quiet
  52. Be careful --batch and --url-only are mutually exclusives.
  53. --debug (Deprecated) Alias for --log=debug. Ignored if --log is set
  54. Strict options:
  55. Strict options allow you to force some option to be present when uploading a video. It's useful to be sure you do not
  56. forget something when uploading a video, for example if you use multiples NFO. You may force the presence of description,
  57. tags, thumbnail, ...
  58. All strict option are optionals and are provided only to avoid errors when uploading :-)
  59. All strict options can be specified in NFO directly, the only strict option mandatory on cli is --withNFO
  60. All strict options are off by default
  61. --withNFO Prevent the upload without a NFO, either specified via cli or found in the directory
  62. --withThumbnail Prevent the upload without a thumbnail
  63. --withName Prevent the upload if no name are found
  64. --withDescription Prevent the upload without description
  65. --withTags Prevent the upload without tags
  66. --withPlaylist Prevent the upload if no playlist
  67. --withPublishAt Prevent the upload if no schedule
  68. --withPlatform Prevent the upload if at least one platform is not specified
  69. --withCategory Prevent the upload if no category
  70. --withLanguage Prevent upload if no language
  71. --withChannel Prevent upload if no channel
  72. Categories:
  73. Category is the type of video you upload. Default is films.
  74. Here are available categories from Peertube and Youtube:
  75. music, films, vehicles,
  76. sports, travels, gaming, people,
  77. comedy, entertainment, news,
  78. how to, education, activism, science & technology,
  79. science, technology, animals
  80. Languages:
  81. Language of the video (audio track), choose one. Default is English
  82. Here are available languages from Peertube and Youtube:
  83. Arabic, English, French, German, Hindi, Italian,
  84. Japanese, Korean, Mandarin, Portuguese, Punjabi, Russian, Spanish
  85. """
  86. import sys
  87. if sys.version_info[0] < 3:
  88. raise Exception("Python 3 or a more recent version is required.")
  89. import os
  90. import datetime
  91. import logging
  92. logger = logging.getLogger('Prismedia')
  93. logger.setLevel(logging.INFO)
  94. ch = logging.StreamHandler()
  95. ch.setLevel(logging.INFO)
  96. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s')
  97. ch.setFormatter(formatter)
  98. logger.addHandler(ch)
  99. from docopt import docopt
  100. from . import yt_upload
  101. from . import pt_upload
  102. from . import utils
  103. try:
  104. # noinspection PyUnresolvedReferences
  105. from schema import Schema, And, Or, Optional, SchemaError, Hook, Use
  106. except ImportError:
  107. logger.critical('This program requires that the `schema` data-validation library'
  108. ' is installed: \n'
  109. 'see https://github.com/halst/schema\n')
  110. exit(1)
  111. try:
  112. # noinspection PyUnresolvedReferences
  113. import magic
  114. except ImportError:
  115. logger.critical('This program requires that the `python-magic` library'
  116. ' is installed, NOT the Python bindings to libmagic API \n'
  117. 'see https://github.com/ahupp/python-magic\n')
  118. exit(1)
  119. VERSION = "prismedia v0.10.2"
  120. VALID_PRIVACY_STATUSES = ('public', 'private', 'unlisted')
  121. VALID_CATEGORIES = (
  122. "music", "films", "vehicles",
  123. "sports", "travels", "gaming", "people",
  124. "comedy", "entertainment", "news",
  125. "how to", "education", "activism", "science & technology",
  126. "science", "technology", "animals"
  127. )
  128. VALID_PLATFORM = ('youtube', 'peertube', 'none')
  129. VALID_LANGUAGES = ('arabic', 'english', 'french',
  130. 'german', 'hindi', 'italian',
  131. 'japanese', 'korean', 'mandarin',
  132. 'portuguese', 'punjabi', 'russian', 'spanish')
  133. def validateVideo(path):
  134. supported_types = ['video/mp4']
  135. detected_type = magic.from_file(path, mime=True)
  136. if detected_type not in supported_types:
  137. print("File", path, "detected type is", detected_type, "which is not one of", supported_types)
  138. force_file = ['y', 'yes']
  139. is_forcing = input("Are you sure you selected the correct file? (y/N)")
  140. if is_forcing.lower() not in force_file:
  141. return False
  142. return path
  143. def validateCategory(category):
  144. if category.lower() in VALID_CATEGORIES:
  145. return True
  146. else:
  147. return False
  148. def validatePrivacy(privacy):
  149. if privacy.lower() in VALID_PRIVACY_STATUSES:
  150. return True
  151. else:
  152. return False
  153. def validatePlatform(platform):
  154. for plfrm in platform.split(','):
  155. if plfrm.lower().replace(" ", "") not in VALID_PLATFORM:
  156. return False
  157. return True
  158. def validateLanguage(language):
  159. if language.lower() in VALID_LANGUAGES:
  160. return True
  161. else:
  162. return False
  163. def validatePublish(publish):
  164. # Check date format and if date is future
  165. try:
  166. now = datetime.datetime.now()
  167. publishAt = datetime.datetime.strptime(publish, '%Y-%m-%dT%H:%M:%S')
  168. if now >= publishAt:
  169. return False
  170. except ValueError:
  171. return False
  172. return True
  173. def validateThumbnail(thumbnail):
  174. supported_types = ['image/jpg', 'image/jpeg']
  175. if os.path.exists(thumbnail) and \
  176. magic.from_file(thumbnail, mime=True) in supported_types:
  177. return thumbnail
  178. else:
  179. return False
  180. def validateLogLevel(loglevel):
  181. numeric_level = getattr(logging, loglevel, None)
  182. if not isinstance(numeric_level, int):
  183. return False
  184. return True
  185. def _optionnalOrStrict(key, scope, error):
  186. option = key.replace('-', '')
  187. option = option[0].upper() + option[1:]
  188. if scope["--with" + option] is True and scope[key] is None:
  189. logger.critical("Prismedia: you have required the strict presence of " + key + " but none is found")
  190. exit(1)
  191. return True
  192. def configureLogs(options):
  193. if options.get('--batch') and options.get('--url-only'):
  194. logger.critical("Prismedia: Please use either --batch OR --url-only, not both.")
  195. exit(1)
  196. # batch and url-only implies quiet
  197. if options.get('--batch') or options.get('--url-only'):
  198. options['--quiet'] = True
  199. if options.get('--quiet'):
  200. # We need to set both log level in the same time
  201. logger.setLevel(50)
  202. ch.setLevel(50)
  203. elif options.get('--log'):
  204. numeric_level = getattr(logging, options["--log"], None)
  205. # We need to set both log level in the same time
  206. logger.setLevel(numeric_level)
  207. ch.setLevel(numeric_level)
  208. elif options.get('--debug'):
  209. logger.warning("DEPRECATION: --debug is deprecated, please use --log=debug instead")
  210. logger.setLevel(10)
  211. ch.setLevel(10)
  212. def configureStdoutLogs():
  213. logger_stdout = logging.getLogger('stdoutlogs')
  214. logger_stdout.setLevel(logging.INFO)
  215. ch_stdout = logging.StreamHandler(stream=sys.stdout)
  216. ch_stdout.setLevel(logging.INFO)
  217. # Default stdout logs is url only
  218. formatter_stdout = logging.Formatter('%(message)s')
  219. ch_stdout.setFormatter(formatter_stdout)
  220. logger_stdout.addHandler(ch_stdout)
  221. def main():
  222. options = docopt(__doc__, version=VERSION)
  223. earlyoptionSchema = Schema({
  224. Optional('--log'): Or(None, And(
  225. str,
  226. Use(str.upper),
  227. validateLogLevel,
  228. error="Log level not recognized")
  229. ),
  230. Optional('--quiet', default=False): bool,
  231. Optional('--debug'): bool,
  232. Optional('--url-only', default=False): bool,
  233. Optional('--batch', default=False): bool,
  234. Optional('--withNFO', default=False): bool,
  235. Optional('--withThumbnail', default=False): bool,
  236. Optional('--withName', default=False): bool,
  237. Optional('--withDescription', default=False): bool,
  238. Optional('--withTags', default=False): bool,
  239. Optional('--withPlaylist', default=False): bool,
  240. Optional('--withPublishAt', default=False): bool,
  241. Optional('--withPlatform', default=False): bool,
  242. Optional('--withCategory', default=False): bool,
  243. Optional('--withLanguage', default=False): bool,
  244. Optional('--withChannel', default=False): bool,
  245. # This allow to return all other options for further use: https://github.com/keleshev/schema#extra-keys
  246. object: object
  247. })
  248. schema = Schema({
  249. '--file': And(str, os.path.exists, validateVideo, error='file is not supported, please use mp4'),
  250. # Strict option checks - at the moment Schema needs to check Hook and Optional separately #
  251. Hook('--name', handler=_optionnalOrStrict): object,
  252. Hook('--description', handler=_optionnalOrStrict): object,
  253. Hook('--tags', handler=_optionnalOrStrict): object,
  254. Hook('--category', handler=_optionnalOrStrict): object,
  255. Hook('--language', handler=_optionnalOrStrict): object,
  256. Hook('--platform', handler=_optionnalOrStrict): object,
  257. Hook('--publishAt', handler=_optionnalOrStrict): object,
  258. Hook('--thumbnail', handler=_optionnalOrStrict): object,
  259. Hook('--channel', handler=_optionnalOrStrict): object,
  260. Hook('--playlist', handler=_optionnalOrStrict): object,
  261. # Validate checks #
  262. Optional('--name'): Or(None, And(
  263. str,
  264. lambda x: not x.isdigit(),
  265. error="The video name should be a string")
  266. ),
  267. Optional('--description'): Or(None, And(
  268. str,
  269. lambda x: not x.isdigit(),
  270. error="The video description should be a string")
  271. ),
  272. Optional('--tags'): Or(None, And(
  273. str,
  274. lambda x: not x.isdigit(),
  275. error="Tags should be a string")
  276. ),
  277. Optional('--category'): Or(None, And(
  278. str,
  279. validateCategory,
  280. error="Category not recognized, please see --help")
  281. ),
  282. Optional('--language'): Or(None, And(
  283. str,
  284. validateLanguage,
  285. error="Language not recognized, please see --help")
  286. ),
  287. Optional('--privacy'): Or(None, And(
  288. str,
  289. validatePrivacy,
  290. error="Please use recognized privacy between public, unlisted or private")
  291. ),
  292. Optional('--nfo'): Or(None, str),
  293. Optional('--platform'): Or(None, And(str, validatePlatform, error="Sorry, upload platform not supported")),
  294. Optional('--publishAt'): Or(None, And(
  295. str,
  296. validatePublish,
  297. error="DATE should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  298. ),
  299. Optional('--peertubeAt'): Or(None, And(
  300. str,
  301. validatePublish,
  302. error="DATE should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  303. ),
  304. Optional('--youtubeAt'): Or(None, And(
  305. str,
  306. validatePublish,
  307. error="DATE should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  308. ),
  309. Optional('--cca'): bool,
  310. Optional('--disable-comments'): bool,
  311. Optional('--nsfw'): bool,
  312. Optional('--thumbnail'): Or(None, And(
  313. str, validateThumbnail, error='thumbnail is not supported, please use jpg/jpeg'),
  314. ),
  315. Optional('--channel'): Or(None, str),
  316. Optional('--channelCreate'): bool,
  317. Optional('--playlist'): Or(None, str),
  318. Optional('--playlistCreate'): bool,
  319. '--help': bool,
  320. '--version': bool,
  321. # This allow to return all other options for further use: https://github.com/keleshev/schema#extra-keys
  322. object: object
  323. })
  324. # We need to validate early options first as withNFO and logs options should be prioritized
  325. try:
  326. options = earlyoptionSchema.validate(options)
  327. configureLogs(options)
  328. except SchemaError as e:
  329. logger.critical(e)
  330. exit(1)
  331. if options.get('--url-only') or options.get('--batch'):
  332. configureStdoutLogs()
  333. options = utils.parseNFO(options)
  334. # Once NFO are loaded, we need to revalidate strict options in case some were in NFO
  335. try:
  336. options = earlyoptionSchema.validate(options)
  337. except SchemaError as e:
  338. logger.critical(e)
  339. exit(1)
  340. if not options.get('--thumbnail'):
  341. options = utils.searchThumbnail(options)
  342. try:
  343. options = schema.validate(options)
  344. except SchemaError as e:
  345. logger.critical(e)
  346. exit(1)
  347. logger.debug("Python " + sys.version)
  348. logger.debug(options)
  349. if options.get('--platform') is None or "peertube" in options.get('--platform'):
  350. pt_upload.run(options)
  351. if options.get('--platform') is None or "youtube" in options.get('--platform'):
  352. yt_upload.run(options)
  353. if __name__ == '__main__':
  354. logger.warning("DEPRECATION: use 'python -m prismedia', not 'python -m prismedia.upload'")
  355. main()