示例#1
0
    def handle(self, *args, **options):
        
        for pad in Pad.objects.all():
            padID = pad.group.groupID + '$' + urllib.quote_plus(pad.name.replace('::', '_'))
            epclient = EtherpadLiteClient(pad.server.apikey, pad.server.apiurl)
            
            text = epclient.getText(padID)['text']

            backup_file_path = os.path.join(BACKUP_DIR, pad.display_slug)
            
            with open(backup_file_path.encode('utf-8'), 'w') as f:
                f.write(text.encode('utf-8'))
示例#2
0
def css_slide(request):
    try:
        pad = Pad.objects.get(display_slug='slidy.css')
        padID = pad.group.groupID + '$' + urllib.quote_plus(pad.name.replace('::', '_'))
        epclient = EtherpadLiteClient(pad.server.apikey, pad.server.apiurl)
        return HttpResponse(epclient.getText(padID)['text'], mimetype="text/css")
    except:
        # If there is no pad called "css", loads a default css file
        f = open('relearn/static/css/slidy.css', 'r')
        css = f.read()
        f.close()
        return HttpResponse(css, mimetype="text/css")
示例#3
0
class Etherpad:
    def __init__(self):
        self.epclient = EtherpadLiteClient(settings.APIKEY, settings.APIURL)

    def create_ether_blog(self, blog):
        groupid = self.epclient.createGroupIfNotExistsFor(str(blog.uuid))
        padid = self.epclient.createGroupPad(groupid['groupID'], blog.pk)
        blog = EtherBlog.objects.create(blog=blog,
                                        etherid=padid['padID'],
                                        groupid=groupid['groupID'])
        return blog

    def create_ether_user(self, user):
        result = self.epclient.createAuthorIfNotExistsFor(
            user.id, user.username)
        user = EtherUser.objects.create(user=user,
                                        user_ether_id=result['authorID'])
        return user

    def create_session_group(self, request, groupid):
        ethergroup = str(groupid)
        try:
            etheruser = EtherUser.objects.get(user=request.user)
        except Exception:
            etheruser = self.create_ether_user(request.user)
        etheruser = str(etheruser.user_ether_id)
        validUntil = int(time()) + 28800
        result = self.epclient.createSession(ethergroup, etheruser, validUntil)
        return result['sessionID']

    def getHTML(self, blog):
        blog = EtherBlog.objects.get(blog=blog)
        result = self.epclient.getHtml(blog.etherid)
        return result['html']

    def getText(self, blog):
        blog = EtherBlog.objects.get(blog=blog)
        result = self.epclient.getText(blog.etherid)
        return result['text']

    def deletePad(self, blog):
        article = EtherBlog.objects.get(blog=blog)
        self.epclient.deletePad(blog.etherid)
        return

    def get_pad_usercount(self, blog):
        count = self.epclient.padUsersCount(blog.etherid)
        return count['padUsersCount']

    def get_read_only_padid(self, blog):
        readonly = self.epclient.getReadOnlyID(blog.etherid)
        return readonly['readOnlyID']
示例#4
0
def getText(article):
    epclient = EtherpadLiteClient(settings.APIKEY, settings.APIURL)
    article = EtherArticle.objects.get(article=article)
    result = epclient.getText(article.article_ether_id)
    return result['text']
示例#5
0
#!/usr/local/bin/python
pdflatex = "/usr/local/texlive/2011/bin/amd64-freebsd/pdflatex"
import cgi
import cgitb

cgitb.enable()  # for troubleshooting
import os
import tempfile
import codecs

from py_etherpad import EtherpadLiteClient

myPad = EtherpadLiteClient('yourapitoken', 'http://etherpad.install.tld/api')

#get the text of the etherpad
padText = myPad.getText('testPad')

tmpDir = tempfile.mkdtemp()

# Clean up the directory yourself
# os.removedirs(tmpDir)

file = codecs.open("%s/pad.tex" % (tmpDir), "w", "utf-8")
#print "%s/pad.tex" %(tmpDir)
file.write(padText['text'])
file.close()

#cmdstring = "some_other_script.py %s %s" % (argument1 argument2)
cmdstring = "%s -output-directory=%s -halt-on-error %s/pad.tex > /dev/null" % (
    pdflatex, tmpDir, tmpDir)
os.system(cmdstring)
示例#6
0
文件: pdfjs.py 项目: azend/etherTeX
#!/usr/local/bin/python
pdflatex = "/usr/local/texlive/2011/bin/amd64-freebsd/pdflatex"
import cgi 
import cgitb; cgitb.enable()  # for troubleshooting
import os
import tempfile
import codecs

from py_etherpad import EtherpadLiteClient
myPad = EtherpadLiteClient('yourapitoken','http://etherpad.install.tld/api')

#get the text of the etherpad
padText = myPad.getText('testPad')

tmpDir= tempfile.mkdtemp()

# Clean up the directory yourself
# os.removedirs(tmpDir)

file = codecs.open("%s/pad.tex" %(tmpDir), "w", "utf-8")
#print "%s/pad.tex" %(tmpDir)
file.write(padText['text'])
file.close()

