main.py 6.7 KB

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