main.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. def _finish():
  62. if hasattr(bar, "next_update"):
  63. return bar.finish()
  64. return progressinfo(callback=_callback, finish=_finish)
  65. else:
  66. return progressinfo(callback=None, finish=lambda: True)
  67. def get_category_id(category):
  68. """Return category ID from its name."""
  69. if category:
  70. if category in youtube_upload.categories.IDS:
  71. ncategory = youtube_upload.categories.IDS[category]
  72. debug("Using category: {0} (id={1})".format(category, ncategory))
  73. return str(youtube_upload.categories.IDS[category])
  74. else:
  75. msg = "{0} is not a valid category".format(category)
  76. raise InvalidCategory(msg)
  77. def upload_video(youtube, options, video_path, total_videos, index):
  78. """Upload video with index (for split videos)."""
  79. u = lib.to_utf8
  80. title = u(options.title)
  81. description = u(options.description or "").decode("string-escape")
  82. tags = [u(s.strip()) for s in (options.tags or "").split(",")]
  83. ns = dict(title=u(options.title), n=index+1, total=total_videos)
  84. complete_title = \
  85. (options.title_template.format(**ns) if total_videos > 1 else title)
  86. progress = get_progress_info()
  87. category_id = get_category_id(options.category)
  88. request_body = {
  89. "snippet": {
  90. "title": complete_title,
  91. "description": description,
  92. "categoryId": category_id,
  93. "tags": tags,
  94. },
  95. "status": {
  96. "privacyStatus": options.privacy,
  97. },
  98. "recordingDetails": {
  99. "location": lib.string_to_dict(options.location),
  100. },
  101. }
  102. debug("Start upload: {0}".format(video_path))
  103. try:
  104. video_id = youtube_upload.upload_video.upload(youtube, video_path,
  105. request_body, progress_callback=progress.callback)
  106. except apiclient.errors.HttpError, error:
  107. raise RequestError("Server response was: {0}".format(error.content.strip()))
  108. progress.finish()
  109. return video_id
  110. def run_main(parser, options, args, output=sys.stdout):
  111. """Run the main scripts from the parsed options/args."""
  112. required_options = ["title"]
  113. missing = [opt for opt in required_options if not getattr(options, opt)]
  114. if missing:
  115. parser.print_usage()
  116. msg = "Some required option are missing: {0}".format(", ".join(missing))
  117. raise OptionsMissing(msg)
  118. home = os.path.expanduser("~")
  119. default_client_secrets = lib.get_first_existing_filename(
  120. [sys.prefix, os.path.join(sys.prefix, "local")],
  121. "share/youtube_upload/client_secrets.json")
  122. default_credentials = os.path.join(home, ".youtube-upload-credentials.json")
  123. client_secrets = options.client_secrets or default_client_secrets or \
  124. os.path.join(home, ".client_secrets.json")
  125. credentials = options.credentials_file or default_credentials
  126. debug("Using client secrets: {0}".format(client_secrets))
  127. debug("Using credentials file: {0}".format(credentials))
  128. get_code_callback = (youtube_upload.auth.browser.get_code
  129. if options.auth_browser else youtube_upload.auth.console.get_code)
  130. youtube = youtube_upload.auth.get_resource(client_secrets, credentials,
  131. get_code_callback=get_code_callback)
  132. if youtube:
  133. for index, video_path in enumerate(args):
  134. video_id = upload_video(youtube, options, video_path, len(args), index)
  135. video_url = WATCH_VIDEO_URL.format(id=video_id)
  136. if options.thumb:
  137. youtube.thumbnails().set(videoId=video_id, media_body=options.thumb).execute()
  138. if options.playlist:
  139. # find playlist with given name
  140. existing_playlist_id = None
  141. playlists = youtube.playlists()
  142. request = playlists.list(mine=True, part='id,snippet')
  143. while request is not None:
  144. results = request.execute()
  145. for item in results['items']:
  146. if item.get('snippet', {}).get('title') == options.playlist:
  147. existing_playlist_id = item.get('id')
  148. # stop paginating playlists on first matching playlist title
  149. if existing_playlist_id is None:
  150. request = playlists.list_next(request, results)
  151. else:
  152. break
  153. # create playlist, if necessary
  154. if existing_playlist_id is None:
  155. playlists_insert_response = youtube.playlists().insert(part="snippet,status", body={
  156. "snippet": {
  157. "title": options.playlist
  158. },
  159. "status": {
  160. "privacyStatus": options.privacy
  161. }
  162. }).execute()
  163. existing_playlist_id = playlists_insert_response.get('id', None)
  164. # something has gone wrong
  165. if existing_playlist_id is None:
  166. debug('Error creating playlist')
  167. else:
  168. # add video to playlist
  169. youtube.playlistItems().insert(part='snippet', body={
  170. "snippet": {
  171. "playlistId": existing_playlist_id,
  172. "resourceId": {
  173. "kind": "youtube#video",
  174. "videoId": video_id
  175. }
  176. }
  177. }).execute()
  178. debug("Added video to playlist '{0}'".format(options.playlist))
  179. debug("Video URL: {0}".format(video_url))
  180. output.write(video_id + "\n")
  181. else:
  182. raise AuthenticationError("Cannot get youtube resource")
  183. def main(arguments):
  184. """Upload videos to Youtube."""
  185. usage = """Usage: %prog [OPTIONS] VIDEO [VIDEO2 ...]
  186. Upload videos to Youtube."""
  187. parser = optparse.OptionParser(usage)
  188. # Video metadata
  189. parser.add_option('-t', '--title', dest='title', type="string",
  190. help='Video title')
  191. parser.add_option('-c', '--category', dest='category', type="string",
  192. help='Video category')
  193. parser.add_option('-d', '--description', dest='description', type="string",
  194. help='Video description')
  195. parser.add_option('', '--tags', dest='tags', type="string",
  196. help='Video tags (separated by commas: "tag1, tag2,...")')
  197. parser.add_option('', '--privacy', dest='privacy', metavar="STRING",
  198. default="public", help='Privacy status (public | unlisted | private)')
  199. parser.add_option('', '--location', dest='location', type="string",
  200. default=None, metavar="latitude=VAL,longitude=VAL[,altitude=VAL]",
  201. help='Video location"')
  202. parser.add_option('', '--thumbnail', dest='thumb', type="string",
  203. help='Video thumbnail')
  204. parser.add_option('', '--playlist', dest='playlist', type="string",
  205. help='Playlist title (will create if necessary)')
  206. parser.add_option('', '--title-template', dest='title_template',
  207. type="string", default="{title} [{n}/{total}]", metavar="STRING",
  208. help='Template for multiple videos (default: {title} [{n}/{total}])')
  209. # Authentication
  210. parser.add_option('', '--client-secrets', dest='client_secrets',
  211. type="string", help='Client secrets JSON file')
  212. parser.add_option('', '--credentials-file', dest='credentials_file',
  213. type="string", help='Credentials JSON file')
  214. parser.add_option('', '--auth-browser', dest='auth_browser', action="store_true",
  215. help='Open a GUI browser to authenticate if required')
  216. options, args = parser.parse_args(arguments)
  217. run_main(parser, options, args)
  218. if __name__ == '__main__':
  219. sys.exit(lib.catch_exceptions(EXIT_CODES, main, sys.argv[1:]))