video_privacy_enhancer.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. """
  2. Video Privacy Enhancer
  3. --------------------------
  4. Authored by Jacob Levernier, 2014
  5. Released under the GNU AGPLv3
  6. For more information on this plugin, please see the attached Readme.md file.
  7. """
  8. """
  9. LIBRARIES FOR PYTHON TO USE
  10. """
  11. from pelican import signals # For making this plugin work with Pelican.
  12. import os.path # For checking whether files are present in the filesystem.
  13. import re # For using regular expressions.
  14. import logging
  15. logger = logging.getLogger(__name__) # For using logger.debug() to log errors or other notes.
  16. import six
  17. # import urllib.request
  18. import six.moves.urllib.request
  19. from . import video_service_thumbnail_url_generating_functions as video_thumbnail_functions # These are functions defined in 'video_service_thumbnail_url_generating_functions.py', which is located in the same directory as this file.
  20. """
  21. END OF LIBRARIES
  22. """
  23. """
  24. SETTINGS
  25. """
  26. # Do not use a leading or trailing slash below (e.g., use "images/video-thumbnails"):
  27. output_directory_for_thumbnails = "images/video-thumbnails"
  28. # See the note in the Readme file re: adding support for other video services to this list.
  29. supported_video_services = {
  30. "youtube": {
  31. "shortcode_not_including_exclamation_point": "youtube",
  32. "function_for_generating_thumbnail_url": video_thumbnail_functions.generate_thumbnail_download_link_youtube,
  33. },
  34. "vimeo": {
  35. "shortcode_not_including_exclamation_point": "vimeo",
  36. "function_for_generating_thumbnail_url": video_thumbnail_functions.generate_thumbnail_download_link_vimeo,
  37. },
  38. }
  39. """
  40. In order for this plugin to work optimally, you need to do just a few things:
  41. 1. Enable the plugn in pelicanconf.py (see http://docs.getpelican.com/en/3.3.0/plugins.html for documentation):
  42. PLUGIN_PATH = "/pelican-plugins"
  43. PLUGINS = ["video_privacy_enhancer"]
  44. 2a. If necessary, install jQuery on your site (See https://stackoverflow.com/questions/1458349/installing-jquery -- the jQuery base file should go into your Pelican theme's 'static' directory)
  45. 2b. Copy the jQuery file in this folder into, for example, your_theme_folder/static/video_privacy_enhancer_jQuery.js, and add a line like this to the <head></head> element of your website's base.html (or equivalent) template:
  46. `<script src="{{ SITEURL }}/theme/video_privacy_enhancer_jquery.js"></script> <!--Load jQuery functions for the Video Privacy Enhancer Pelican plugin -->`
  47. 3. Choose a default video embed size and add corresponding CSS to your theme's CSS file:
  48. Youtube allows the following sizes in its embed GUI (as of this writing, in March 2014). I recommend choosing one, and then having the iframe for the actual video embed match it (so that it's a seamless transition). This can be handled with CSS in both cases, so I haven't hard-coded it here:
  49. 1280 W x 720 H
  50. 853 W x 480 H
  51. 640 W x 360 H
  52. 560 W x 315 H
  53. Here's an example to add to your CSS file:
  54. ```
  55. /* For use with the video-privacy-enhancer Pelican plugin */
  56. img.video-embed-dummy-image,
  57. iframe.embedded_privacy_video {
  58. width: 853px;
  59. max-height: 480px;
  60. /* Center the element on the screen */
  61. display: block;
  62. margin-top: 2em;
  63. margin-bottom: 2em;
  64. margin-left: auto;
  65. margin-right: auto;
  66. }
  67. iframe.embedded_privacy_video {
  68. width: 843px;
  69. height: 480px;
  70. }
  71. ```
  72. """
  73. """
  74. END SETTINGS
  75. """
  76. # A function to check whtether output_directory_for_thumbnails (a variable set above in the SETTINGS section) exists. If it doesn't exist, we'll create it.
  77. def check_for_thumbnail_directory(pelican_output_path):
  78. # Per http://stackoverflow.com/a/84173, check if a file exists. isfile() works on files, and exists() works on files and directories.
  79. try:
  80. if not os.path.exists(pelican_output_path + "/" + output_directory_for_thumbnails): # If the directory doesn't exist already...
  81. os.makedirs(pelican_output_path + "/" + output_directory_for_thumbnails) # Create the directory to hold the video thumbnails.
  82. return True
  83. except Exception as e:
  84. logger.error("Video Privacy Enhancer Plugin: Error in checking if thumbnail folder exists and making the directory if it doesn't: %s", e) # In case something goes wrong.
  85. return False
  86. def download_thumbnail(video_id_from_shortcode, video_thumbnail_url, video_service_name, pelican_output_path):
  87. # Check if the thumbnail directory exists already:
  88. check_for_thumbnail_directory(pelican_output_path)
  89. # Check if the thumbnail for this video exists already (if it's been previously downloaded). If it doesn't, download it:
  90. if not os.path.exists(pelican_output_path + "/" + output_directory_for_thumbnails + "/" + video_service_name + "_" + video_id_from_shortcode + ".jpg"): # If the thumbnail doesn't already exist...
  91. logger.debug("Video Privacy Enhancer Plugin: Downloading thumbnail from the following url: " + video_thumbnail_url)
  92. six.moves.urllib.request.urlretrieve(video_thumbnail_url, pelican_output_path + "/" + output_directory_for_thumbnails + "/" + video_service_name + "_" + video_id_from_shortcode + ".jpg") # Download the thumbnail. This follows the instructions at http://www.reelseo.com/youtube-thumbnail-image/ for downloading YouTube thumbnail images.
  93. # A function to read through each page and post as it comes through from Pelican, find all instances of a shortcode (e.g., `!youtube(...)`) and change it into an HTML <img> element with the video thumbnail.
  94. # 'dictionary_of_services' below should be the dictionary defined in the settings above, which includes the service's name as the dictionary key, and, for each service, has a dictionary containing 'shortcode_to_search_for_not_including_exclamation_point' and 'function_for_generating_thumbnail_url'
  95. def process_shortcodes(data_passed_from_pelican):
  96. dictionary_of_services = supported_video_services # This should be defined in the settings section above.
  97. if not data_passed_from_pelican._content: # If the item passed from Pelican has a "content" attribute (i.e., if it's not an image file or something else like that). NOTE: data_passed_from_pelican.content (without an underscore in front of 'content') seems to be read-only, whereas data_passed_from_pelican._content is able to be overwritten. This is somewhat explained in an IRC log from 2013-02-03 from user alexis to user webdesignhero_ at https://botbot.me/freenode/pelican/2013-02-01/?tz=America/Los_Angeles.
  98. return # Exit the function, essentially passing over the (non-text) file.
  99. # Loop through services (e.g., youtube, vimeo), processing the output for each:
  100. for video_service_name, video_service_information in six.iteritems(dictionary_of_services):
  101. # Good for debugging:
  102. logger.debug("Video Privacy Enhancer Plugin: The name of the current service being processed is '" + video_service_name + "'")
  103. shortcode_to_search_for_not_including_exclamation_point = video_service_information['shortcode_not_including_exclamation_point']
  104. logger.debug("Video Privacy Enhancer Plugin: Currently looking for the shortcode '" + shortcode_to_search_for_not_including_exclamation_point + "'")
  105. function_for_generating_thumbnail_url = video_service_information['function_for_generating_thumbnail_url']
  106. all_instances_of_the_shortcode = re.findall('(?<!\\\)\!' + shortcode_to_search_for_not_including_exclamation_point + '.*?\)', data_passed_from_pelican._content) # Use a regular expression to find every instance of, e.g., '!youtube' followed by anything up to the first matching ')'.
  107. if(len(all_instances_of_the_shortcode) > 0): # If the article/page HAS any shortcodes, go on. Otherwise, don't (to do so would inadvertantly wipe out the output content for that article/page).
  108. replace_shortcode_in_text = "" # This just gives this an initial value before going into the loop below.
  109. # Go through each shortcode instance that we found above, and parse it:
  110. for shortcode_to_parse in all_instances_of_the_shortcode:
  111. video_id_from_shortcode = re.findall('(?<=' + shortcode_to_search_for_not_including_exclamation_point + '\().*?(?=\))', shortcode_to_parse)[0] # Get what's inside of the parentheses in, e.g., '!youtube(...).'
  112. # print "Video ID is " + video_id_from_shortcode # Good for debugging purposes.
  113. # Use the Pelican pelicanconf.py settings:
  114. pelican_output_path = data_passed_from_pelican.settings['OUTPUT_PATH']
  115. pelican_site_url = data_passed_from_pelican.settings['SITEURL']
  116. # Download the video thumbnail if it's not already on the filesystem:
  117. video_thumbnail_url = function_for_generating_thumbnail_url(video_id_from_shortcode)
  118. download_thumbnail(video_id_from_shortcode, video_thumbnail_url, video_service_name, pelican_output_path)
  119. # Replace the shortcode (e.g., '!youtube(...)') with '<img>...</img>'. Note that the <img> is given a class that the jQuery file mentioned at the top of this file will watch over. Any time an image with that class is clicked, the jQuery function will trigger and turn it into the full video embed.
  120. replace_shortcode_in_text = re.sub(r'\!' + shortcode_to_search_for_not_including_exclamation_point + '\(' + video_id_from_shortcode + '\)', r'<img class="video-embed-dummy-image" id="' + video_id_from_shortcode + '" src="' + pelican_site_url + '/' + output_directory_for_thumbnails + '/' + video_service_name + '_' + video_id_from_shortcode + '.jpg" alt="Embedded Video - Click to view" title="Embedded Video - Click to view" embed-service="' + video_service_name + '"></img>', data_passed_from_pelican._content)
  121. # Replace the content of the page or post with our now-updated content (having gone through all instances of the shortcode and updated them all, exiting the loop above.
  122. data_passed_from_pelican._content = replace_shortcode_in_text
  123. # Make Pelican work (see http://docs.getpelican.com/en/3.3.0/plugins.html#how-to-create-plugins):
  124. def register():
  125. signals.content_object_init.connect(process_shortcodes)