pax_global_header00006660000000000000000000000064127205523610014515gustar00rootroot0000000000000052 comment=7ca692051a444418855e346ea1fdda77d1ab3ffc db2twitter-0.6/000077500000000000000000000000001272055236100134545ustar00rootroot00000000000000db2twitter-0.6/.gitignore000066400000000000000000000003751272055236100154510ustar00rootroot00000000000000db2twitter.ini db2twitter.ini.avec_id_defini __pycache__ db2twitter.db .coverage db2twitter.egg-info linuxjobsfrnew.sql linuxjobsfrold.sql linuxjobsfrbefore.sql *.swp 1461837260_logoTPT.jpg fallback_1461837260_logoTPT.jpg set_env_and_fire.sh docs/build db2twitter-0.6/.travis.yml000066400000000000000000000004151272055236100155650ustar00rootroot00000000000000language: python python: - "3.3" - "3.4" - "3.5" # command to install dependencies install: - pip install -r requirements.txt - pip install coveralls # command to run tests script: coverage3 run --source=db2twitter setup.py test after_success: coveralls db2twitter-0.6/README.md000066400000000000000000000042261272055236100147370ustar00rootroot00000000000000[](https://travis-ci.org/chaica/db2twitter) # db2twitter db2twitter automatically extracts fields from your database, use them to feed a template of tweet and send the tweet. ### Quick Install * Install db2twitter from PyPI # pip3 install db2twitter * Install db2twitter from sources # tar zxvf db2twitter-0.6.tar.gz # cd db2twitter # python3.4 setup.py install # # or # python3.4 setup.py install --install-scripts=/usr/bin ### Use db2twitter * Create or modify db2twitter.ini file in order to configure db2twitter: [twitter] consumer_key=pPskvBmlE1yatbrFsLMdQL1r3m consumer_secret=lkjerpleRZER4xf948sfsrfgmlkezrZERgl1234ljfeqIdIie4 access_token=1234823497-912qsdfkerR913U5hjzer34234kerPzAQHoP9ez access_token_secret=ljsERZE987h8k1klr123k9kezr09h134HLKJER98er5K1 tweet={} recrute un {} https://www.linuxjobs.fr/jobs/{} hashtags=devops,linux,debian,redhat,python,java,php,mysql,postgresql upper_first_char=true [database] ; use the following for MySQL - you need mysql_connector_python dbconnector=mysql+mysqlconnector ; use the following for PostgreSQL - you need psycopg2 python library ; dbconnector=postgresql+psycopg2 dbhost=localhost database=jobboard dbuser=jobboard dbpass=V3rYS3cr3t dbtables=jobs, jobs_rows=companyname,jobtitle,id,logo jobs_image=true ; send custom sql filter to the request with the following line ; jobs_sqlfilter=status=1 [sqlite] sqlitepath=/home/chaica/progra/python/db2twitter/db2twitter.db [media] image_path=/var/www/jobboard/images/ [timer] days=mon-fri, hours=0-11,14-17, [circle] last_tweets=3 each_time=2 ; no_image=true * Launch db2twitter $ db2twitter /path/to/db2twitter.ini ### Authors Carl Chenet ### License This software comes under the terms of the GPLv3+. See the LICENSE file for the complete text of the license. db2twitter-0.6/db2twitter.py000077500000000000000000000001701272055236100161210ustar00rootroot00000000000000#!/usr/bin/env python3 # app libraries imports from db2twitter.main import Main if __name__ == '__main__': Main() db2twitter-0.6/db2twitter/000077500000000000000000000000001272055236100155465ustar00rootroot00000000000000db2twitter-0.6/db2twitter/__init__.py000066400000000000000000000000001272055236100176450ustar00rootroot00000000000000db2twitter-0.6/db2twitter/cliparse.py000066400000000000000000000044051272055236100177250ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright © 2015-2016 Carl Chenet # 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 # 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 # CLI parsing '''CLI parsing''' # standard libraries imports from argparse import ArgumentParser import os.path import sys class CliParse(object): '''CliParse class''' def __init__(self): '''Constructor for the CliParse class''' self.epilog = 'For more information: https://db2twitter.readthedocs.io' self.description = 'db2twitter automatically extracts fields from your database, use them to feed a template of tweet and send the tweet' self.main() def main(self): '''main of CliParse class''' parser = ArgumentParser(prog='db2twitter', description=self.description, epilog=self.epilog) parser.add_argument('pathtoconf', metavar='FILE', type=str, help='the path to the retweet configuration') parser.add_argument('-c', '--circle', action='store_true', default=False, help='circling the last tweets') parser.add_argument('--dry-run', dest='dryrun', action='store_true', default=False, help='simulate the execution, no tweet sent') self.cliargs = parser.parse_args() if not os.path.exists(self.cliargs.pathtoconf): sys.exit('the path you provided for db2twitter configuration file does not exist') if not os.path.isfile(self.cliargs.pathtoconf): sys.exit('the path you provided for db2twitter configuration is not a file') @property def args(self): '''return the cli arguments''' return self.cliargs db2twitter-0.6/db2twitter/confparse.py000066400000000000000000000140621272055236100201030ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright © 2015-2016 Carl Chenet # 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 # 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 # 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 # 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 sqlitemaxid, text(filterrequest)) else: tableobj = session.query(tableschemas[table]).filter(tableschemas[table].columns.id > sqlitemaxid) else: tabrequest = '{}'.format(cfgvalues['ids'][table]) if cfgvalues['sqlfilter']: filterrequest = '{}'.format(cfgvalues['sqlfilter'][table]) tableobj = session.query(tableschemas[table]).filter(getattr(tableschemas[table].columns, tabrequest) > sqlitemaxid, text(filterrequest)) else: tableobj = session.query(tableschemas[table]).filter(getattr(tableschemas[table].columns, tabrequest) > sqlitemaxid) # ignore the None query result if tableobj: for tweetindb in tableobj: if table in cfgvalues['images']: # split the different fields we need, last field is the image path self.tweets.append({'withimage': True, 'data': [getattr(tweetindb, i) for i in cfgvalues['rows'][table]]}) else: self.tweets.append({'withimage': False, 'data': [getattr(tweetindb, i) for i in cfgvalues['rows'][table]]}) else: self.firstrun = True for table in cfgvalues['rows']: # if the table does not have a user-specified row 'id' if not cfgvalues['ids']: if cfgvalues['sqlfilter']: filterrequest = '{}'.format(cfgvalues['sqlfilter'][table]) tableobj = session.query(tableschemas[table]).filter(tableschemas[table].columns.id <= self.lastinsertid, text(filterrequest)) else: tableobj = session.query(tableschemas[table]).filter(tableschemas[table].columns.id <= self.lastinsertid) else: tabrequest = '{}'.format(cfgvalues['ids'][table]) if cfgvalues['sqlfilter']: filterrequest = '{}'.format(cfgvalues['sqlfilter']) tableobj = session.query(tableschemas[table]).filter(getattr(tableschemas[table].columns, tabrequest) <= self.lastinsertid, text(filterrequest)) else: tableobj = session.query(tableschemas[table]).filter(getattr(tableschemas[table].columns, tabrequest) <= self.lastinsertid) # ignore the None query result if tableobj: for tweetdb in tableobj: if table in cfgvalues['images']: # split the different fields we need, last field is the image path self.tweets.append({'withimage': True, 'data': [getattr(tweetdb, i) for i in cfgvalues['rows'][table]]}) else: # split the different fields we need self.tweets.append({'withimage': False, 'data': [getattr(tweetdb, i) for i in cfgvalues['rows'][table]]}) # lets quit now if nothing new to tweet if not self.tweets: sys.exit(0) @property def dbvalues(self): '''Database parsed values''' return (self.tweets, self.lastinsertid, self.firstrun) db2twitter-0.6/db2twitter/getdblasttweets.py000066400000000000000000000052351272055236100213320ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright © 2015-2016 Carl Chenet # 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 # 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 # 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 # 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 # Check the size of an image '''Check the size of an image''' # 3rd party libraries imports from PIL import Image class ImageSize(object): '''ImageSize class''' def __init__(self, imagepath): '''Constructor of the ImageSize class''' self.imagepath = imagepath self.iswidthok = False self.isheightok = False self.width = 0 self.height = 0 self.twittermin = 4 self.twittermax = 8192 self.imagesizeok = False self.main() def main(self): '''Main of ImageSize class''' with Image.open(self.imagepath) as im: self.width, self.height = im.size # control the width - should be >= 4 and <= 8192 if self.width >= self.twittermin and self.width <= self.twittermax: self.iswidthok = True else: self.iswidthok = False # control the height - should be >= 4 and <= 8192 if self.height >= self.twittermin and self.height <= self.twittermax: self.isheightok = True else: self.isheightok = False # prepare return value if self.iswidthok and self.isheightok: self.imagesizeok = True else: self.imagesizeok = False @property def sendtotwitter(self): '''Return boolean if image size is ok''' return self.imagesizeok db2twitter-0.6/db2twitter/main.py000066400000000000000000000045151272055236100170510ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright © 2015-2016 Carl Chenet # 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 # 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 # 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 # 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 # Got data about the already sent tweets '''Got data about the already sent tweets''' # 3rs party libraries imports import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base # app libraries imports from db2twitter.wasposted import WasPosted class SentTweets(object): '''SentTweets class''' def __init__(self, cfgvalues): '''Constructor for the TwBuild class''' self.cfgvalues = cfgvalues # activate the sqlite db engine = create_engine('sqlite:///{}'.format(self.cfgvalues['sqlitepath'])) tmpsession = sessionmaker(bind=engine) session = tmpsession() self.session = session WasPosted.metadata.create_all(engine) @property def sqlitesession(self): '''Get the current session to the already sent tweets sqlite3 database''' return self.session db2twitter-0.6/db2twitter/timetosend.py000066400000000000000000000075251272055236100203040ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright © 2015-2016 Carl Chenet # 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 # 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 # Is it time to send the tweet '''Is it time to send the tweet''' # standard libraries imports import datetime import sys class TimeToSend(object): '''TimeToSend class''' def __init__(self, cfgvalues): '''Constructor for the TimeToSend class''' self.weekdays = ['mon','tue','wed','thu','fri','sat','sun'] self.translateweekdays = {0: 'mon', 1: 'tue', 2: 'wed', 3: 'thu', 4: 'fri', 5: 'sat', 6: 'sun'} self.dayhours = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24] activehours = [i for i in cfgvalues['hours'].split(',') if i != ''] activedays = [i for i in cfgvalues['days'].split(',') if i != ''] self.sendthesedays = [] self.sendthesehours = [] # get the days while sending tweets is authorized for day in activedays: if '-' in day: dstart, dend = day.split('-') gendays = (i for i in self.weekdays[self.weekdays.index(dstart):self.weekdays.index(dend)+1]) for x in gendays: self.sendthesedays.append(x) else: self.sendthesedays.append(day) # get the hours while sending tweets is authorized for hour in activehours: if '-' in hour: hstart, hend = hour.split('-') for k in [hstart, hend]: if int(k) < 0: print('db2twitter.ini config file has a wrong value : hours should be >= 0') sys.exit(0) if int(k) > 23: print('db2twitter.ini config file has a wrong value : hours should be <= 23') sys.exit(0) genhours = (i for i in self.dayhours[self.dayhours.index(int(hstart)):self.dayhours.index(int(hend)+1)]) for y in genhours: self.sendthesehours.append(int(y)) else: if int(hour) < 0: print('db2twitter.ini config file has a wrong value : hours should be >= 0') sys.exit(0) if int(hour) > 23: print('db2twitter.ini config file has a wrong value : hours should be <= 23') sys.exit(0) self.sendthesehours.append(int(hour)) @property def sendthetweet(self): '''main of TimeToSend class''' #get the current date currentdate = self.getdate() currentweekday = self.translateweekdays[currentdate.weekday()] currenthour = currentdate.hour isgoodday = False isgoodhour = False if currentweekday in self.sendthesedays: isgoodday = True if currenthour in self.sendthesehours: isgoodhour = True if isgoodday and isgoodhour: return True else: return False def getdate(sel): '''get the current date and time''' return datetime.datetime.now() db2twitter-0.6/db2twitter/twbuild.py000066400000000000000000000107431272055236100175770ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright © 2015-2016 Carl Chenet # 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 # 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 # Build the tweet to send '''Build the tweet to send''' # standard libraries imports import os.path # app libraries imports from db2twitter.imagesize import ImageSize class TwBuild(object): '''TwBuild class''' def __init__(self, cfgvalues, dbvalues): '''Constructor for the TwBuild class''' self.cfgvalues = cfgvalues self.dbvalues = dbvalues self.tweets = [] self.main() def main(self): '''main of TwBuild class''' # get hashtags if self.cfgvalues['hashtags'] != '': hashtags = self.cfgvalues['hashtags'].split(',') hashtags = [i for i in hashtags if i != ''] for i in self.dbvalues: iswithimage = True if i['withimage']: # the tweet uses an image image = i['data'][-1] # lets apply a specific prefix to the image if self.cfgvalues['imageprefix']: image = ''.join([self.cfgvalues['imageprefix'], image]) # lets apply a specific path to the image if self.cfgvalues['imagepath']: image = os.path.join(self.cfgvalues['imagepath'], image) # if the image path does not exist, fallback to no-image tweet if not image or not os.path.exists(image) or not os.path.isfile(image): iswithimage = False else: im = ImageSize(image) if not im.sendtotwitter: # try the fallback if not self.cfgvalues['fallbackimageprefix']: iswithimage = False else: fallbackimage = os.path.join(os.path.dirname(image), ''.join([self.cfgvalues['fallbackimageprefix'], os.path.basename(image)])) # give up if the file of the fallback image does not exist if not os.path.exists(fallbackimage): iswithimage = False else: # check the size of the fallback image fallback = ImageSize(fallbackimage) if not fallback.sendtotwitter: iswithimage = False else: image = fallbackimage if iswithimage: j = self.cfgvalues['tweet'].format(*i['data']) # identify and replace hashtags j = j.lower() for hashtag in hashtags: pattern = ' ' + hashtag if pattern in j.lower(): j = j.replace(pattern, ' #{}'.format(hashtag)) # uppercase for the first letter of the tweet if self.cfgvalues['upper_first_char']: j = j[0].upper() + j[1:] self.tweets.append({'withimage': True, 'data': j, 'imagepath': image}) if not i['withimage'] or not iswithimage: j = self.cfgvalues['tweet'].format(*i['data']) # identify and replace hashtags j = j.lower() for hashtag in hashtags: pattern = ' ' + hashtag if pattern in j.lower(): j = j.replace(pattern, ' #{}'.format(hashtag)) # uppercase for the first letter of the tweet if self.cfgvalues['upper_first_char']: j = j[0].upper() + j[1:] self.tweets.append({'withimage': False, 'data': j}) @property def readytotweet(self): '''return the tweet ready to be sent''' return self.tweets db2twitter-0.6/db2twitter/twresend.py000066400000000000000000000044651272055236100177640ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright © 2015-2016 Carl Chenet # 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 # 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 # Send the tweet '''Send the tweet''' # 3rd party libraries imports import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base import tweepy # app libraries imports from db2twitter.wasposted import WasPosted from db2twitter.timetosend import TimeToSend class TwReSend(object): '''TwReSend class''' def __init__(self, cfgvalues, cliargs, tweets): '''Constructor for the TwReSend class''' self.cfgvalues = cfgvalues self.cliargs = cliargs self.tweets = tweets # activate the twitter api self.auth = tweepy.OAuthHandler(self.cfgvalues['consumer_key'], self.cfgvalues['consumer_secret']) self.auth.secure = True self.auth.set_access_token(self.cfgvalues['access_token'], self.cfgvalues['access_token_secret']) self.api = tweepy.API(self.auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) self.main() def main(self): '''main of TwSend class''' for tweet in self.tweets: if not tweet['imagepath'] or self.cfgvalues['circlenoimage']: if self.cliargs.dryrun: print(tweet['data']) else: self.api.update_status(status=tweet['data']) else: if self.cliargs.dryrun: print('{} | image:{}'.format(tweet['data'], tweet['imagepath'])) else: self.api.update_with_media(tweet['imagepath'], status=tweet['data']) db2twitter-0.6/db2twitter/twsend.py000066400000000000000000000073251272055236100174330ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright © 2015-2016 Carl Chenet # 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 # 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 # Send the tweet '''Send the tweet''' # 3rd party libraries imports import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base import tweepy # 3rd party libraries from db2twitter.imagesize import ImageSize from db2twitter.timetosend import TimeToSend from db2twitter.wasposted import WasPosted class TwSend(object): '''TwSend class''' def __init__(self, cfgvalues, cliargs, tweets, session, dbvalues): '''Constructor for the TwBuild class''' _, self.lastinsertid, self.firstrun = dbvalues self.alreadysent = False self.cfgvalues = cfgvalues self.cliargs = cliargs self.tweets = tweets # activate the twitter api self.auth = tweepy.OAuthHandler(self.cfgvalues['consumer_key'], self.cfgvalues['consumer_secret']) self.auth.secure = True self.auth.set_access_token(self.cfgvalues['access_token'], self.cfgvalues['access_token_secret']) self.api = tweepy.API(self.auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) # activate the sqlite db self.session = session self.main() def main(self): '''main of TwSend class''' for tweet in self.tweets: self.alreadysent = False # store the tweets in the sqlite3 database if tweet['withimage']: self.storetweet(tweet['data'], tweet['imagepath']) else: self.storetweet(tweet['data'], '') # if it is the first run, dont send all the tweets if not self.firstrun: tts = TimeToSend(self.cfgvalues) # are date and time ok to send the tweet? if tts.sendthetweet: # was the tweet already sent? if not self.alreadysent: if tweet['withimage']: # dry run mode if self.cliargs.dryrun: print('{} | image:{}'.format(tweet['data'], tweet['imagepath'])) else: self.api.update_with_media(tweet['imagepath'], status=tweet['data']) else: # dry run mode if self.cliargs.dryrun: print(tweet['data']) else: self.api.update_status(status=tweet['data']) def storetweet(self, tweet, tweetimage): '''store a tweet in sqlite database''' newtweet = WasPosted(tweet=tweet, tweetimage=tweetimage, lastinsertid=self.lastinsertid) try: self.session.add(newtweet) self.session.commit() except (sqlalchemy.exc.IntegrityError) as err: print(err) print('tweet already sent') self.session.rollback() self.alreadysent = True db2twitter-0.6/db2twitter/wasposted.py000066400000000000000000000007721272055236100201370ustar00rootroot00000000000000'''WasPosted mapping for SQLAlchemy''' from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, DateTime, Boolean MYBASE = declarative_base() class WasPosted(MYBASE): '''WasPosted mapping for SQLAlchemy''' __tablename__ = 'wasposted' twid = Column(Integer, primary_key=True) tweet = Column(String, unique=True) tweetimage = Column(String, unique=False) lastinsertid = Column(Integer) lastcircled = Column(Boolean, default=False) db2twitter-0.6/docs/000077500000000000000000000000001272055236100144045ustar00rootroot00000000000000db2twitter-0.6/docs/Makefile000066400000000000000000000152171272055236100160520ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/backupchecker.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/backupchecker.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/backupchecker" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/backupchecker" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." db2twitter-0.6/docs/source/000077500000000000000000000000001272055236100157045ustar00rootroot00000000000000db2twitter-0.6/docs/source/authors.rst000066400000000000000000000000621272055236100201210ustar00rootroot00000000000000Authors ======= Carl Chenet db2twitter-0.6/docs/source/conf.py000066400000000000000000000201751272055236100172100ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # db2twitter documentation build configuration file, created by # sphinx-quickstart on Wed Dec 17 18:25:26 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.1' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'db2twitter' copyright = '2015-2016, Carl Chenet ' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.6' # The full version, including alpha/beta/rc tags. release = '0.6' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'db2twitterdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'db2twitter.tex', 'db2twitter Documentation', 'Carl Chenet \\textless{}chaica@ohmytux.com.org\\textgreater{}', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'db2twitter', 'db2twitter Documentation', ['Carl Chenet '], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'db2twitter', 'db2twitter Documentation', 'Carl Chenet ', 'db2twitter', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False db2twitter-0.6/docs/source/configure.rst000066400000000000000000000102761272055236100204250ustar00rootroot00000000000000.. _configure-section-label: Configure db2twitter ==================== As a prerequisite to use db2twitter, you need a Twitter app. Log in Twitter, go to https://apps.twitter.com, create an app and generate the access token. In order to configure db2twitter, you need to create a db2twitter.ini file (or any name you prefer, finishing with the extension .ini) with the following parameters:: [twitter] consumer_key=pPmJ3Bjlb2patls4r7AQW1k1l consumer_secret=lpj1kvnzbJxfKmeQtaQz18wm94klhaYIw5vaXq0l1mwId1wi1j access_token=1234567897-k8aN3Y5f6cfGgWhhLEuDGad1UPKHnPzkQHmP3q1 access_token_secret=nLQwDFwZR123456789uGE6YXIukY74TmBK6JLEC123456 tweet={} hires a {} https://www.linuxjobs.fr/jobs/{} hashtags=devops,linux,debian,redhat,python,java,php,mysql,postgresql upper_first_char=true [database] ; use the following for PostgreSQL - you need mysql_connector_python dbconnector=mysql+mysqlconnector ; use the following for PostgreSQL - you need psycopg2 python library ; dbconnector=postgresql+psycopg2 dbhost=localhost database=yourdatabase dbuser=yourdatabaseuser dbpass=V3rYs3cr3t dbtables=jobs, jobs_rows=company_name,title,id ;jobs_sqlfilter=status=1 [sqlite] sqlitepath=/var/lib/db2twitter/db2twitter.db [media] image_path=/var/www/mywebsite/images/ ; image prefix if all your images is prefixed by a string ; image_prefix=thumb_ ; fallback image prefix, e.g if your image does not have the good size for ; Twitter and you have a smaller image with the same name prefixed by a string ; fallback_image_prefix=thumb_ [timer] days=mon-fri, hours=0-11,14-17, [circle] last_tweets=3 each_time=2 ; no_image=true For the [twitter] section: - consumer_key: the Twitter consumer key (see your apps.twitter.com webpage) - consumer_secret: the Twitter consumer secret key (see your apps.twitter.com webpage) - access_token: the Twitter access token key (see your apps.twitter.com webpage) - access_token_secret: the Twitter access token secret key (see your apps.twitter.com webpage) - tweet: your tweet template. Should be a Python string format (see https://docs.python.org/3/library/string.html#format-examples) - hashtags: a # will be added to these words in your tweets - upper_first_char: use true if you want the first character of your tweets is upper case, false otherwise For the [database] section: - dbconnector: the Sqlalchemy connector to use to access your database (see examples) - dbhost: the host where the database runs - database: the name of the database - dbuser: the user name to access the database - dbpass: the password to access the database - dbtables: a comma-separated list of tables to use to get data from - jobs_rows: you should replace the jobs_rows field by a [your table]_rows field. You should have as much fields as the number of specified dbtables. This field contains a comma-separated name of the row to get data from - jobs_sqlfilter: a string to pass to SqlAlchemy filter() function in order to be a new filter condition on the table you want to parse. Useful e.g if you want to ignore some rows of your table For the [sqlite] section: - sqlitepath: the path to the sqlite3 database For the [media] section: - image_path: the path to the directory storing all the images you wish to send with your tweets - image_prefix: prefix string for your images, e.g if your image name in your database field is "cat.png" and the image name on your file system is "thumb_cat.png" - fallback_image_prefix: prefix to fallback on an image with the same name but prefixed by this string **if and only if** the image size check fails, e.g "cat.png" becomes "fallback_cat.png" For the [timer] section: - days: weekdays (mon for monday, thu for thursday, wed for wednesday, tue for tuesday, fri for friday, sat for saturday, sun for sunday) when db2twitter is authorized to send tweets - hours: hours of the day (0 to 23) when db2twitter is authorized to send tweets For the [circle] section - last_tweets: is the number of last tweets in the sqlite database to circle around - each_time: how many tweets to send at each execution with the circle parameter - no_image: while circling, do not tweet images db2twitter-0.6/docs/source/index.rst000066400000000000000000000010341272055236100175430ustar00rootroot00000000000000Documentation for the db2twitter project ======================================== db2twitter automatically extracts fields from your database, use them to feed a template of tweet and send the tweet. From 0.2 db2twitter stores already sent tweets in a sqlite3 database. You'll find below anything you need to install, configure or run db2twitter. Guide ===== .. toctree:: :maxdepth: 2 install configure use license authors Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` db2twitter-0.6/docs/source/install.rst000066400000000000000000000014561272055236100201120ustar00rootroot00000000000000How to install db2twitter ========================= From sources ^^^^^^^^^^^^ From db2twitter 0.6, you will need the `Pillow imaging library `_ in order to send images to Twitter. On a Debian system to install Pillow you could need the libjpeg-dev dependency. Install it with the following command: # apt-get install libjpeg-dev From PyPI ^^^^^^^^^ $ pip3 install db2twitter From sources ^^^^^^^^^^^^ * You need at least Python 3.4. * Untar the tarball and go to the source directory with the following commands:: $ tar zxvf db2twitter-0.6.tar.gz $ cd db2twitter * Next, to install db2twitter on your computer, type the following command with the root user:: $ python3.4 setup.py install $ # or $ python3.4 setup.py install --install-scripts=/usr/bin db2twitter-0.6/docs/source/license.rst000066400000000000000000000002031272055236100200530ustar00rootroot00000000000000License ======= This software comes under the terms of the **GPLv3+**. See the LICENSE file for the complete text of the license. db2twitter-0.6/docs/source/use.rst000066400000000000000000000013201272055236100172260ustar00rootroot00000000000000Use db2twitter ============== After the configuration of db2twitter, just launch the following command:: $ db2twitter /path/to/db2twitter.ini To use the circle mode, meaning you will alternatively tweet X tweets of your Y last tweets of your database (see the :ref:`configure-section-label` section), use the --circle option: $ db2twitter --circle /path/to/db2twitter.ini We recommend using db2twitter with cron. The following line in /etc/crontab will check for new db rows in your database every minute, build and send tweets accordingly:: # m h dom mon dow user command * * * * * db2twitter db2twitter /path/to/db2twitter.ini 0 * * * * db2twitter db2twitter --circle /path/to/db2twitter.ini db2twitter-0.6/requirements.txt000066400000000000000000000000561272055236100167410ustar00rootroot00000000000000Pillow>=3.2.0 sqlalchemy>=1.0.8 tweepy>=3.3.0 db2twitter-0.6/scripts/000077500000000000000000000000001272055236100151435ustar00rootroot00000000000000db2twitter-0.6/scripts/db2twitter000077500000000000000000000016331272055236100171660ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright © 2015-2016 Carl Chenet # 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 # 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 . # db2twitter startup '''db2twitter startup''' # standard libraries imports import sys # app libraries imports from db2twitter.main import Main if __name__ == '__main__': Main() sys.exit(0) db2twitter-0.6/setup.py000066400000000000000000000031371272055236100151720ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright © 2015 Carl Chenet # 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 # 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 # Setup for db2twitter '''Setup for db2twitter''' # 3rd party libraries imports from setuptools import setup CLASSIFIERS = [ 'Intended Audience :: End Users/Desktop', 'Environment :: Console', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 3.4' ] setup( name='db2twitter', version='0.6', license='GNU GPL v3', description='extract info from a database and send it to twitter', long_description='extract information from a database, write a tweet with them and send this tweet', classifiers=CLASSIFIERS, author='Carl Chenet', author_email='chaica@ohmytux.com', url='https://github.com/chaica/db2twitter', download_url='https://github.com/chaica/db2twitter', packages=['db2twitter'], scripts=['scripts/db2twitter'], install_requires=['tweepy', 'sqlalchemy','pillow'], ) db2twitter-0.6/tests.py000077500000000000000000000114121272055236100151720ustar00rootroot00000000000000#!/usr/bin/env python3.4 # -*- coding: utf-8 -*- # Copyright © 2015 Carl Chenet # 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 # 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 . # Unit tests for db2twitter '''Unit tests for db2twitter''' import datetime import sys import unittest from db2twitter.cliparse import CliParse from db2twitter.confparse import ConfParse from db2twitter.twbuild import TwBuild from db2twitter.timetosend import TimeToSend class TestDb2Twitter(unittest.TestCase): '''TestDb2Twitter class''' def test_getconfigfile(self): '''Test the CliParse class''' filepath = './tests.py' circling = False sys.argv[-1] = filepath clip = CliParse() self.assertEqual(clip.args, {'validpathtoconf': filepath, 'iscircling': circling}) def test_getconfigvars(self): '''Test the ConfParse class''' confp = ConfParse('tests/getconfigvars/db2twitter.ini') self.assertEqual(confp.confvalues, {'consumer_key': 'qPsJvBZlE2yatbsLM4dQL1r3m', 'consumer_secret': 'ixM1AvyzVJxjKmsQtmQzJ8pmB4vlhmYIO5v2XqEl0mqIdIwie5', 'access_token': '2370158707-m8eN2YcfVcKGfWmVLERDGMd1UPKHVPzAQHoP7qN', 'access_token_secret': 'tB74LfWy551sRTU49buGE6YXIukY74TmBK6JLECeOA5ti', 'tweet': '{} recrute un {} https://www.linuxjobs.fr/jobs/{}', 'hashtags': 'devops,linux,', 'upper_first_char': True, 'dbconnector': 'mysql+mysqlconnector', 'dbhost': 'localhost', 'database': 'linuxjobs', 'dbuser': 'linuxjobs', 'dbpass': 'xxxxxxxxx', 'dbtables': 'jobs,', 'ids': {}, 'rows': {'jobs': ['company_name','title','id']}, 'sqlitepath': '/var/lib/db2twitter/db2twitter.db', 'sqlfilter': {}, 'days': 'mon-fri,', 'hours': '0-11,14-17,', 'circlelasttwnb': '3', 'circletwbatchnb': '2', 'sqlfilter': {}, }) def test_gettwbuild(self): '''Test the TwBuild class''' conf= { 'tweet': '{} recrute un {} https://www.linuxjobs.fr/jobs/{}', 'hashtags': 'devops,linux,', 'upper_first_char': True,} twbuildp = TwBuild(conf, [['machin', 'devops', 1]]) self.assertEqual(twbuildp.readytotweet, ['Machin recrute un #devops https://www.linuxjobs.fr/jobs/1']) def test_timetosendhourstrue(self): '''Test the TimeToSend class - return True''' conf = { 'days': 'mon-sun,', #'hours': '0,1,2,3,4,5-7,8,9,10,11,12,13,14,15,16,17,18,19-23,',} 'hours': '0-23,',} tts = TimeToSend(conf) self.assertTrue(tts.sendthetweet) def test_timetosendhourslisttrue(self): '''Test the TimeToSend class with a list of hours- return True''' conf = { 'days': 'mon-sun,', 'hours': '0-23,',} tts = TimeToSend(conf) self.assertTrue(tts.sendthetweet) @unittest.skipIf(((datetime.datetime.now().weekday() == 6) and (datetime.datetime.now().hour == 0)), 'only executing if we are not sunday and not midnight') def test_timetosendhoursfalse(self): '''Test the TimeToSend class - return False''' conf = { 'days': 'sun,', 'hours': '0,',} tts = TimeToSend(conf) self.assertFalse(tts.sendthetweet) ################################################################ # # End of the unit tests # ################################################################ if __name__ == '__main__': unittest.main() db2twitter-0.6/tests/000077500000000000000000000000001272055236100146165ustar00rootroot00000000000000db2twitter-0.6/tests/getconfigvars/000077500000000000000000000000001272055236100174575ustar00rootroot00000000000000db2twitter-0.6/tests/getconfigvars/db2twitter.ini000066400000000000000000000013071272055236100222530ustar00rootroot00000000000000[twitter] consumer_key=qPsJvBZlE2yatbsLM4dQL1r3m consumer_secret=ixM1AvyzVJxjKmsQtmQzJ8pmB4vlhmYIO5v2XqEl0mqIdIwie5 access_token=2370158707-m8eN2YcfVcKGfWmVLERDGMd1UPKHVPzAQHoP7qN access_token_secret=tB74LfWy551sRTU49buGE6YXIukY74TmBK6JLECeOA5ti tweet={} recrute un {} https://www.linuxjobs.fr/jobs/{} hashtags=devops,linux, upper_first_char=true [database] ; use the following for PostgreSQL - you need mysql_connector_python dbconnector=mysql+mysqlconnector dbhost=localhost database=linuxjobs dbuser=linuxjobs dbpass=xxxxxxxxx dbtables=jobs, jobs_rows=company_name,title,id, [sqlite] sqlitepath=/var/lib/db2twitter/db2twitter.db [timer] days=mon-fri, hours=0-11,14-17, [circle] last_tweets=3 each_time=2