Commits

Takeshi Komiya committed 9bf8c85

Add nicovideo extension

Comments (0)

Files changed (10)

 nwdiag:
    Takeshi KOMIYA <i.tkomiya@gmail.com>
 
+googlechart:
+   Takeshi KOMIYA <i.tkomiya@gmail.com>
+
+nicovideo:
+   Takeshi KOMIYA <i.tkomiya@gmail.com>
+
 requirements:
    Andrey Mikhaylenko <neithere@gmail.com>
 
-googlechart:
-   Takeshi KOMIYA <i.tkomiya@gmail.com>
-
 hyphenator:
    Björn Müller <diehose@freenet.de> 
 
 - issuetracker: link to different issue trackers
 - lilypond: an extension inserting music scripts from Lilypond_ in PNG format.
 - mscgen: embed mscgen-formatted MSC (Message Sequence Chart)s.
+- nicoviceo: embed videos from nicovideo
 - nwdiag: embed network diagrams by using nwdiag_
 - omegat: support tools to collaborate with OmegaT_ (Sphinx 1.1 needed)
 - osaka: convert standard Japanese doc to Osaka dialect (it is joke extension)

nicovideo/LICENSE

+If not otherwise noted, the extensions in this package are licensed
+under the following license.
+
+Copyright (c) 2009 by the contributors (see AUTHORS file).
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+* Redistributions of source code must retain the above copyright
+  notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+  notice, this list of conditions and the following disclaimer in the
+  documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

nicovideo/MANIFEST.in

+include README
+include LICENSE
+include CHANGES.*
+nicovideo extension README
+==========================
+This is a sphinx extension which embed videos from nicovideo_ .
+
+.. _nicovideo:: http://www.nicovideo.jp/
+
+Setting
+=======
+
+You can get archive file at http://bitbucket.org/birkenfeld/sphinx-contrib/
+
+Install
+-------
+
+.. code-block:: bash
+
+   > easy_install sphinxcontrib-nicovideo
+
+
+Configure Sphinx
+----------------
+To enable this extension, add ``sphinxcontrib.nicovideo`` module to extensions 
+option at :file:`conf.py`. 
+
+.. code-block:: python
+
+   import os, sys
+
+   # Path to the folder where nicovideo.py is
+   # NOTE: not needed if the package is installed in traditional way
+   # using setup.py or easy_install
+   sys.path.append(os.path.abspath('/path/to/sphinxcontrib.nicovideo'))
+
+   # Enabled extensions
+   extensions = ['sphinxcontrib.nicovideo']
+
+
+Directives and Roles
+=====================
+
+.. rst:role: nicovideo
+
+   nicovideo role makes a link to movie page::
+
+      :nicovideo:`sm9`
+
+.. rst:directive:: .. nicovideo:: [video_id]
+
+   nicovideo directive embeds a movie into the generated document.
+
+
+Repository
+==========
+This code is hosted by Bitbucket.
+
+  http://bitbucket.org/birkenfeld/sphinx-contrib/

nicovideo/setup.cfg

+[egg_info]
+tag_build = dev
+tag_date = true
+
+[aliases]
+release = egg_info -RDb ''

nicovideo/setup.py

+# -*- coding: utf-8 -*-
+
+from setuptools import setup, find_packages
+
+long_desc = '''
+This package contains the nicovideo Sphinx extension.
+
+.. add description here ..
+'''
+
+requires = ['Sphinx>=0.6']
+
+setup(
+    name='sphinxcontrib-nicovideo',
+    version='0.1.0',
+    url='http://bitbucket.org/birkenfeld/sphinx-contrib',
+    download_url='http://pypi.python.org/pypi/sphinxcontrib-nicovideo',
+    license='BSD',
+    author='Takeshi KOMIYA',
+    author_email='i.tkomiya@gmail.com',
+    description='Sphinx "nicovideo" extension',
+    long_description=long_desc,
+    zip_safe=False,
+    classifiers=[
+        'Development Status :: 4 - Beta',
+        'Environment :: Console',
+        'Environment :: Web Environment',
+        'Intended Audience :: Developers',
+        'License :: OSI Approved :: BSD License',
+        'Operating System :: OS Independent',
+        'Programming Language :: Python',
+        'Topic :: Documentation',
+        'Topic :: Utilities',
+    ],
+    platforms='any',
+    packages=find_packages(),
+    include_package_data=True,
+    install_requires=requires,
+    namespace_packages=['sphinxcontrib'],
+)

nicovideo/sphinxcontrib/__init__.py

