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.

350 lines
16 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 --heartbeat
  9. prismedia -h | --help
  10. prismedia --version
  11. Options:
  12. -f, --file=STRING Path to the video file to upload in mp4. This is the only mandatory option.
  13. --name=NAME Name of the video to upload. (default to video filename)
  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. --originalDate=DATE Configure the video as initially recorded at DATE
  36. DATE should be on the form YYYY-MM-DDThh:mm:ss eg: 2018-03-12T19:00:00
  37. DATE should be in the past
  38. --auto-originalDate Automatically use the file modification time as original date
  39. --thumbnail=STRING Path to a file to use as a thumbnail for the video.
  40. Supported types are jpg and jpeg.
  41. By default, prismedia search for an image based on video name followed by .jpg or .jpeg
  42. --channel=STRING Set the channel to use for the video (Peertube only)
  43. If the channel is not found, spawn an error except if --channelCreate is set.
  44. --channelCreate Create the channel if not exists. (Peertube only, default do not create)
  45. Only relevant if --channel is set.
  46. --playlist=STRING Set the playlist to use for the video.
  47. If the playlist is not found, spawn an error except if --playlistCreate is set.
  48. --playlistCreate Create the playlist if not exists. (default do not create)
  49. Only relevant if --playlist is set.
  50. --progress=STRING Set the progress bar view, one of percentage, bigFile (MB), accurate (KB).
  51. --heartbeat Use some credits to show some activity for you apikey so the platform know it is used and would not put your quota to 0 (only Youtube currently)
  52. -h --help Show this help.
  53. --version Show version.
  54. Logging options
  55. -q --quiet Suppress any log except Critical (alias for --log=critical).
  56. --log=STRING Log level, between debug, info, warning, error, critical. Ignored if --quiet is set (default to info)
  57. -u --url-only Display generated URL after upload directly on stdout, implies --quiet
  58. --batch Display generated URL after upload with platform information for easier parsing. Implies --quiet
  59. Be careful --batch and --url-only are mutually exclusives.
  60. --debug (Deprecated) Alias for --log=debug. Ignored if --log is set
  61. Strict options:
  62. Strict options allow you to force some option to be present when uploading a video. It's useful to be sure you do not
  63. forget something when uploading a video, for example if you use multiples NFO. You may force the presence of description,
  64. tags, thumbnail, ...
  65. All strict option are optionals and are provided only to avoid errors when uploading :-)
  66. All strict options can be specified in NFO directly, the only strict option mandatory on cli is --withNFO
  67. All strict options are off by default
  68. --withNFO Prevent the upload without a NFO, either specified via cli or found in the directory
  69. --withThumbnail Prevent the upload without a thumbnail
  70. --withName Prevent the upload if no name are found
  71. --withDescription Prevent the upload without description
  72. --withTags Prevent the upload without tags
  73. --withPlaylist Prevent the upload if no playlist
  74. --withPublishAt Prevent the upload if no schedule
  75. --withOriginalDate Prevent the upload if no original date configured
  76. --withPlatform Prevent the upload if at least one platform is not specified
  77. --withCategory Prevent the upload if no category
  78. --withLanguage Prevent upload if no language
  79. --withChannel Prevent upload if no channel
  80. Categories:
  81. Category is the type of video you upload. Default is films.
  82. Here are available categories from Peertube and Youtube:
  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. Languages:
  89. Language of the video (audio track), choose one. Default is English
  90. Here are available languages from Peertube and Youtube:
  91. Arabic, English, French, German, Hindi, Italian,
  92. Japanese, Korean, Mandarin, Portuguese, Punjabi, Russian, Spanish
  93. """
  94. import sys
  95. if sys.version_info[0] < 3:
  96. raise Exception("Python 3 or a more recent version is required.")
  97. import os
  98. import datetime
  99. import logging
  100. from docopt import docopt
  101. from . import yt_upload
  102. from . import pt_upload
  103. from . import utils
  104. logger = logging.getLogger('Prismedia')
  105. try:
  106. # noinspection PyUnresolvedReferences
  107. from schema import Schema, And, Or, Optional, SchemaError, Hook, Use
  108. except ImportError:
  109. logger.critical('This program requires that the `schema` data-validation library'
  110. ' is installed: \n'
  111. 'see https://github.com/halst/schema\n')
  112. exit(1)
  113. try:
  114. # noinspection PyUnresolvedReferences
  115. import magic
  116. except ImportError:
  117. logger.critical('This program requires that the `python-magic` library'
  118. ' is installed, NOT the Python bindings to libmagic API \n'
  119. 'see https://github.com/ahupp/python-magic\n')
  120. exit(1)
  121. VERSION = "prismedia v0.11.0"
  122. def _optionnalOrStrict(key, scope, error):
  123. option = key.replace('-', '')
  124. option = option[0].upper() + option[1:]
  125. if scope["--with" + option] is True and scope[key] is None:
  126. logger.critical("Prismedia: you have required the strict presence of " + key + " but none is found")
  127. exit(1)
  128. return True
  129. def configureLogs(options):
  130. if options.get('--batch') and options.get('--url-only'):
  131. logger.critical("Prismedia: Please use either --batch OR --url-only, not both.")
  132. exit(1)
  133. # batch and url-only implies quiet
  134. if options.get('--batch') or options.get('--url-only'):
  135. options['--quiet'] = True
  136. if options.get('--quiet'):
  137. # We need to set both log level in the same time
  138. logger.setLevel(50)
  139. ch.setLevel(50)
  140. elif options.get('--log'):
  141. numeric_level = getattr(logging, options["--log"], None)
  142. # We need to set both log level in the same time
  143. logger.setLevel(numeric_level)
  144. ch.setLevel(numeric_level)
  145. elif options.get('--debug'):
  146. logger.warning("DEPRECATION: --debug is deprecated, please use --log=debug instead")
  147. logger.setLevel(10)
  148. ch.setLevel(10)
  149. def configureStdoutLogs():
  150. logger_stdout = logging.getLogger('stdoutlogs')
  151. logger_stdout.setLevel(logging.INFO)
  152. ch_stdout = logging.StreamHandler(stream=sys.stdout)
  153. ch_stdout.setLevel(logging.INFO)
  154. # Default stdout logs is url only
  155. formatter_stdout = logging.Formatter('%(message)s')
  156. ch_stdout.setFormatter(formatter_stdout)
  157. logger_stdout.addHandler(ch_stdout)
  158. def main():
  159. options = docopt(__doc__, version=VERSION)
  160. earlyoptionSchema = Schema({
  161. Optional('--log'): Or(None, And(
  162. str,
  163. Use(str.upper),
  164. validateLogLevel,
  165. error="Log level not recognized")
  166. ),
  167. Optional('--quiet', default=False): bool,
  168. Optional('--debug'): bool,
  169. Optional('--url-only', default=False): bool,
  170. Optional('--batch', default=False): bool,
  171. Optional('--withNFO', default=False): bool,
  172. Optional('--withThumbnail', default=False): bool,
  173. Optional('--withName', default=False): bool,
  174. Optional('--withDescription', default=False): bool,
  175. Optional('--withTags', default=False): bool,
  176. Optional('--withPlaylist', default=False): bool,
  177. Optional('--withPublishAt', default=False): bool,
  178. Optional('--withOriginalDate', default=False): bool,
  179. Optional('--withPlatform', default=False): bool,
  180. Optional('--withCategory', default=False): bool,
  181. Optional('--withLanguage', default=False): bool,
  182. Optional('--withChannel', default=False): bool,
  183. # This allow to return all other options for further use: https://github.com/keleshev/schema#extra-keys
  184. object: object
  185. })
  186. schema = Schema({
  187. '--file': And(str, os.path.exists, validateVideo, error='file is not supported, please use mp4'),
  188. # Strict option checks - at the moment Schema needs to check Hook and Optional separately #
  189. Hook('--name', handler=_optionnalOrStrict): object,
  190. Hook('--description', handler=_optionnalOrStrict): object,
  191. Hook('--tags', handler=_optionnalOrStrict): object,
  192. Hook('--category', handler=_optionnalOrStrict): object,
  193. Hook('--language', handler=_optionnalOrStrict): object,
  194. Hook('--platform', handler=_optionnalOrStrict): object,
  195. Hook('--publishAt', handler=_optionnalOrStrict): object,
  196. Hook('--originalDate', handler=_optionnalOrStrict): object,
  197. Hook('--thumbnail', handler=_optionnalOrStrict): object,
  198. Hook('--channel', handler=_optionnalOrStrict): object,
  199. Hook('--playlist', handler=_optionnalOrStrict): object,
  200. # Validate checks #
  201. Optional('--name'): Or(None, And(
  202. str,
  203. lambda x: not x.isdigit(),
  204. error="The video name should be a string")
  205. ),
  206. Optional('--description'): Or(None, And(
  207. str,
  208. lambda x: not x.isdigit(),
  209. error="The video description should be a string")
  210. ),
  211. Optional('--tags'): Or(None, And(
  212. str,
  213. lambda x: not x.isdigit(),
  214. error="Tags should be a string")
  215. ),
  216. Optional('--category'): Or(None, And(
  217. str,
  218. validateCategory,
  219. error="Category not recognized, please see --help")
  220. ),
  221. Optional('--language'): Or(None, And(
  222. str,
  223. validateLanguage,
  224. error="Language not recognized, please see --help")
  225. ),
  226. Optional('--privacy'): Or(None, And(
  227. str,
  228. validatePrivacy,
  229. error="Please use recognized privacy between public, unlisted or private")
  230. ),
  231. Optional('--nfo'): Or(None, str),
  232. Optional('--platform'): Or(None, And(str, validatePlatform, error="Sorry, upload platform not supported")),
  233. Optional('--publishAt'): Or(None, And(
  234. str,
  235. validatePublishDate,
  236. error="Publish Date should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  237. ),
  238. Optional('--peertubeAt'): Or(None, And(
  239. str,
  240. validatePublishDate,
  241. error="Publish Date should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  242. ),
  243. Optional('--youtubeAt'): Or(None, And(
  244. str,
  245. validatePublishDate,
  246. error="Publish Date should be the form YYYY-MM-DDThh:mm:ss and has to be in the future")
  247. ),
  248. Optional('--originalDate'): Or(None, And(
  249. str,
  250. validateOriginalDate,
  251. error="Original date should be the form YYYY-MM-DDThh:mm:ss and has to be in the past")
  252. ),
  253. Optional('--auto-originalDate'): bool,
  254. Optional('--cca'): bool,
  255. Optional('--disable-comments'): bool,
  256. Optional('--nsfw'): bool,
  257. Optional('--thumbnail'): Or(None, And(
  258. str, validateThumbnail, error='thumbnail is not supported, please use jpg/jpeg'),
  259. ),
  260. Optional('--channel'): Or(None, str),
  261. Optional('--channelCreate'): bool,
  262. Optional('--playlist'): Or(None, str),
  263. Optional('--playlistCreate'): bool,
  264. Optional('--progress'): Or(None, And(str, validateProgress, error="Sorry, progress visualisation not supported")),
  265. '--heartbeat': bool,
  266. '--help': bool,
  267. '--version': bool,
  268. # This allow to return all other options for further use: https://github.com/keleshev/schema#extra-keys
  269. object: object
  270. })
  271. if options.get('--heartbeat'):
  272. yt_upload.heartbeat()
  273. exit(0)
  274. # We need to validate early options first as withNFO and logs options should be prioritized
  275. try:
  276. options = earlyoptionSchema.validate(options)
  277. configureLogs(options)
  278. except SchemaError as e:
  279. logger.critical(e)
  280. exit(1)
  281. if options.get('--url-only') or options.get('--batch'):
  282. configureStdoutLogs()
  283. options = utils.parseNFO(options)
  284. # If after loading NFO we still has no original date and --auto-originalDate is enabled,
  285. # then we need to search from the file
  286. # We need to do that before the strict validation in case --withOriginalDate is enabled
  287. if not options.get('--originalDate') and options.get('--auto-originalDate'):
  288. options['--originalDate'] = utils.searchOriginalDate(options)
  289. # Once NFO are loaded, we need to revalidate strict options in case some were in NFO
  290. try:
  291. options = earlyoptionSchema.validate(options)
  292. except SchemaError as e:
  293. logger.critical(e)
  294. exit(1)
  295. if not options.get('--thumbnail'):
  296. options = utils.searchThumbnail(options)
  297. try:
  298. options = schema.validate(options)
  299. except SchemaError as e:
  300. logger.critical(e)
  301. exit(1)
  302. logger.debug("Python " + sys.version)
  303. logger.debug(options)
  304. if options.get('--platform') is None or "peertube" in options.get('--platform'):
  305. pt_upload.run(options)
  306. if options.get('--platform') is None or "youtube" in options.get('--platform'):
  307. yt_upload.run(options)
  308. if __name__ == '__main__':
  309. logger.warning("DEPRECATION: use 'python -m prismedia', not 'python -m prismedia.upload'")
  310. main()