main.py 8.4 KB

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