main.py 8.9 KB

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