main.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. #!/usr/bin/python2
  2. #
  3. # Upload videos to Youtube from the command-line using APIv3.
  4. #
  5. # Author: Arnau Sanchez <pyarnau@gmail.com>
  6. # Project: https://github.com/tokland/youtube-upload
  7. """
  8. Upload a video to Youtube from the command-line.
  9. $ youtube-upload --title="A.S. Mutter playing" \
  10. --description="Anne Sophie Mutter plays Beethoven" \
  11. --category=Music \
  12. --tags="mutter, beethoven" \
  13. anne_sophie_mutter.flv
  14. pxzZ-fYjeYs
  15. """
  16. import os
  17. import sys
  18. import optparse
  19. import collections
  20. import youtube_upload.auth
  21. import youtube_upload.upload_video
  22. import youtube_upload.categories
  23. import youtube_upload.lib as lib
  24. # http://code.google.com/p/python-progressbar (>= 2.3)
  25. try:
  26. import progressbar
  27. except ImportError:
  28. progressbar = None
  29. class InvalidCategory(Exception): pass
  30. class OptionsMissing(Exception): pass
  31. EXIT_CODES = {
  32. OptionsMissing: 2,
  33. InvalidCategory: 3,
  34. }
  35. WATCH_VIDEO_URL = "https://www.youtube.com/watch?v={id}"
  36. debug = lib.debug
  37. def get_progress_info():
  38. """Return a function callback to update the progressbar."""
  39. build = collections.namedtuple("ProgressInfo", ["callback", "finish"])
  40. if progressbar:
  41. widgets = [
  42. progressbar.Percentage(), ' ',
  43. progressbar.Bar(), ' ',
  44. progressbar.ETA(), ' ',
  45. progressbar.FileTransferSpeed(),
  46. ]
  47. bar = progressbar.ProgressBar(widgets=widgets)
  48. def _callback(total_size, completed):
  49. if not hasattr(bar, "next_update"):
  50. bar.maxval = total_size
  51. bar.start()
  52. bar.update(completed)
  53. return build(callback=_callback, finish=bar.finish)
  54. else:
  55. return build(callback=None, finish=lambda: True)
  56. def get_category_id(category):
  57. """Return category ID from its name."""
  58. if category:
  59. if category in youtube_upload.categories.IDS:
  60. return str(youtube_upload.categories.IDS[category])
  61. else:
  62. msg = "{0} is not a valid category".format(category)
  63. raise InvalidCategory(msg)
  64. def upload_video(youtube, options, video_path, total_videos, index):
  65. """Upload video with index (for split videos)."""
  66. title = lib.to_utf8(options.title)
  67. description = lib.to_utf8(options.description or "").decode("string-escape")
  68. ns = dict(title=title, n=index+1, total=total_videos)
  69. complete_title = \
  70. (options.title_template.format(**ns) if total_videos > 1 else title)
  71. progress = get_progress_info()
  72. category_id = get_category_id(options.category)
  73. request_body = {
  74. "snippet": {
  75. "title": complete_title,
  76. "tags": map(str.strip, (options.tags or "").split(",")),
  77. "description": description,
  78. "categoryId": category_id,
  79. },
  80. "status": {
  81. "privacyStatus": options.privacy
  82. },
  83. "recordingDetails": {
  84. "location": lib.string_to_dict(options.location),
  85. },
  86. }
  87. debug("Start upload: {0} ({1})".format(video_path, complete_title))
  88. video_id = youtube_upload.upload_video.upload(youtube, video_path, request_body,
  89. progress_callback=progress.callback, chunksize=16*1024)
  90. progress.finish()
  91. return video_id
  92. def run_main(parser, options, args, output=sys.stdout):
  93. """Run the main scripts from the parsed options/args."""
  94. required_options = ["title"]
  95. missing = [opt for opt in required_options if not getattr(options, opt)]
  96. if missing:
  97. parser.print_usage()
  98. msg = "Some required option are missing: %s" % ", ".join(missing)
  99. raise OptionsMissing(msg)
  100. default_client_secrets = \
  101. os.path.join(sys.prefix, "share/youtube_upload/client_secrets.json")
  102. home = os.path.expanduser("~")
  103. default_credentials = os.path.join(home, ".youtube-upload-credentials.json")
  104. client_secrets = options.client_secrets or default_client_secrets
  105. credentials = options.credentials_file or default_credentials
  106. debug("Using client secrets: {0}".format(client_secrets))
  107. debug("Using credentials file: {0}".format(credentials))
  108. youtube = youtube_upload.auth.get_resource(client_secrets, credentials)
  109. for index, video_path in enumerate(args):
  110. video_id = upload_video(youtube, options, video_path, len(args), index)
  111. video_url = WATCH_VIDEO_URL.format(id=video_id)
  112. debug("Video URL: {0}".format(video_url))
  113. output.write(video_id + "\n")
  114. def main(arguments):
  115. """Upload videos to Youtube."""
  116. usage = """Usage: %prog [OPTIONS] VIDEO [VIDEO2 ...]
  117. Upload videos to Youtube."""
  118. parser = optparse.OptionParser(usage)
  119. # Video metadata
  120. parser.add_option('-t', '--title', dest='title', type="string",
  121. help='Video(s) title')
  122. parser.add_option('-c', '--category', dest='category', type="string",
  123. help='Video(s) category')
  124. parser.add_option('-d', '--description', dest='description', type="string",
  125. help='Video(s) description')
  126. parser.add_option('', '--tags', dest='tags', type="string",
  127. help='Video(s) tags (separated by commas: tag1,tag2,...)')
  128. parser.add_option('', '--privacy', dest='privacy', metavar="STRING",
  129. default="public", help='Privacy status (public | unlisted | private)')
  130. parser.add_option('', '--location', dest='location', type="string",
  131. default=None, metavar="latitude=VAL,longitude=VAL[,altitude=VAL]",
  132. help='Video(s) location"')
  133. parser.add_option('', '--title-template', dest='title_template',
  134. type="string", default="{title} [{n}/{total}]", metavar="STRING",
  135. help='Template for multiple videos (default: {title} [{n}/{total}])')
  136. # Authentication
  137. parser.add_option('', '--client-secrets', dest='client_secrets',
  138. type="string", help='Client secrets JSON file')
  139. parser.add_option('', '--credentials-file', dest='credentials_file',
  140. type="string", help='Client secrets JSON file')
  141. options, args = parser.parse_args(arguments)
  142. run_main(parser, options, args)
  143. if __name__ == '__main__':
  144. sys.exit(lib.catch_exceptions(EXIT_CODES, main, sys.argv[1:]))