Skip to content

Commit 13c3748

Browse files
committed
[20160820]
[description] version 1.0.0 now you can write your own in uploader folder and if you do not have config, there will be a default config.
1 parent 64f342e commit 13c3748

File tree

9 files changed

+174
-111
lines changed

9 files changed

+174
-111
lines changed

ImageGrab/WinImageGrab.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import os
2+
import time
3+
from PIL import ImageGrab, ImageFile
4+
5+
ImageFile.LOAD_TRUNCATED_IMAGES = True
6+
7+
8+
class WinImageGrab(object):
9+
def __init__(self, picture_folder, picture_suffix):
10+
self.picture_folder = picture_folder
11+
self.picture_suffix = picture_suffix
12+
13+
def save_picture(self):
14+
date_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
15+
picture_name = date_time + '.' + self.picture_suffix
16+
picture_path = os.path.join(self.picture_folder, picture_name)
17+
try:
18+
picture_data = ImageGrab.grabclipboard()
19+
if picture_data:
20+
picture_data.save(picture_path, self.picture_suffix)
21+
return picture_path
22+
else:
23+
print('there is no picture in clipboard!')
24+
except Exception as e:
25+
print('get picture from clipboard error because: {}'.format(e))
26+
return ''

ImageGrab/__init__.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import sys
2+
3+
4+
system = sys.platform
5+
ImageGrab = None
6+
if system == 'win32':
7+
from .WinImageGrab import WinImageGrab
8+
ImageGrab = WinImageGrab
9+
elif system.startswith('darwin'):
10+
ImageGrab = None

MarkdownPicPicker.py

Lines changed: 39 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,32 @@
1-
from PIL import ImageGrab, ImageFile
2-
from configparser import ConfigParser
3-
from uploader.QiniuUploader import QiniuUploader
4-
import time
1+
from ImageGrab import ImageGrab
2+
from uploader.SmUploader import Uploader
53
import sys
64
import os
7-
8-
try:
9-
import pythoncom
10-
except ImportError:
11-
print('maybe you have not install pywin32 or not in windows system.')
12-
pythoncom = None
135
try:
14-
import pyHook
15-
except ImportError:
16-
print('maybe you have not install pyHook.')
17-
pyHook = None
18-
19-
ImageFile.LOAD_TRUNCATED_IMAGES = True
6+
from config import read_config
7+
except Exception as _:
8+
print('read config error, use default info.')
9+
config = None
2010

21-
__version__ = '0.2.2'
11+
__version__ = '1.0.0'
2212
__author__ = 'kingname'
2313

24-
from config import read_config
25-
2614

2715
class MarkrdownPicPicker(object):
28-
CONFIG_PATH = 'config.ini'
2916

3017
def __init__(self, link_only=False):
31-
32-
self.method = ''
33-
self.picture_folder = ''
34-
self.picture_suffix = ''
35-
self.picture_bed = ''
36-
self.short_key_one = ''
37-
self.short_key_two = ''
38-
self.key_one = False
39-
self.key_two = False
18+
self.cwd = ''
19+
self.picture_folder = 'pic'
20+
self.picture_suffix = 'png'
21+
self.picture_host = ''
4022
self.uploader = None
4123
self.link_only = link_only
42-
24+
self.config_path = ''
25+
self.uploader_info = {}
26+
self.imageGrab = None
4327
self.init_environment()
4428

45-
if self.method == 'bat':
46-
self.upload_picture()
47-
elif self.method == 'global_listen':
48-
self.keyboard_listen()
29+
self.upload_picture()
4930

5031
def _to_string(self):
5132
"""
@@ -54,68 +35,43 @@ def _to_string(self):
5435
"""
5536
print("folder", self.picture_folder)
5637
print("suffix", self.picture_suffix)
57-
print("picture_bed", self.picture_bed)
38+
print("picture_bed", self.picture_host)
5839

