main.py 7.1 KB

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