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.

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