Skip to content
This repository has been archived by the owner on Apr 1, 2023. It is now read-only.

Commit

Permalink
Created folders structure for Packaging.
Browse files Browse the repository at this point in the history
  • Loading branch information
Sklyvan committed Oct 5, 2021
1 parent e76f928 commit 03e4cf1
Show file tree
Hide file tree
Showing 11 changed files with 31 additions and 25 deletions.
6 changes: 3 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ cython_debug/

# End of https://www.toptal.com/developers/gitignore/api/python,pycharm

/EspaiAulaFiles/
/JSON Files/
token.pickle
./res/EspaiAulaFiles/
./res/JSON Files/
./keys/token.pickle
UserPreferences.ini
13 changes: 7 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Esta aplicación no requiere que el usuario introduzca datos sensibles de inicio
### 1. Requisitos Previos

- [Python 3.8](https://www.python.org/downloads/) o versiones superiores.
(Hay una [versión del programa para Python 3.7](https://github.com/Sklyvan/ScrapingUPF/tree/oldpython) y versiones inferiores, pero no está en mantenimiento.)
(Hay una [versión del programa para Python 3.7](https://github.com/Sklyvan/ScrapingUPF/tree/oldpython) y versiones inferiores, pero no está en mantenimiento.)

- [Python Package Installer](https://github.com/pypa/pip) (PIP)

Expand All @@ -33,7 +33,7 @@ pip install -r Requirements.txt # Si PIP da error, hay que usar pip3.

### 3. Seleccionar las Preferencias

La selección de asignaturas se hace modificando el archivo [UserPreferences.ini](https://github.com/Sklyvan/ScrapingUPF/blob/main/UserPreferences.ini), no hay que modificar nada más del programa para su uso común. **Solo se puede añadir una línea de cada elemento, es decir, no se pueden añadir dos PlanEstudio.**
La selección de asignaturas se hace modificando el archivo [UserPreferences.ini](UserPreferences.ini), no hay que modificar nada más del programa para su uso común. **Solo se puede añadir una línea de cada elemento, es decir, no se pueden añadir dos PlanEstudio.**
<br>
Si hay alguna duda sobre cuál es su código de su Plan de Estudio, el Plan Docente o similares, se pueden conocer mediante: [Calendario y Horarios](https://gestioacademica.upf.edu/pds/consultaPublica/look%5Bconpub%5DInicioPubHora?entradaPublica=true&idiomaPais=ca.ES&centro=332&estudi=3324&planDocente=2021) <br>
<br>
Expand Down Expand Up @@ -76,6 +76,7 @@ Se pueden añadir las asignaturas mediante dos métodos:
#### Método Manual

Se pueden añadir tantas asignaturas como se quiera siempre que: <br>

1. Para toda asignatura se añada un grupo de teoría, uno de prácticas y uno de seminarios. En caso de que no haya uno de ellos, hay que poner un código inventado igualmente.

2. Los valores deben estar separados por comas y sin espacios.
Expand Down Expand Up @@ -125,20 +126,20 @@ Final=31/10/2021
Para ejecutar el programa simplemente hay que lanzar el archivo Main.py mediante Python:

```shell
python3 Main.py
python3 ./src/Main.py
```

Al iniciar el programa se va a abrir una ventana con nuestro buscador que nos va a pedir autorización para la API de Google Calendar.

![](RunningTheApplication.gif)
![](./res/RunningTheApplication.gif)

### 5. Información para Desarrolladores

El producto ha sido desarrollado bajo la licencia [GNU General Public License 3](https://www.gnu.org/licenses/gpl-3.0.en.html), por lo que se permite la modificación del mismo, su distribución y su uso privado, siempre que el código siga siendo completamente abierto y público tal y como obliga su licencia.

El archivo de credenciales de la API de Google Calendar es totalmente pública, de manera que se puede seguir usando la misma API para proyectos basados en esta aplicación. Si se hace un mal uso del archivo se regenerará la clave y pasará a ser privada.
El archivo de credenciales de la API de Google Calendar es totalmente pública, de manera que se puede seguir usando la misma API para proyectos basados en esta

En caso de que se quiera crear una interfaz gráfica para la aplicación se pueden usar herramientas como [PyQt5](https://pypi.org/project/PyQt5/) que solo van a necesitar editar el archivo de [UserPreferences.ini](https://github.com/Sklyvan/ScrapingUPF/blob/main/UserPreferences.ini).
En caso de que se quiera crear una interfaz gráfica para la aplicación se pueden usar herramientas como [PyQt5](https://pypi.org/project/PyQt5/) que solo van a necesitar editar el archivo de [UserPreferences.ini](UserPreferences.ini).

### Contacto

Expand Down
2 changes: 1 addition & 1 deletion UserPreferences.ini
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Asignaturas=False
GruposAsignaturas=False
GruposPracticas=False
GruposSeminarios=False
EspaiAulaFilePath=./EspaiAulaFiles/Gestió de Grups i Aules.html
EspaiAulaFilePath=../res/EspaiAulaFiles/Gestió de Grups i Aules.html

[FECHAS]
Inicio=01/10/2021
Expand Down
File renamed without changes.
File renamed without changes
File renamed without changes.
9 changes: 5 additions & 4 deletions GoogleCalendar.py → src/GoogleCalendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,24 @@
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
tokenPath, credsPath = '../keys/token.pickle', '../keys/credentials.json'

class Calendar:
def __init__(self):
self.Service = None
SCOPES = ['https://www.googleapis.com/auth/calendar']
CREDS = None # Google API Function, generating the current Auth without opening the browser, so cool :).
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
if os.path.exists(tokenPath):
with open(tokenPath, 'rb') as token:
CREDS = pickle.load(token)
if not CREDS or not CREDS.valid:
if CREDS and CREDS.expired and CREDS.refresh_token:
CREDS.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
credsPath, SCOPES)
CREDS = flow.run_local_server(port=0)
with open('token.pickle', 'wb') as token:
with open(tokenPath, 'wb') as token:
pickle.dump(CREDS, token)

service = build('calendar', 'v3', credentials=CREDS)
Expand Down
7 changes: 5 additions & 2 deletions Imports.py → src/Imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@
from GoogleCalendar import Calendar

# # # Python Required Constants # # #
CONFIG_FILE = "UserPreferences.ini"
CONFIG_FILE = "../UserPreferences.ini"
URL = 'https://gestioacademica.upf.edu/pds/consultaPublica/look%5Bconpub%5DInicioPubHora?entradaPublica=true' # URL principal para establecer una conexión y obtener una sesión.
URL_RND = 'https://gestioacademica.upf.edu/pds/consultaPublica/look[conpub]MostrarPubHora' # Con esta URL obtenemos un número "aleatorio" que nos permite simular la conexión de un usuario consultando el horario.
URL_JSON = 'https://gestioacademica.upf.edu/pds/consultaPublica/[Ajax]selecionarRangoHorarios' # Con esta URL obtenermos el archivo JSON que contiene el horario.
TIMEZONE = get_localzone().key

GOOGLE_CALENDAR_API_MAX_COLORS = 11
GOOGLE_CALENDAR_API_MAX_COLORS = 11
DECODE_HTML_FILE = 'latin-1'
DELETE_EVENTS_SYMBOL = 'R'
PYTHON_VERSION = {'Major': 3, 'Minor': 8}
9 changes: 5 additions & 4 deletions Main.py → src/Main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def extractRND(fromSoup):
float(RND)
except ValueError:
sys.exit("Something went pretty wrong while searching the RND value. This is probably a code bug, so contact Sklyvan.")
return -1
return False
else:
return RND

Expand Down Expand Up @@ -45,12 +45,13 @@ def downloadContent(fromData, fromHeaders=''):
return jsonFile

if __name__ == '__main__':
if sys.version_info.major < 3 or (sys.version_info.major >= 3 and sys.version_info.minor < 8): # Python 3.8 or bigger version is needed for Walrus Operator.
# Python 3.8 or bigger version is needed for Walrus Operator.
if sys.version_info.major < PYTHON_VERSION['Major'] or (sys.version_info.major >= PYTHON_VERSION['Major'] and sys.version_info.minor < PYTHON_VERSION['Minor']):
sys.exit(f"You're using Python {sys.version_info.major}.{sys.version_info.minor}, required version is 3.8 or bigger.")
userPreferences = getUserPreferences(CONFIG_FILE)

if isUsingEspaiAulaFilePath(userPreferences):
espaiAulaFile = HTML_LocalFile(getEspaiAulaFilePath(userPreferences), 'latin-1')
espaiAulaFile = HTML_LocalFile(getEspaiAulaFilePath(userPreferences), DECODE_HTML_FILE)
fromGroups, fromSubjects, userSubjectsGroups, pGroups, sGroups = extractSubjectsPreferencesFromFile(espaiAulaFile)
else:
fromGroups, fromSubjects, userSubjectsGroups, pGroups, sGroups = extractSubjectsPreferences(userPreferences)
Expand All @@ -73,7 +74,7 @@ def downloadContent(fromData, fromHeaders=''):

MyCalendar = Calendar()

if sys.argv[len(sys.argv)-1] == 'R':
if sys.argv[len(sys.argv)-1] == DELETE_EVENTS_SYMBOL:
descriptions = list(map(lambda x: x.getDescription(),subjectsBlocks))
events = MyCalendar.getEvents()
for event in events:
Expand Down
10 changes: 5 additions & 5 deletions NetworkRequests.py → src/NetworkRequests.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,13 @@ def POST(self, dataString): # Hace el POST con la nueva string de datos y crea e
def getJSON(self, exportFile=False, nameID=None): # Como al final nos devuelve un horario, lo extraemos en formato JSON ya que es mucho más cómo de trabajar.
self.jSON = json.loads(self.HTML_Page.text)
if exportFile:
if not os.path.isdir('./JSON Files'): os.mkdir('./JSON Files')
if not os.path.isdir('../res/JSON Files'): os.mkdir('../res/JSON Files')
if not nameID:
open('./JSON Files/Data.json', 'w').write(str(self.jSON))
self.jsonDir = './JSON Files/Data.json'
open('../res/JSON Files/Data.json', 'w').write(str(self.jSON))
self.jsonDir = '../res/JSON Files/Data.json'
else:
open(f'./JSON Files/Data{nameID}.json', 'w').write(str(self.jSON))
self.jsonDir = f'./JSON Files/Data{nameID}.json'
open(f'../res/JSON Files/Data{nameID}.json', 'w').write(str(self.jSON))
self.jsonDir = f'../res/JSON Files/Data{nameID}.json'
return self.jSON

class HTML_LocalFile:
Expand Down
File renamed without changes.

0 comments on commit 03e4cf1

Please sign in to comment.