Skip to content
This repository was archived by the owner on Jul 1, 2024. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions DOCKER.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Per fer servir mailtoticket + fetchmail a Docker caldrà

####0.- Crear una carpeta "conf" buida
Necessitarem posar les configuracions a passar al docker en una única carpeta

####1.- Tenir un fitxer docker/.fetchmailrc correcte
Tenim una plantilla per generar-lo, bàsicament es canviar el username i password del compte a llegir.
El deixarem a la carpeta "conf" que acabem de crear

####2.- Fer el settings_default.py
Es pot partir copiar del settings_sample.py. El copiarem també a "conf"

####3.- Fer el build

```
docker build -t mailtoticket .
```

####4.- Executar, passant on ha d'escriure els logs i on tenim la carpeta conf

Poso un example amb windows. La idea es mapejar un path local amb el "/log" i el "conf"

```
docker run -it -v "d:\usuaris\jaumem\workspace-mailtoticket\mailtoticket\log":/log -v "d:\usuaris\jaumem\workspace-mailtoticket\mailtoticket\conf":/conf mailtoticket
```
26 changes: 26 additions & 0 deletions Dockerfile-fetchgmail
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
FROM python:3.7.5-alpine3.10
# El /log es per escriure els logs i el /conf es per posar el fetchmailrc (sense el punt) i el settings_default.py
VOLUME /log
VOLUME /conf
ARG USER_ID=1000
ARG GROUP_ID=1000
RUN addgroup --gid "$GROUP_ID" "mailtoticket"
RUN adduser --disabled-password --gecos "" --ingroup "mailtoticket" --no-create-home --home /mailtoticket --uid "$USER_ID" mailtoticket
RUN apk add openldap-dev build-base
# Posem el timezone correcte pels logs
RUN apk add tzdata && cp /usr/share/zoneinfo/Europe/Madrid /etc/localtime && echo "Europe/Madrid" >/etc/timezone && apk del tzdata
# Instalem dependencies (a part de la resta de programa, perque aixi fa cache)
WORKDIR /mailtoticket
RUN chown mailtoticket:mailtoticket /mailtoticket/
COPY requirements.txt /mailtoticket/
RUN pip install -r requirements.txt
# Copiem els scripts de fetchgmail
COPY fetchgmail /mailtoticket/fetchgmail/
# Copiem el mailtoticket
COPY filtres /mailtoticket/filtres/
COPY soa /mailtoticket/soa/
COPY *.py /mailtoticket/
# Aixo es perque trobi el settings on l'hem deixat
ENV PYTHONPATH=/conf
USER mailtoticket
CMD ["/bin/sh","/mailtoticket/fetchgmail/fetchgmail.sh"]
42 changes: 42 additions & 0 deletions fetchgmail/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
## Fetchgmail

Codi basat en el que hi ha aqui

https://github.com/google/gmail-oauth2-tools

i seguint aquestes explicacions

https://github.com/google/gmail-oauth2-tools/wiki/OAuth2DotPyRunThrough

# Preparació

Primer de tot hem de donar d'alta la nostra aplicació tal i com explica aqui

https://github.com/google/gmail-oauth2-tools/wiki/OAuth2DotPyRunThrough

Necessitarem un client_id i un client_secret que ens generarà Google. Amb aquests valors obtindrem un refresh token. Per fer aixo, executarem via docker el següent:

```
python oauth2.py --user=nom.usuari@upc.edu --client_id=xxxxxx.apps.googleusercontent.com --client_secret=yyyyy --generate_oauth2_token
```

Del resultat d'aquesta ordre, nomes necessitem el refresh token, que ens apuntarem al fitxer settings_fetchgmail.py, substituint els valors de user, client_id i refresh_token pels correctes.

```
user="nom.usuari@upc.edu"
client_id="xxxxxx"
client_secret="yyyyyy"
# El refresh token s'obté executant oauth2.sh
refresh_token="zzzzzzzz"
mailtoticket=["python","/mailtoticket/mailtoticket.py"]
```

# Proves

Ara ja tenim un settings.py amb tot el necessari per poder accedir al compte. Llavors simplement executem

```
python3 fetchgmail
```

I aixo es connectarà al compte i executarà el mailtoticket.sh passant cada mail no llegit per l'entrada estàndard
54 changes: 54 additions & 0 deletions fetchgmail/fetchgmail.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import imaplib
import oauth2
import settings_fetchgmail as settings
import os
import subprocess
import pickle
import datetime

MAIL_TMP = "/tmp/mail"


def escriure_mail(mail):
with open(MAIL_TMP, "wb") as f:
f.write(mail)
f.flush()


def refresca_i_guarda_token():
creds = oauth2.RefreshToken(
settings.client_id, settings.client_secret, settings.refresh_token)
durada = datetime.timedelta(seconds=creds["expires_in"])
creds["expiration_time"] = datetime.datetime.now() + durada
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return creds


def llegir_token():
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if creds["expiration_time"] > datetime.datetime.now():
return creds
return refresca_i_guarda_token()


creds = llegir_token()
access_token = creds['access_token']
auth_string = oauth2.GenerateOAuth2String(
settings.user, access_token, base64_encode=False)
imap_conn = imaplib.IMAP4_SSL('imap.gmail.com')
imap_conn.authenticate('XOAUTH2', lambda x: auth_string)
imap_conn.select('INBOX')

resp, items = imap_conn.uid('SEARCH', None, '(UNSEEN)')
items = items[0].split() # getting the mails id

for emailid in items:
resp, data = imap_conn.uid('FETCH', emailid, "(RFC822)")
escriure_mail(data[0][1])
with open(MAIL_TMP, "rb") as f:
r = subprocess.run(settings.mailtoticket, stdin=f)
if r.returncode > 0:
imap_conn.uid('STORE', emailid, '-FLAGS', r'(\Seen)')
2 changes: 2 additions & 0 deletions fetchgmail/fetchgmail.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/sh
while true; do python /mailtoticket/fetchgmail/fetchgmail.py; sleep 60; done
Loading