Skip to content

Instantly share code, notes, and snippets.

@lihongjie0209
Created April 2, 2017 03:22
Show Gist options
  • Save lihongjie0209/65712f03252b99514ba7df7271ecb8e1 to your computer and use it in GitHub Desktop.
Save lihongjie0209/65712f03252b99514ba7df7271ecb8e1 to your computer and use it in GitHub Desktop.
auto commit screen shot to github and copy the the picture link to clipboard.
"""
本脚本主要用于自动上传截图至github, 主要逻辑如下:
1. 每隔两秒扫描截图文件夹, 得到截图文件总数
2. 与之前的截图总数对比, 如果有新的图片, 那么自动上传至github
3. 复制图片地址到剪贴板
"""
import logging
from pathlib import Path
import requests
from urllib.parse import urlparse, urlunparse
import base64
import time
import pyperclip
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
formater = logging.Formatter(fmt='%(asctime)s [%(levelname)s] %(message)s')
handler.setFormatter(formater)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
dir = Path('/home/lihongjie/Pictures')
repo_url = 'https://github.com/lihongjie0209/Picture'
def repo_to_api(repo, file, download=False):
# ParseResult(scheme='https', netloc='github.com', path='/lihongjie0209/Practice', params='', query='', fragment='')
l = list(urlparse(repo))
l[1] = 'api.github.com' if not download else "raw.githubusercontent.com"
l[2] = '/repos' + l[2] + '/contents/' if not download else l[2] + \
"/master/{}".format(file.name)
api = urlunparse(l)
logger.debug("get_api: {}".format(api))
return api
def get_file_content(file):
with file.open('rb') as f:
bytes_content = f.read()
encode_content = base64.b64encode(bytes_content)
return encode_content
def auto_commit(file, repo, message="auto commit"):
create_file_api = repo_to_api(repo, file)
file_url = create_file_api + file.name
logger.debug("file_url: {}".format(file_url))
file_content = get_file_content(file)
headers = {"Authorization": "token 4d34eb8b0499c837249f1623736ecfdc77a9f06a",
"Accept": "application / vnd.github.v3 + json",
"Content-Type": "application/json"}
payload = {'path': file.name,
'message': message,
'content': str(file_content, encoding='ascii'),
'branch': 'master'}
r = requests.put(file_url, headers=headers, json=payload)
response = r.json()
logger.info("auto commit [ {} ] to {}".format(response['content']['name'], response['content']['_links']['html']))
return response
def copy_link(repo, file):
pic_link = repo_to_api(repo=repo, file=file, download=True)
pyperclip.copy(pic_link)
logger.info("copy {} to clipboard".format(pic_link))
def get_pic_num():
pics = get_all_pic()
pic_num = len(pics)
logger.debug("the number of picture is {}".format(pic_num))
return pic_num
def get_all_pic(prefix="Screenshot"):
pics = [i for i in dir.iterdir() if i.name.startswith(prefix)]
return pics
def get_new_pic():
pics = get_all_pic()
pics.sort(key=lambda p: p.stat().st_ctime)
new_pic = pics[-1]
logger.info("find new screen shot: {} ".format(str(new_pic)))
return new_pic
def main():
old_num = get_pic_num()
while True:
time.sleep(2)
current_num = get_pic_num()
if current_num > old_num:
new_pic = get_new_pic()
copy_link(repo=repo_url, file=new_pic)
auto_commit(file=new_pic, repo=repo_url, message='auto commit')
old_num = current_num
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment