<repo_name>BenteaB/PlanBy<file_sep>/README.md
# PlanBy
Bets app ever is processing....


No fiti atenti ce baban o sa fie toata chestia asta 
<file_sep>/Calendar/dorin1.py
from flask import Flask, render_template, request, jsonify
import requests
from bs4 import BeautifulSoup
from flask_cors import CORS
import json

app = Flask(__name__)
CORS(app) # cross origin

@app.route("/site.html",methods=['GET','POST','PUT'])
def get_orar():


    data = request.json
    x = json.loads(data)
    #print(x["grupa"]) #doar dictionar ai voie in jscript

    url = "https://www.cs.ubbcluj.ro/files/orar/2020-1/tabelar/I1.html"

    r = requests.get(url)
    soup = BeautifulSoup(r.text, "html.parser")

    table_all = soup.find_all("table")

    citit = x["grupa"] #citit = input("Numarul grupei(ex: 211/1): ")

    gr, subgr = citit.split("/")
    gr = int(gr)-211
    subgr = int(subgr)

    gr = 0
    subgr = 1

    table = table_all[gr]

    k = 0
    lista = {}
    rows = table.find_all("tr")
    for row in rows[1:]:
        zi = row.find_all("td")[0].text.strip()
        ora = row.find_all("td")[1].text.strip()
        frecv = row.find_all("td")[2].text.strip()
        form = row.find_all("td")[4].text.strip()
        tip = row.find_all("td")[5].text.strip()
        disc = row.find_all("td")[6].text.strip()
        prof = row.find_all("td")[7].text.strip()

        if frecv == "":
            frecv = 0
        elif frecv == "sapt. 1":
            frecv = 1
        elif frecv == "sapt. 2":
            frecv = 2

        if form[-2:] == "/1":
            form = 1
        elif form[-2:] == "/2":
            form = 2
        else:
            form = subgr

        #prof = prof.split(" ", 1)[1]

        if form == subgr:
             # nu am mai pus formatia
            lista[k] = {"zi":zi,"ora":ora,"frecv":frecv,"tip":tip,"disc":disc,"prof":prof}
            k += 1

    #for el in lista:
        #print(el)
    return lista

app.run(debug = True)<file_sep>/prostie.py
import urllib

url = ['http://google.com','http://bing.com']

for i in url:
    html = urllib.urlopen(i).read()
    print(html.encode('utf-8')) 
<file_sep>/Errors.py
class PlatformError(Exception):
  pass

class HourError(Exception):
  pass<file_sep>/Calendar/EmailReaderToPopUp.py
import email
import imaplib
import re
from flask import Flask, render_template, request, jsonify
import requests
from flask_cors import CORS
import json
from datetime import date

from Errors import PlatformError, HourError


def get_body(msg):
  if msg.is_multipart():
    return get_body(msg.get_payload(0))
  else:
    return msg.get_payload(None, True)

def ConvertMessageToString(raw):
  string_message = str(get_body(raw))
  string_message = string_message.replace("\\r", "")
  string_message = string_message.replace("\\n", "")
  return string_message

def FindPlatform(message):
  platforms = {"Discord": ["discord"], "Zoom": ["zoom"], "Microsoft Teams": ["ms teams", "msteams", "teams", "microfost teams"], "Google meet":["google meet", "meet"], "Messenger": ["messenger", "facebook"]}

  temp = message.lower()
  for elem in platforms:
    for platform in platforms[elem]:
      if platform in temp:  
        return elem
  raise PlatformError("Nu am gasit nici o platforma!\n")

def FindDay(message):
  days = []
  months = []
  separators = ["/", "."]
  for i in range (1, 31):
    days.append(str(i))
  for i in range(1, 13):
    months.append(str(i))
  for i in reversed(days):
    day = i
    occurrences = [m.start() for m in re.finditer(day, message)]
    for j in occurrences:
      try:
        month = int(message[j + 3 : j + 5])
      except ValueError:
        try:
          month = int(message[j + 3])
        except ValueError:
          continue
        except IndexError:
          break
      except IndexError:
        try:
          month = int(message[j + 3])
        except ValueError:
          continue
        except IndexError:
          break
        print(day)
      if (str(month) in months) and (message[j + 2] in separators):
        print(day, str(month))
        return day + " " + str(month)
  raise HourError("Nu am gasit nici o data calendaristica in email!\n")

def FindHour(message):
  hours = []
  separator = [" ", ":", ";", "-"]
  rez = ""
  for i in range(0, 25):
    i = str(i)
    if len(i) < 2:
      i = "0" + i
    hours.append(i)

  for i in range(0, 10):
    hours.append(str(i))

  for i in hours:
    hour = i
    occurrences = [m.start() for m in re.finditer(hour, message)]
    for j in occurrences:
      try:
        minutes = int(message[j + 3 : j + 5])
      except ValueError:
        continue
      else:
        if minutes % 10 == 0 and minutes >= 0 and minutes <= 50:
          if len(hour) == 1:
            j -= 1
          if message[j + 3 : j + 5].isdigit() and (message[j + 2] in separator):
            return hour + ":" + message[j + 3 : j + 5]
  raise HourError("Nu am gasit nici o ora in email!\n")



def Logare():
  user = "<EMAIL>"
  password = "<PASSWORD>"
  imap_url = "imap.gmail.com"

  M = imaplib.IMAP4_SSL(imap_url)
  M.login(user, password)
  M.select('INBOX')
  M.select()
  return M

def SearchPlatformAndHour(Account):
  typ, data = Account.search(None, 'unseen')
  Platform = None
  Hour = None
  for num in reversed(data[0].split()):
    typ, data = Account.fetch(num, '(RFC822)')
    raw = email.message_from_bytes(data[0][1])
    TheMessage = ConvertMessageToString(raw)
    try:
      Platform = FindPlatform(TheMessage)
    except PlatformError:
      continue
    try:
      Hour = FindHour(TheMessage)
    except HourError:
      continue
    try:
      DataCalendaristica = FindDay(TheMessage)
    except HourError as re:
      print(re)
    return [Platform, Hour, DataCalendaristica]
    raise Exception("Nu am putut gasi un meeting!\n")


def Delogare(Account):
  Account.close()
  Account.logout()


app = Flask(__name__)
CORS(app) # cross origin

@app.route("/index.html", methods=['GET', 'POST', 'PUT'])
def run():

  data = request.json
  x = json.loads(data)
  k = 0
  while True:
    cont = Logare()
    k += 1
    print("Cautarea nr: " + str(k))
    try:
      Platforma, Hour, DataCalendaristica = SearchPlatformAndHour(cont)
      dictionar = {}
      dictionar["platforma"] = Platforma
      dictionar["ora"] = Hour
      lista = DataCalendaristica.split()
      dictionar["zi"] = lista[0]
      dictionar["luna"] = lista[1]
      Delogare(cont)
      return dictionar
      #meetings -> contine toate meetingurile din mailurile necitite
    except Exception as ex:
      continue
    Delogare(cont)

app.run(debug = True)<file_sep>/Calendar/script.js
const date = new Date();

const renderCalendar = () => {
  date.setDate(1);

  const monthDays = document.querySelector(".days");

  const lastDay = new Date(
    date.getFullYear(),
    date.getMonth() + 1,
    0
  ).getDate();

  const prevLastDay = new Date(
    date.getFullYear(),
    date.getMonth(),
    0
  ).getDate();

  const firstDayIndex = date.getDay();

  const lastDayIndex = new Date(
    date.getFullYear(),
    date.getMonth() + 1,
    0
  ).getDay();

  const nextDays = 7 - lastDayIndex - 1;

  const months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
  ];

  document.querySelector(".date h1").innerHTML = months[date.getMonth()];

  document.querySelector(".date p").innerHTML = new Date().toDateString();

  let days = "";

  for (let x = firstDayIndex; x > 0; x--) {
    days += `<div class="prev-date">${prevLastDay - x + 1}</div>`;
  }

  for (let i = 1; i <= lastDay; i++) {
    if (
      i === new Date().getDate() &&
      date.getMonth() === new Date().getMonth()
    ) {
      days += `<div class="today" id = ${i}>${i}</div>`;
    } else {
      days += `<div class = day id = ${i}>${i}</div>`;
    }
  }

  for (let j = 1; j <= nextDays; j++) {
    days += `<div class="next-date">${j}</div>`;
    monthDays.innerHTML = days;
  }
};

document.querySelector(".prev").addEventListener("click", () => {
  date.setMonth(date.getMonth() - 1);
  renderCalendar();
});

document.querySelector(".next").addEventListener("click", () => {
  date.setMonth(date.getMonth() + 1);
  renderCalendar();
});

var events_plan = Array(32);
for (i = 1; i <= 31; ++i){
  events_plan[i] = "";
}

