main.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 OptionsError(Exception): pass
  35. class AuthenticationError(Exception): pass
  36. class RequestError(Exception): pass
  37. EXIT_CODES = {
  38. OptionsError: 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. if options.publish_at:
  92. debug("Your video will remain private until specified date.")
  93. tags = [u(s.strip()) for s in (options.tags or "").split(",")]
  94. ns = dict(title=title, n=index+1, total=total_videos)
  95. title_template = u(options.title_template)
  96. complete_title = (title_template.format(**ns) if total_videos > 1 else title)
  97. progress = get_progress_info()
  98. category_id = get_category_id(options.category)
  99. request_body = {
  100. "snippet": {
  101. "title": complete_title,
  102. "description": description,
  103. "categoryId": category_id,
  104. "tags": tags,
  105. },
  106. "status": {
  107. "privacyStatus": ("private" if options.publish_at else options.privacy),
  108. "publishAt": options.publish_at,
  109. },
  110. "recordingDetails": {
  111. "location": lib.string_to_dict(options.location),
  112. },
  113. }
  114. debug("Start upload: {0}".format(video_path))
  115. try:
  116. video_id = upload_video.upload(youtube, video_path,
  117. request_body, progress_callback=progress.callback)
  118. except apiclient.errors.HttpError as error:
  119. raise RequestError("Server response: {0}".format(error.content.strip()))
  120. finally:
  121. progress.finish()
  122. return video_id
  123. def get_youtube_handler(options):
  124. """Return the API Youtube object."""
  125. home = os.path.expanduser("~")
  126. default_client_secrets = lib.get_first_existing_filename(
  127. [sys.prefix, os.path.join(sys.prefix, "local")],
  128. "share/youtube_upload/client_secrets.json")
  129. default_credentials = os.path.join(home, ".youtube-upload-credentials.json")
  130. client_secrets = options.client_secrets or default_client_secrets or \
  131. os.path.join(home, ".client_secrets.json")
  132. credentials = options.credentials_file or default_credentials
  133. debug("Using client secrets: {0}".format(client_secrets))
  134. debug("Using credentials file: {0}".format(credentials))
  135. get_code_callback = (auth.browser.get_code
  136. if options.auth_browser else auth.console.get_code)
  137. return auth.get_resource(client_secrets, credentials,
  138. get_code_callback=get_code_callback)
  139. def parse_options_error(parser, options):
  140. """Check errors in options."""
  141. required_options = ["title"]
  142. missing = [opt for opt in required_options if not getattr(options, opt)]
  143. if missing:
  144. parser.print_usage()
  145. msg = "Some required option are missing: {0}".format(", ".join(missing))
  146. raise OptionsError(msg)
  147. def run_main(parser, options, args, output=sys.stdout):
  148. """Run the main scripts from the parsed options/args."""
  149. parse_options_error(parser, options)
  150. youtube = get_youtube_handler(options)
  151. if youtube:
  152. for index, video_path in enumerate(args):
  153. video_id = upload_youtube_video(youtube, options, video_path, len(args), index)
  154. video_url = WATCH_VIDEO_URL.format(id=video_id)
  155. debug("Video URL: {0}".format(video_url))
  156. if options.open_link:
  157. open_link(video_url) #Opens the Youtube Video's link in a webbrowser
  158. if options.thumb:
  159. youtube.thumbnails().set(videoId=video_id, media_body=options.thumb).execute()
  160. if options.playlist:
  161. playlists.add_video_to_playlist(youtube, video_id,
  162. title=options.playlist, privacy=options.privacy)
  163. output.write(video_id + "\n")
  164. else:
  165. raise AuthenticationError("Cannot get youtube resource")
  166. def main(arguments):
  167. """Upload videos to Youtube."""
  168. usage = """Usage: %prog [OPTIONS] VIDEO [VIDEO2 ...]
  169. Upload videos to Youtube."""
  170. parser = optparse.OptionParser(usage)
  171. # Video metadata
  172. parser.add_option('-t', '--title', dest='title', type="string",
  173. help='Video title')
  174. parser.add_option('-c', '--category', dest='category', type="string",
  175. help='Video category')
  176. parser.add_option('-d', '--description', dest='description', type="string",
  177. help='Video description')
  178. parser.add_option('', '--tags', dest='tags', type="string",
  179. help='Video tags (separated by commas: "tag1, tag2,...")')
  180. parser.add_option('', '--privacy', dest='privacy', metavar="STRING",
  181. default="public", help='Privacy status (public | unlisted | private)')
  182. parser.add_option('', '--publish-at', dest='publish_at', metavar="datetime",
  183. default=None, help='Publish Date: YYYY-MM-DDThh:mm:ss.sZ')
  184. parser.add_option('', '--location', dest='location', type="string",
  185. default=None, metavar="latitude=VAL,longitude=VAL[,altitude=VAL]",
  186. help='Video location"')
  187. parser.add_option('', '--thumbnail', dest='thumb', type="string",
  188. help='Video thumbnail')
  189. parser.add_option('', '--playlist', dest='playlist', type="string",
  190. help='Playlist title (if it does not exist, it will be created)')
  191. parser.add_option('', '--title-template', dest='title_template',
  192. type="string", default="{title} [{n}/{total}]", metavar="STRING",
  193. help='Template for multiple videos (default: {title} [{n}/{total}])')
  194. # Authentication
  195. parser.add_option('', '--client-secrets', dest='client_secrets',
  196. type="string", help='Client secrets JSON file')
  197. parser.add_option('', '--credentials-file', dest='credentials_file',
  198. type="string", help='Credentials JSON file')
  199. parser.add_option('', '--auth-browser', dest='auth_browser', action='store_true',
  200. help='Open a GUI browser to authenticate if required')
  201. #Additional options
  202. parser.add_option('', '--open-link', dest='open_link', action='store_true',
  203. help='Opens a url in a web browser to display uploaded videos')
  204. options, args = parser.parse_args(arguments)
  205. run_main(parser, options, args)
  206. def run():
  207. sys.exit(lib.catch_exceptions(EXIT_CODES, main, sys.argv[1:]))
  208. if __name__ == '__main__':
  209. run()