Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
hotena_blog_post_for_cotEditer.py
#!/usr/local/bin/python
#coding=utf-8
"""post hatena-blog script for CotEditor
Post text of the current document on CotEditor to Habeta-blog.
This is a CotEditor script.
"""
__version__ = '1.0.0'
__date__ = '2017-08-24'
__author__ = 'tadaken3 <http://tadaken3.hatenablog.jp/>'
__license__ = 'Creative Commons Attribution-NonCommercial 3.0 Unported License'
import sys
import datetime
import random
import hashlib
import base64
import requests
from subprocess import Popen, PIPE
# setting -----------------------------------------------------------
username = 'Your Name'
api_key = 'API kye'
blogname = 'yourblogname.hatenablog.jp'
# main --------------------------------------------------------------
def main():
file = run_osascript('tell application "CotEditor" '
'to return path of front document')
title, body = parseText(file)
data = create_data(title, body)
post_hatena(data)
def run_osascript(script):
p = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE)
stdout, stderr = p.communicate(script)
return stdout.rstrip()
def wsse(username, api_key):
created = datetime.datetime.now().isoformat() + "Z"
b_nonce = hashlib.sha1(str(random.random())).digest()
b_digest = hashlib.sha1(b_nonce + created + api_key).digest()
c = 'UsernameToken Username="{0}", PasswordDigest="{1}", Nonce="{2}", Created="{3}"'
return c.format(username, base64.b64encode(b_digest), base64.b64encode(b_nonce), created)
def create_data(title,body):
template = """<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:app="http://www.w3.org/2007/app">
<title>{0}</title>
<author><name>name</name></author>
<content type="text/plain">{1}</content>
<updated>2013-09-05T00:00:00</updated>
<app:control>
<app:draft>yes</app:draft>
</app:control>
</entry>
"""
data = template.format(title, body)
return data
def parseText(file):
with open(file) as f:
obj = f.readlines()
title = ""
body = ""
for i, line in enumerate(obj):
if i == 0:
title = line
else:
body = body + line
return title, body
def post_hatena(data):
headers = {'X-WSSE': wsse(username, api_key)}
url = 'http://blog.hatena.ne.jp/{0}/{1}/atom/entry'.format(username, blogname)
r = requests.post(url, data=data, headers=headers)
if r.status_code != 201:
sys.stderr.write('Error!\n' + 'status_code: ' + str(r.status_code) + '\n' + 'message: ' + r.text)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.