let eventsForDate = ""
let lastDayClicked = -1;
let actualDayClicked;


document.querySelector(".days").addEventListener("click", () => {
  if (lastDayClicked != -1 && lastDayClicked != new Date().getDate() && document.getElementById(lastDayClicked).style.background != "rgb(77, 166, 255)"){
    document.getElementById(lastDayClicked).style.background = "#222227";
  }
  if (window.event.target.className === "days"){
    return;
  }
  if (window.event.target.className === "today") {
    lastDayClicked = window.event.target.textContent;
    document.querySelector(".listOfEvents").innerHTML = events_plan[lastDayClicked];
    return;
  }
  actualDayClicked = window.event.target.textContent
  if (lastDayClicked == -1){
    window.event.target.style.background = "#777";
  }
  else
    if(document.getElementById(actualDayClicked).style.background != "rgb(77, 166, 255)"){
      window.event.target.style.background = "#777";
    }
    console.log(actualDayClicked);
  document.querySelector(".listOfEvents").innerHTML = events_plan[actualDayClicked];
  lastDayClicked = window.event.target.textContent;
})

document.getElementById("btn").addEventListener("click", () => {
  if (document.getElementById("time").value === "" || document.getElementById("name").value === "" || lastDayClicked === -1) {
    return;
  }
  if (lastDayClicked != new Date().getDate()){
  document.getElementById(lastDayClicked).style.background = "#4da6ff"
  }
  console.log(events_plan[lastDayClicked]);
  events_plan[lastDayClicked] += document.getElementById("name").value + ": " + document.getElementById("time").value + "<br>";
  document.querySelector(".listOfEvents").innerHTML = events_plan[lastDayClicked];
})

document.getElementById("mail").addEventListener("click", () => {
   

  if (lastDayClicked != -1 && lastDayClicked != new Date().getDate() && document.getElementById(lastDayClicked).style.background != "rgb(77, 166, 255)"){
    document.getElementById(lastDayClicked).style.background = "#222227";
  }

    if (lastDayClicked != -1 && document.getElementById(lastDayClicked).style.background != "rgb(77, 166, 255"){
      document.getElementById(last) = "#777";
    }
  console.log(actualDayClicked);
  document.querySelector(".listOfEvents").innerHTML = events_plan[actualDayClicked];
  

  if (lastDayClicked != new Date().getDate()){
  document.getElementById(actualDayClicked).style.background = "#4da6ff"
  }
  events_plan[actualDayClicked] += document.getElementById("name").value + ": " + document.getElementById("time").value + "<br>";
  document.querySelector(".listOfEvents").innerHTML = events_plan[actualDayClicked];
  document.getElementById("mail").style.visibility = "hidden";
  
})

fetch("http://localhost:5000/index.html", {method: 'POST', headers: {'content-type': 'application/json'}, body: JSON.stringify('{"grupa":"211/1"}')}).then( response => {
return response.json();
} ).then( res => {
  console.log(res);
  document.getElementById("mail").style.visibility = "visible";
  document.getElementById("name").value = res["platforma"]
  document.getElementById("time").value = res["ora"]
  actualDayClicked = res["zi"];
  console.log(actualDayClicked)
  

} )

var group;
document.getElementById("btnGrupa").addEventListener("click", () => {
    group = document.getElementById("grupa").value;
    functie()
})
const functie = () => {
fetch("http://localhost:5000/site.html", {method: 'POST', headers: {'content-type': 'application/json'}, body: JSON.stringify( JSON.stringify({"grupa":group}) ) }).then( response => {
return response.json();
} ).then( res => {
  console.log(res);
  for (curs in res) {
    if (curs["zi"] === "Luni"){
      for (var i = 2; i <= 30; ++i) {
        events_plan[i] += curs["disc"] + " " + curs["ora"] + " " + curs["prof"] + "<br>" 
        document.querySelector(".listOfEvents").innerHTML = events_plan[lastDayClicked];
      }
    }
  }

} )
}

    //res -> ce iese din python

//console.log(window.event.target.textContent)
//document.querySelector(".listOfEvents").innerHTML = events_name[window.event.target.textContent] + ":" + events_hours[window.event.target.textContent]
//document.querySelector(".Events").style.visibility = "visible"
//events_name[window.event.target.textContent][events_name.length]
//events_hours[window.event.target.textContent][events_hours.length]
renderCalendar();

