main.py 6.6 KB

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