+# -*- coding: utf-8 -*-
+"""
+    sphinxcontrib
+    ~~~~~~~~~~~~~
+
+    This package is a namespace package that contains all extensions
+    distributed in the ``sphinx-contrib`` distribution.
+
+    :copyright: Copyright 2007-2009 by the Sphinx team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+__import__('pkg_resources').declare_namespace(__name__)
+

nicovideo/sphinxcontrib/nicovideo.py

+# -*- coding: utf-8 -*-
+"""
+    sphinxcontrib.nicovideo
+    ~~~~~~~~~~~~~~~~~~~~~~~~
+
+    :copyright: Copyright 2011 by Takeshi KOMIYA
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+import urllib2
+from xml.dom import minidom
+
+from docutils import nodes, utils
+from docutils.parsers.rst import directives
+
+from sphinx.util.nodes import split_explicit_title
+from sphinx.util.compat import Directive
+
+
+class NicoVideo(object):
+    """ Utility class for access movie info in nicovideo """
+
+    def __init__(self, movie_id):
+        movie_id = NicoVideo.regulate_movie_id(movie_id)
+        url = 'http://www.nicovideo.jp/api/getthumbinfo/' + movie_id
+        resp = urllib2.urlopen(url).read()
+        self.__info = minidom.parseString(resp)
+
+    @staticmethod
+    def regulate_movie_id(movie_id):
+        if re.search('^sm\d+$', movie_id):
+            return movie_id
+        elif re.search('^\d+$', movie_id):
+            return 'sm' + movie_id
+        else:
+            return movie_id
+
+    @property
+    def url(self):
+        return 'http://www.nicovideo.jp/watch/' + self.video_id
+
+    @property
+    def thumb_url(self):
+        return 'http://ext.nicovideo.jp/thumb/' + self.video_id
+
+    @property
+    def thumbjs_url(self):
+        return 'http://ext.nicovideo.jp/thumb_watch/' + self.video_id
+
+    def __getattr__(self, name):
+        try:
+            tags = self.__info.getElementsByTagName(name)
+            return tags[0].childNodes[0].nodeValue
+        except:
+            return None
+
+
+class nicovideo(nodes.General, nodes.Element):
+    pass
+
+
+class NicoVideoDirective(Directive):
+    """Directive for embedding nico-videos"""
+
+    has_content = False
+    required_arguments = 1
+    optional_arguments = 1
+    final_argument_whitespace = True
+    option_spec = {
+        'thumb': directives.flag,
+    }
+
+    def run(self):
+        node = nicovideo(movie_id=self.arguments[0], thumb=('thumb' in self.options)) 
+        return [node]
+
+
+def visit_nicovideo_node(self, node):
+    movie = NicoVideo(node['movie_id'])
+
+    try:
+        if node['thumb']:
+            # embed movie as thumbnail
+            attrs = dict(width=312, height=176, src=movie.thumb_url,
+                         scrolling='no', style='border:solid 1px #CCC;',
+                         frameborder='0')
+            self.body.append(self.starttag(node, 'iframe', **attrs))
+            self.body.append(self.starttag(node, 'noscript'))
+            self.body.append(self.starttag(node, 'a', href=movie.url))
+            self.body.append(movie.title)
+            self.body.append('</a></noscript></iframe>')
+        else:
+            # embed movie using player
+            attrs = dict(type='text/javascript', src=movie.thumbjs_url)
+            self.body.append(self.starttag(node, 'script', **attrs))
+            self.body.append('</script>')
+            self.body.append(self.starttag(node, 'noscript'))
+            self.body.append(self.starttag(node, 'a', href=movie.url))
+            self.body.append(movie.title)
+            self.body.append('</a></noscript>')
+    except:
+        self.builder.warn('fail to load nicovideo: %r' % node['movie_id'])
+        raise nodes.SkipNode
+
+
+def depart_nicovideo_node(self, node):
+    pass
+
+
+def nicovideo_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
+    """Role for linking to nicovideo pages."""
+    text = utils.unescape(text)
+    has_explicit, title, movie_id = split_explicit_title(text)
+
+    try:
+        movie = NicoVideo(movie_id)
+        if has_explicit == False:
+            title = movie.title
+
+        ref = nodes.reference(rawtext, title, refuri=movie.url)
+        return [ref], []
+    except:
+        msg = inliner.reporter.error('fail to load nicovideo: %s' % movie_id,
+                                     line=lineno)
+        prb = inliner.problematic(rawtext, rawtext, msg)
+        return [prb], [msg]
+
+
+def setup(app):
+    app.add_role('nicovideo', nicovideo_role)
+    app.add_node(nicovideo, html=(visit_nicovideo_node, depart_nicovideo_node))
+    app.add_directive('nicovideo', NicoVideoDirective)

nicovideo/tox.ini

+## configuration for tox <http://codespeak.net/tox/>
+
+## tox automates running certain tasks within virtualenvs.  The following
+## tox configuration outlines a basic setup for running unit tests and
+## building sphinx docs in separate virtual environments.  Give it a try!
+
+[tox]
+envlist=python,doc
+
+# test running
+[testenv:python]
+deps=
+    ## if you use nose for test running
+    # nose
+    ## if you use py.test for test running
+    # pytest
+commands=
+    ## run tests with py.test
+    # py.test []
+    ## run tests with nose
+    # nose
+
+[testenv:doc]
+deps=
+    sphinx
+    # add all Sphinx extensions and other dependencies required to build your docs
+commands=
+    ## test links
+    # sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees doc {envtmpdir}/linkcheck
+    ## test html output
+    # sphinx-build -W -b html -d {envtmpdir}/doctrees doc {envtmpdir}/html
+