5940
def init_environment(self):
60-
self.__dict__.update(read_config())
61-
if not self.method \
62-
or not self.picture_folder \
63-
or not self.picture_suffix \
64-
or not self.picture_bed:
65-
print('there must be something wrong in config, please check.')
66-
exit()
41+
if not config:
42+
self.uploader = Uploader()
43+
else:
44+
self.__dict__.update(read_config())
45+
self.cwd = os.path.dirname(os.path.dirname(self.config_path))
46+
uploader_list = self._find_uploader()
47+
if self.picture_host and self.picture_host in uploader_list:
48+
self.uploader = __import__('uploader.' + self.picture_host,
49+
globals(), locals(), ['Uploader'], 0).Uploader(self.uploader_info)
50+
6751
if not os.path.exists(self.picture_folder):
6852
os.makedirs(self.picture_folder)
69-
if self.picture_bed:
70-
self.uploader = QiniuUploader(self.uploader_info)
71-
72-
def keyboard_listen(self):
73-
if not pythoncom or not pyHook:
74-
print('as pythoncom or pyHook is not exists, please use bat method.')
75-
exit()
76-
if not self.short_key_one or not self.short_key_two:
77-
print('there must be something wrong in the config, please check.')
53+
self.imageGrab = ImageGrab(self.picture_folder, self.picture_suffix) if ImageGrab else None
54+
if not self.imageGrab:
55+
print('can not find image grab, exit.')
7856
exit()
79-
hm = pyHook.HookManager()
80-
hm.KeyDown = self.keyboard_event
81-
hm.HookKeyboard()
82-
pythoncom.PumpMessages()
83-
84-
def keyboard_event(self, event):
85-
if event.Key == self.short_key_one and not self.key_one:
86-
self.key_one = True
87-
elif event.Key == self.short_key_two and not self.key_two:
88-
self.key_two = True
89-
if self.key_one and self.key_two:
90-
self.upload_picture()
91-
self.key_one = False
92-
self.key_two = False
93-
return True
9457

9558
def upload_picture(self):
96-
picture_path, picture_name = self.save_picture()
59+
picture_path = self.imageGrab.save_picture()
9760
if not picture_path:
9861
return False
9962
else:
100-
self.uploader.upload(picture_path, picture_name)
101-
self.uploader.write_markdown_picture_url(picture_name, link_only=True if self.link_only else False)
63+
self.uploader.upload(picture_path, link_only=True if self.link_only else False)
10264
return True
10365

104-
def save_picture(self):
105-
date_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
106-
picture_name = date_time + '.' + self.picture_suffix
107-
picture_path = os.path.join(self.picture_folder, picture_name)
108-
try:
109-
picture_data = ImageGrab.grabclipboard()
110-
if picture_data:
111-
picture_data.save(picture_path, self.picture_suffix)
112-
return picture_path, picture_name
113-
else:
114-
print('there is no picture in clipboard!')
115-
except Exception as e:
116-
print('get picture from clipboard error because: {}'.format(e))
117-
return '', ''
66+
def _find_uploader(self):
67+
uploader_folder = os.path.join(self.cwd, 'uploader')
68+
if os.path.isdir(uploader_folder):
69+
uploader_list = [uploader_file.split('.')[0] for uploader_file in os.listdir(uploader_folder)]
70+
if uploader_list:
71+
return uploader_list
11872

73+
print('can not find the uploader folder.')
74+
exit()
11975

12076
if __name__ == '__main__':
12177
arg = sys.argv[-1]

config/__init__.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import sys, os
1+
import sys
2+
import os
23
from configparser import ConfigParser
34

45

@@ -8,23 +9,21 @@ def read_config():
89
config_path = os.path.join(os.path.dirname(sys.executable), 'config.ini')
910
else:
1011
config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini')
11-
print(config_path)
12-
configs = ConfigParser()
12+
1313
if not os.path.exists(config_path):
14-
print('can not find the config.ini, exit')
15-
exit()
14+
print('can not find the config.ini, use the default sm uploader.'
15+
'attention: this website may breakdown in the future, only used temporarily.')
16+
_dict['picture_host'] = 'SmUploader'
17+
return _dict
18+
configs = ConfigParser()
1619
configs.read(config_path)
17-
_dict['method'] = configs['basic'].get('run_method', '')
1820
_dict['picture_folder'] = configs['basic'].get('picture_folder', '')
1921
_dict['picture_suffix'] = configs['basic'].get('picture_suffix', '')
20-
_dict['picture_bed'] = configs['basic'].get('picture_bed', '')
21-
22-
if _dict['picture_bed']:
23-
_dict['uploader_info'] = configs['qiniu']
22+
_dict['picture_host'] = configs['basic'].get('picture_host', '')
23+
_dict['config_path'] = config_path
2424

25-
if _dict['method'] == 'global_listen':
26-
_dict['short_key_one'] = configs['global_listen']['short_key_one']
27-
_dict['short_key_two'] = configs['global_listen']['short_key_two']
25+
if _dict['picture_host']:
26+
_dict['uploader_info'] = configs[_dict['picture_host']]
2827

2928
return _dict
3029

config/config.ini

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,14 @@
11
[basic]
2-
# method can be [bat] or [global_listen]
3-
run_method = bat
42
picture_folder = pic
53
picture_suffix = png
6-
# now support qiniu only
7-
picture_bed = qiniu
4+
# now support SmUploader or QiniuUploader, the default is SmUploader
5+
picture_host = SmUploader
86

