main.py 8.0 KB

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