main.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. #!/usr/bin/python2
  2. #
  3. # Youtube-upload is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation, either version 3 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # Youtube-upload is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Youtube-upload. If not, see <http://www.gnu.org/licenses/>.
  15. #
  16. # Author: Arnau Sanchez <tokland@gmail.com>
  17. # Websites: http://code.google.com/p/youtube-upload
  18. # http://code.google.com/p/tokland
  19. """
  20. Upload a video to Youtube from the command-line.
  21. $ youtube-upload --title="A.S. Mutter playing" \
  22. --description="Anne Sophie Mutter plays Beethoven" \
  23. --category=Music \
  24. --keywords="mutter, beethoven" \
  25. anne_sophie_mutter.flv
  26. www.youtube.com/watch?v=pxzZ-fYjeYs
  27. """
  28. import os
  29. import sys
  30. import string
  31. import locale
  32. import optparse
  33. import collections
  34. import youtube_upload.auth
  35. import youtube_upload.upload_video
  36. import youtube_upload.categories
  37. # http://code.google.com/p/python-progressbar (>= 2.3)
  38. try:
  39. import progressbar
  40. except ImportError:
  41. progressbar = None
  42. class InvalidCategory(Exception): pass
  43. class VideoArgumentMissing(Exception): pass
  44. class OptionsMissing(Exception): pass
  45. class BadAuthentication(Exception): pass
  46. class ParseError(Exception): pass
  47. class VideoNotFound(Exception): pass
  48. class UnsuccessfulHTTPResponseCode(Exception): pass
  49. VERSION = "0.8.0"
  50. EXIT_CODES = {
  51. # Non-retryable
  52. BadAuthentication: 1,
  53. VideoArgumentMissing: 2,
  54. OptionsMissing: 2,
  55. InvalidCategory: 3,
  56. ParseError: 5,
  57. VideoNotFound: 6,
  58. # Retryable
  59. UnsuccessfulHTTPResponseCode: 100,
  60. }
  61. WATCH_VIDEO_URL = "https://www.youtube.com/watch?v={id}"
  62. ProgressInfo = collections.namedtuple("ProgressInfo", ["callback", "finish"])
  63. def to_utf8(s):
  64. """Re-encode string from the default system encoding to UTF-8."""
  65. current = locale.getpreferredencoding()
  66. return s.decode(current).encode("UTF-8") if s and current != "UTF-8" else s
  67. def debug(obj, fd=sys.stderr):
  68. """Write obj to standard error."""
  69. string = str(obj.encode(get_encoding(fd), "backslashreplace")
  70. if isinstance(obj, unicode) else obj)
  71. fd.write(string + "\n")
  72. def catch_exceptions(exit_codes, fun, *args, **kwargs):
  73. """
  74. Catch exceptions on 'fun(*args, **kwargs)' and return the exit code specified
  75. in the 'exit_codes' dictionary. Returns 0 if no exception is raised.
  76. """
  77. try:
  78. fun(*args, **kwargs)
  79. return 0
  80. except tuple(exit_codes.keys()) as exc:
  81. debug("[%s] %s" % (exc.__class__.__name__, exc))
  82. return exit_codes[exc.__class__]
  83. def get_encoding(fd):
  84. """Guess terminal encoding."""
  85. return fd.encoding or locale.getpreferredencoding()
  86. def compact(it):
  87. """Filter false (in the truth sense) elements in iterator."""
  88. return filter(bool, it)
  89. def tosize(seq, size):
  90. """Return a list of fixed length from sequence (which may be shorter or longer)."""
  91. return (seq[:size] if len(seq) >= size else (seq + [None] * (size-len(seq))))
  92. def first(it):
  93. """Return first element in iterable."""
  94. return it.next()
  95. def get_progress_info():
  96. """Return a function callback to update the progressbar."""
  97. def _callback(total_size, completed):
  98. if not hasattr(bar, "next_update"):
  99. bar.maxval = total_size
  100. bar.start()
  101. bar.update(completed)
  102. widgets = [
  103. progressbar.Percentage(), ' ',
  104. progressbar.Bar(), ' ',
  105. progressbar.ETA(), ' ',
  106. progressbar.FileTransferSpeed(),
  107. ]
  108. bar = progressbar.ProgressBar(widgets=widgets)
  109. return ProgressInfo(callback=_callback, finish=bar.finish)
  110. def string_to_dict(string):
  111. """Return dictionary from string "key1=value1, key2=value2"."""
  112. pairs = [s.strip() for s in (string or "").split(",")]
  113. return dict(pair.split("=") for pair in pairs)
  114. def upload_video(youtube, options, video_path, total_videos, index):
  115. """Upload video with index (for split videos)."""
  116. title = to_utf8(options.title)
  117. description = to_utf8(options.description or "").decode("string-escape")
  118. namespace = dict(title=title, n=index+1, total=total_videos)
  119. complete_title = (string.Template(options.title_template).substitute(**namespace)
  120. if total_videos > 1 else title)
  121. progress = get_progress_info()
  122. if options.category:
  123. ids = youtube_upload.categories.IDS
  124. if options.category in ids:
  125. category_id = str(ids[options.category])
  126. else:
  127. raise InvalidCategory("{} is not a valid category".format(options.category))
  128. else:
  129. category_id = None
  130. body = {
  131. "snippet": {
  132. "title": complete_title,
  133. "tags": map(str.strip, (options.keywords or "").split(",")),
  134. "description": description,
  135. "categoryId": category_id,
  136. },
  137. "status": {
  138. "privacyStatus": options.privacy
  139. },
  140. "recordingDetails": {
  141. "location": string_to_dict(options.location),
  142. },
  143. }
  144. video_id = youtube_upload.upload_video.upload(youtube, video_path, body,
  145. progress_callback=progress.callback, chunksize=16*1024)
  146. progress.finish()
  147. return video_id
  148. def run_main(parser, options, args, output=sys.stdout):
  149. """Run the main scripts from the parsed options/args."""
  150. required_options = ["title"]
  151. missing = [opt for opt in required_options if not getattr(options, opt)]
  152. if missing:
  153. parser.print_usage()
  154. raise OptionsMissing("Some required option are missing: %s" % ", ".join(missing))
  155. default_client_secrets = \
  156. os.path.join(sys.prefix, "share", "youtube_upload", "client_secrets.json")
  157. home = os.path.expanduser("~")
  158. default_credentials = os.path.join(home, ".youtube_upload-credentials.json")
  159. client_secrets = options.client_secrets or default_client_secrets
  160. credentials = options.credentials_file or default_credentials
  161. debug("Using client secrets: {}".format(client_secrets))
  162. debug("Using credentials file: {}".format(credentials))
  163. youtube = youtube_upload.auth.get_resource(client_secrets, credentials)
  164. for index, video_path in enumerate(args):
  165. video_id = upload_video(youtube, options, video_path, len(args), index)
  166. video_url = WATCH_VIDEO_URL.format(id=video_id)
  167. debug("Watch URL: {}".format(video_url))
  168. output.write(video_id + "\n")
  169. def main(arguments):
  170. """Upload video to Youtube."""
  171. usage = """Usage: %prog [OPTIONS] VIDEO_PATH ...
  172. Upload videos to youtube."""
  173. parser = optparse.OptionParser(usage, version=VERSION)
  174. # Required options
  175. parser.add_option('-t', '--title', dest='title', type="string",
  176. help='Video(s) title')
  177. parser.add_option('-c', '--category', dest='category', type="string",
  178. help='Video(s) category')
  179. # Optional options
  180. parser.add_option('-d', '--description', dest='description', type="string",
  181. help='Video(s) description')
  182. parser.add_option('', '--keywords', dest='keywords', type="string",
  183. help='Video(s) keywords (separated by commas: tag1,tag2,...)')
  184. parser.add_option('', '--title-template', dest='title_template', type="string",
  185. default="$title [$n/$total]", metavar="STRING",
  186. help='Title template to use on multiple videos (default: $title [$n/$total])')
  187. parser.add_option('', '--privacy', dest='privacy', metavar="STRING",
  188. default="public", help='Set privacy status (public | unlisted | private)')
  189. parser.add_option('', '--location', dest='location', type="string", default=None,
  190. metavar="LAT,LON", help='Video(s) location (latitude=VALUE, longitude=VALUE, altitude=VALUE)."')
  191. # Authentication
  192. parser.add_option('', '--client-secrets', dest='client_secrets', type="string",
  193. help='Client secrets JSON file')
  194. parser.add_option('', '--credentials-file', dest='credentials_file', type="string",
  195. help='Client secrets JSON file')
  196. options, args = parser.parse_args(arguments)
  197. run_main(parser, options, args)
  198. if __name__ == '__main__':
  199. sys.exit(catch_exceptions(EXIT_CODES, main, sys.argv[1:]))