9-
[global_listen]
10-
short_key_one = Lwin
11-
short_key_two = C
12-
13-
[qiniu]
14-
access_key = Q6sS422O05asdfasd3FqasdfasdfF36tqvyQ75Zvzw
15-
secret_key = 6QtAqqTxoSxasdfsaddfROehxPLX2CCmoOaB2aLObM
7+
[QiniuUploader]
8+
access_key = Q6sS422O0fafadfasdfahqCcCpF36tqvyQ75Zvzw
9+
secret_key = 6QtAqqTxoSxZP-asdfasdfasdfasCmoOaB2aLObM
1610
container_name = picturebed
17-
url = http://7sbpmp.com1.z0.glb.clouddn.com/{}
11+
url = http://7sbpmp.com1.z0.glb.clouddn.com/{}
12+
13+
[SmUploader]
14+
url = https://sm.ms/api/upload

markdownPicPicker/__init__.py

Whitespace-only changes.

uploader/ImgurUploader.py

Whitespace-only changes.

uploader/QiniuUploader.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,37 @@
22
import os
33

44

5-
class QiniuUploader(object):
5+
class Uploader(object):
66
def __init__(self, config_info):
77
self.upload_handler = None
88
self.url = config_info['url']
99
self.container_name = config_info.get('container_name')
1010
self.upload_handler = Auth(config_info.get('access_key'), config_info.get('secret_key'))
1111

12-
def upload(self, picture_path, picture_name):
12+
def upload(self, picture_path, link_only=False):
1313
if self.upload_handler:
14+
picture_name = os.path.basename(picture_path)
1415
token = self.upload_handler.upload_token(self.container_name, picture_name, 3600)
1516
info = put_file(token, picture_name, picture_path)
1617
print(info)
18+
self.write_markdown_picture_url(picture_path, link_only)
1719

18-
def write_markdown_picture_url(self, picture_name, link_only=False):
20+
def write_markdown_picture_url(self, picture_path, link_only=False):
21+
picture_name = os.path.basename(picture_path)
1922
if link_only:
2023
markdown_picture_url = self.url.format(picture_name)
2124
else:
2225
markdown_picture_url = '![]({})'.format(self.url.format(picture_name))
2326
command = 'echo {} | clip'.format(markdown_picture_url)
2427
os.system(command)
28+
print('the url is already in your clipboard!')
29+
30+
if __name__ == '__main__':
31+
config_info = {
32+
'url': 'http://7sbpmp.com1.z0.glb.clouddn.com/{}',
33+
'access_key': 'Q6sS422O0asdffd5aVqM3FsdfdfpF36tqvyQ75Zvzw',
34+
'secret_key': '6QtAqqTfasdZP - 2uoXsdfaeeLX2CCmoOaB2aLObM',
35+
'container_name': 'picturebed'
36+
}
37+
uploader = Uploader(config_info)
38+
uploader.upload('1.png')

uploader/SmUploader.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import requests
2+
import json
3+
import os
4+
5+
class Uploader(object):
6+
'''
7+
you can read this api at https://sm.ms/doc/
8+
after uploading, you will get a json:
9+
{
10+
"code": "success",
11+
"data": {
12+
width: 1157,
13+
height: 680,
14+
filename: "image_2015-08-26_10-54-48.png",
15+
storename: "56249afa4e48b.png",
16+
size: 69525,
17+
path: "/2015/10/19/56249afa4e48b.png",
18+
hash: "nLbCw63NheaiJp1",
19+
timestamp: 1445239546,
20+
url: "https://ooo.0o0.ooo/2015/10/19/56249afa4e48b.png",
21+
delete: "https://sm.ms/api/delete/nLbCw63NheaiJp1"
22+
}
23+
}
24+
and the url of this image's key is 'url'
25+
26+
'''
27+
28+
DEFAULT_URL = 'https://sm.ms/api/upload'
29+
30+
def __init__(self, _=None):
31+
self.url = self.DEFAULT_URL
32+
33+
def upload(self, picture_path, link_only=False):
34+
picture_file_handler = open(picture_path, 'rb')
35+
data = {'smfile': picture_file_handler}
36+
result_json = requests.post(self.url, files=data).content
37+
try:
38+
result_dict = json.loads(result_json.decode())
39+
except Exception as _:
40+
print('the result of the picture bed is not standard json.' )
41+
return None
42+
finally:
43+
picture_file_handler.close()
44+
pic_url = result_dict.get('data', {}).get('url', '')
45+
if pic_url:
46+
self.write_markdown_picture_url(pic_url, link_only)
47+
48+
def write_markdown_picture_url(self, pic_url, link_only=False):
49+
if link_only:
50+
markdown_picture_url = pic_url
51+
else:
52+
markdown_picture_url = '![]({})'.format(pic_url)
53+
command = 'echo {} | clip'.format(markdown_picture_url)
54+
os.system(command)
55+
print('the url is already in your clipboard!')
56+
57+
58+
if __name__ == '__main__':
59+
uploader = Uploader({'url': 'https://sm.ms/api/upload'})
60+
uploader.upload('3.png')
61+

0 commit comments

Comments
 (0)