#cmdstring = "some_other_script.py %s %s" % (argument1 argument2)
cmdstring = "%s -output-directory=%s -halt-on-error %s/pad.tex > /dev/null" %(pdflatex,tmpDir,tmpDir)
os.system(cmdstring)
cmdstring = "cp %s/pad.pdf ." % (tmpDir)
os.system("rm pad.pdf")
os.system(cmdstring)
os.system("rm %s/pad*" % (tmpDir))
def getText(article):
	epclient = EtherpadLiteClient(settings.APIKEY, settings.APIURL)
	result =  epclient.getText(article.id)
	return result['text']
示例#8
0
def pad_read(request, mode="r", slug=None):
    """Read only pad
    """
    
    # FIND OUT WHERE WE ARE,
    # then get previous and next
    try:
        articles = json.load(open(os.path.join(BACKUP_DIR, 'index.json')))
    except IOError:
        articles = []
    
    SITE = get_current_site(request)
    href = "http://%s" % SITE.domain + request.path
    
    prev = None
    next = None
    for i, article in enumerate(articles):
        if article['href'] == href:
            if i != 0:        # The first is the most recent article, there is no newer
                next = articles[i-1]
            if i != len(articles) - 1:
                prev = articles[i+1]

    # Initialize some needed values
    pad = get_object_or_404(Pad, display_slug=slug)

    padID = pad.group.groupID + '$' + urllib.quote_plus(pad.name.replace('::', '_'))
    epclient = EtherpadLiteClient(pad.server.apikey, pad.server.apiurl)

    # Etherpad gives us authorIDs in the form ['a.5hBzfuNdqX6gQhgz', 'a.tLCCEnNVJ5aXkyVI']
    # We link them to the Django users DjangoEtherpadLite created for us
    authorIDs = epclient.listAuthorsOfPad(padID)['authorIDs']
    authors = PadAuthor.objects.filter(authorID__in=authorIDs)

    authorship_authors = []
    for author in authors:
        authorship_authors.append({ 'name'  : author.user.first_name if author.user.first_name else author.user.username,
                                    'class' : 'author' + author.authorID.replace('.','_') })
    authorship_authors_json = json.dumps(authorship_authors, indent=2)

    name, extension = os.path.splitext(slug)

    meta = {}

    if not extension:
        # Etherpad has a quasi-WYSIWYG functionality.
        # Though is not alwasy dependable
        text = epclient.getHtml(padID)['html']
        # Quick and dirty hack to allow HTML in pads
        text = unescape(text)
    else:
        # If a pad is named something.css, something.html, something.md etcetera,
        # we don’t want Etherpads automatically generated HTML, we want plain text.
        text = epclient.getText(padID)['text']
        if extension in ['.md', '.markdown']:
            md = markdown.Markdown(extensions=['extra', 'meta', 'headerid(level=2)', 'attr_list', 'figcaption'])
            text = md.convert(text)
            try:
                meta = md.Meta
            except AttributeError:   # Edge-case: this happens when the pad is completely empty
                meta = None
    
    # Convert the {% include %} tags into a form easily digestible by jquery
    # {% include "example.html" %} -> <a id="include-example.html" class="include" href="/r/include-example.html">include-example.html</a>
    def ret(matchobj):
        return '<a id="include-%s" class="include pad-%s" href="%s">%s</a>' % (slugify(matchobj.group(1)), slugify(matchobj.group(1)), reverse('pad-read', args=("r", matchobj.group(1)) ), matchobj.group(1))
    
    text = include_regex.sub(ret, text)
    
    
    # Create namespaces from the url of the pad
    # 'pedagogy::methodology' -> ['pedagogy', 'methodology']
    namespaces = [p.rstrip('-') for p in pad.display_slug.split('::')]

    meta_list = []

    # One needs to set the ‘Static’ metadata to ‘Public’ for the page to be accessible to outside visitors
    if not meta or not 'status' in meta or not meta['status'][0] or not meta['status'][0].lower() in ['public']:
        if not request.user.is_authenticated():
            pass #raise PermissionDenied
    
    if meta and len(meta.keys()) > 0:
        
        # The human-readable date is parsed so we can sort all the articles
        if 'date' in meta:
            meta['date_iso'] = []
            meta['date_parsed'] = []
            for date in meta['date']:
                date_parsed = dateutil.parser.parse(date)
                # If there is no timezone we assume it is in Brussels:
                if not date_parsed.tzinfo:
                    date_parsed = pytz.timezone('Europe/Brussels').localize(date_parsed) 
                meta['date_parsed'].append(date_parsed)
                meta['date_iso'].append( date_parsed.isoformat() )
        
        meta_list = list(meta.iteritems())

    tpl_params = { 'pad'                : pad,
                   'meta'               : meta,      # to access by hash, like meta.author
                   'meta_list'          : meta_list, # to access all meta info in a (key, value) list
                   'text'               : text,
                   'prev_page'          : prev,
                   'next_page'          : next,
                   'mode'               : mode,
                   'namespaces'         : namespaces,
                   'authorship_authors_json' : authorship_authors_json,
                   'authors'            : authors }

    if not request.user.is_authenticated():
        request.session.set_test_cookie()
        tpl_params['next'] = reverse('pad-write', args=(slug,) )

    if mode == "r":
        return render_to_response("pad-read.html", tpl_params, context_instance = RequestContext(request))
    elif mode == "s":
        return render_to_response("pad-slide.html", tpl_params, context_instance = RequestContext(request))
    elif mode == "p":
        return render_to_response("pad-print.html", tpl_params, context_instance = RequestContext(request))