Browse Source

pep8, license header

master
Maxim Likhachev 6 years ago
parent
commit
e90c93e516
  1. 67
      src/vkdigest.py

67
src/vkdigest.py

@ -1,7 +1,20 @@ @@ -1,7 +1,20 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) envrm
# Copyright (C) 2019, Maxim Lihachev, <envrm@yandex.ru>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# pip install vk_api
@ -27,6 +40,7 @@ from email.mime.text import MIMEText @@ -27,6 +40,7 @@ from email.mime.text import MIMEText
############################################################################
def usage():
print '''
vkdigest сценарий для получения сообщений из сообществ vk.com
@ -46,6 +60,7 @@ def usage(): @@ -46,6 +60,7 @@ def usage():
############################################################################
# Конфигурационный файл
CONFIG_FILE = os.path.join(os.path.dirname(__file__), os.pardir, 'conf/vkdigest.ini')
@ -66,6 +81,7 @@ CSS_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.p @@ -66,6 +81,7 @@ CSS_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.p
############################################################################
def readConfig(config_file):
'''Чтение конфигурационного файла'''
global settings
@ -74,22 +90,27 @@ def readConfig(config_file): @@ -74,22 +90,27 @@ def readConfig(config_file):
settings.read(config_file)
return settings
def opt(parameter):
'''Получение опции из файла'''
setting = parameter.split(":")
return settings.get(setting[0], setting[1])
def enabled(opt):
return opt.lower() in ("yes", "true", "t", "1")
def timestamp_to_date(timestamp, fmt='%Y-%m-%d %H:%M:%S'):
'''Преобразование временного штампа в читаемую дату'''
return datetime.datetime.fromtimestamp(int(timestamp)).strftime(fmt)
def today():
'''Текущая дата'''
return int(datetime.datetime.strptime(datetime.datetime.today().strftime('%Y-%m-%d'), '%Y-%m-%d').strftime("%s"))
def u(string):
return string.encode('utf-8')
@ -97,11 +118,16 @@ def u(string): @@ -97,11 +118,16 @@ def u(string):
def make_title():
'''Заголовок страницы и тема письма'''
return MAIL_SUBJECT.format(URL=opt('mail:url'), COMMENT=opt('mail:comment'), DATE=timestamp_to_date(today(), '%Y-%m-%d'))
return MAIL_SUBJECT.format(URL=opt('mail:url'),
COMMENT=opt('mail:comment'),
DATE=timestamp_to_date(today(),
'%Y-%m-%d'))
# Псевдоним для функции send_email
make_subject = make_title
def send_email(message):
'''Отправка письма с дайжестом'''
subject = make_subject()
@ -134,39 +160,48 @@ def auth(login, password): @@ -134,39 +160,48 @@ def auth(login, password):
print(error_msg)
return
def only_today(wall, date=None):
'''Записи за указанную дату'''
return [post for post in wall if post['date'] >= today()]
def get_group_url(group):
'''Адрес группы'''
return group.split(' ')[0]
def get_group_name(url):
'''HTTP-имя группы'''
return url.split('/')[-1]
def get_photos(attachments):
'''Получение ссылок на изображения'''
return [attachment['photo'] for attachment in attachments if attachment['type'] == 'photo']
def get_documents(attachments):
'''Получение ссылок на документы'''
return [attachment['doc'] for attachment in attachments if attachment['type'] == 'doc']
def get_links(attachments):
'''Получение ссылок'''
return [attachment['link'] for attachment in attachments if attachment['type'] == 'link']
def group_info(name):
'''Информация о сообществе'''
# TODO: если репост со страницы пользователя, то вставляет название группы
return vk.groups.getById(group_ids=name)[0]
def wall_url(group_id, post_id):
'''Ссылка на конкретный пост'''
return "http://vk.com/wall" + str(group_id) + '_' + str(post_id)
def wall(name):
'''Получение записей со стены сообщества'''
id = group_info(get_group_name(name))['id']
@ -180,6 +215,7 @@ def wall(name): @@ -180,6 +215,7 @@ def wall(name):
############################################################################
def html_toc(groups):
'''Содержание дайжеста со ссылками на группы'''
HTML.h2("Сообщества:")
@ -194,6 +230,7 @@ def html_toc(groups): @@ -194,6 +230,7 @@ def html_toc(groups):
HTML.br()
HTML.hr()
def groups_info(input_file):
'''Информация о группах, перечисленных в файле'''
f = open(input_file, "r")
@ -214,6 +251,7 @@ def groups_info(input_file): @@ -214,6 +251,7 @@ def groups_info(input_file):
group_info_html(url)
wall_html(url)
def group_info_html(name):
'''Информация о группе в формате HTML'''
group_name = get_group_name(name)
@ -231,6 +269,7 @@ def group_info_html(name): @@ -231,6 +269,7 @@ def group_info_html(name):
HTML.br()
HTML.hr()
def wall_html(name):
'''Сообщения со стены сообщества в формате HTML'''
info = wall(name)
@ -242,6 +281,7 @@ def wall_html(name): @@ -242,6 +281,7 @@ def wall_html(name):
elif 'copy_history' in post:
post_html(post['copy_history'][0], True)
def post_html(content, repost=False):
'''Информация о посте в формате HTML'''
HTML.div(class_="post")
@ -281,6 +321,7 @@ def post_html(content, repost=False): @@ -281,6 +321,7 @@ def post_html(content, repost=False):
############################################################################
# Чтение файла настроек
settings = []
readConfig(CONFIG_FILE)
@ -306,19 +347,26 @@ url = False @@ -306,19 +347,26 @@ url = False
CLI_OUTPUT_FLAG = False
for option, arg in opts:
if option in ('-h', '--help'): usage()
elif option in ('-f', '--file'): input_file = arg
elif option in ('-u', '--url'): url = arg
elif option in ('-s', '--subj'): MAIL_SUBJECT = arg
elif option in ('-t', '--title'): MAIL_SUBJECT = arg
if option in ('-h', '--help'):
usage()
elif option in ('-f', '--file'):
input_file = arg
elif option in ('-u', '--url'):
url = arg
elif option in ('-s', '--subj'):
MAIL_SUBJECT = arg
elif option in ('-t', '--title'):
MAIL_SUBJECT = arg
elif option in ('-o', '--out'):
FILE_OUTPUT = arg
CLI_OUTPUT = False
elif option in ('-m', '--mail'):
SEND_MAIL = True
CLI_OUTPUT = False
elif option in ('-c', '--cli'): CLI_OUTPUT_FLAG = True
else: usage()
elif option in ('-c', '--cli'):
CLI_OUTPUT_FLAG = True
else:
usage()
if CLI_OUTPUT_FLAG:
CLI_OUTPUT = True
@ -354,4 +402,3 @@ if FILE_OUTPUT: @@ -354,4 +402,3 @@ if FILE_OUTPUT:
if CLI_OUTPUT:
print HTML

Loading…
Cancel
Save