favEng / Uludağ Ders-Özel

// ==UserScript==
// @name         Uludağ Ders-Özel
// @namespace    -
// @version      0.2
// @description  İyi bi araç.
// @author       -
// @match        https://ogrotomasyon.uludag.edu.tr/*
// @grant        none
// @require http://code.jquery.com/jquery-1.12.4.min.js
// @license      MIT
// @grant       GM.xmlhttpRequest
// ==/UserScript==

(function () {
  'use strict';

  window.final = [];
  //$.ajaxSetup({async:false});
  $('body').append('<dialog id="window"><div style="display:  flex;"></div><button id="calc" onclick="calc();">Hesapla</button><button id="freeDay" style="float: right;" onclick="haveAFreeDay();">Boş Günüm Olsun</button><button id="freeSleep" style="float: right;" onclick="haveASleepyDay();">İlk 2 Saatler Boş Olsun</button><p style="white-space: pre-wrap" id="info"></p><button style="float: right;" onclick="$(\'#window\')[0].close();$(\'#window table\').remove();$(\'#select\').remove();">Kapat</button></dialog>');
  setInterval(function () {
    if ($('body').html().indexOf("DERS ALMAM")) {
      if (!~$('body').html().indexOf("Çalıştır")) {
        jQuery('#formIntibak > table > tbody > tr:nth-child(1) > td > table > tbody > tr:nth-child(2) > td > table > tbody > tr:nth-child(2) > td:nth-child(2)').html("<input class='button' onclick='schedMaker()' type='button' value='Çalıştır'>");
      }
    }
  }, 2000);

  window.schedMaker = function () {
    jQuery('#calc').show();
    jQuery('#info').hide();
    jQuery('#freeDay').hide();
    jQuery('#freeSleep').hide();
    var courses = [];
    localStorage.setItem("courses", "");
    jQuery('iframe').first().contents().find('table tr').each(function () {
      if (!jQuery(jQuery(this).find('td').get(1)).find('img').length || jQuery(this).css("background-color") == "rgb(234, 107, 57)") {
        if (localStorage.getItem("courses") !== "")
          courses = JSON.parse(localStorage.getItem("courses"));
        courses.push({
          name: jQuery.trim(jQuery(jQuery(this).find('td').get(4)).text()),
          term: jQuery.trim(jQuery(jQuery(this).find('td').get(2)).text()),
          onWeek: []
        });
        localStorage.setItem("courses", JSON.stringify(courses));
      }
    });
    var uniqueItems = Array.from(new Set(JSON.parse(localStorage.getItem("courses"))));
    uniqueItems = uniqueItems.filter((uniqueItems, index, self) =>
      index === self.findIndex((t) => (
        t.name === uniqueItems.name
      ))
    )
    localStorage.setItem("courses", JSON.stringify(uniqueItems));
    //done getting names
    jQuery('iframe').first().contents().find('table tr').each(function () {
      if (!jQuery(jQuery(this).find('td').get(1)).find('img').length || jQuery(this).css("background-color") == "rgb(234, 107, 57)") {
        var code = jQuery.trim(jQuery(jQuery(this).find('td').get(3)).text());
        var name = jQuery.trim(jQuery(jQuery(this).find('td').get(4)).text());
        $.get("https://ogrotomasyon.uludag.edu.tr/dersalma/DersIcerikIframe.aspx?Id=" + jQuery(jQuery(this).find('td').get(4)).find('a').first().attr('href').split('_').pop(), function (data) {
          justDo(data, code, name)
        });
      }
    });
    $('#window div').prepend('<table style="font-size: 9px;" border="1"><thead><tr><td></td><td>Ders</td><td>Dönem</td></tr></thead></table>');
    courses = JSON.parse(localStorage.getItem("courses"));
    $.each(courses, function (index, value) {
      $('#window').find('table').append('<tr><td><input class="radiobutton" type="checkbox" value="' + index + '"></td><td>' + value.name + '</td><td>' + value.term + '</td></tr>');
    });
    $('#window')[0].showModal();
  }

  function justDo(html, code, name) {
    var dom_nodes = $($.parseHTML(html));
    var onWeek = [];
    var test = [];
    fill2DimensionsArray(onWeek, 7, 10);
    fill2DimensionsArray(test, 7, 10);
    dom_nodes.find('#tblstr > table > tbody > tr:nth-child(4) > td > table > tbody > tr:nth-child(2) > td > table').find('tr').each(function () {
      if (jQuery(this).find('td').length == 5) {
        if (jQuery(jQuery(this).find('td').get(1)).text().search("Gün") == -1) {
          if (jQuery(jQuery(this).find('td').get(1)).text().search("Pazartesi") == 1)
            onWeek[0][jQuery.trim(jQuery(jQuery(this).find('td').get(2)).text()) - 2] = name + " (" + jQuery.trim(jQuery(jQuery(this).find('td').get(4)).text()) + ")";
          if (jQuery(jQuery(this).find('td').get(1)).text().search("Salı") == 1)
            onWeek[1][jQuery.trim(jQuery(jQuery(this).find('td').get(2)).text()) - 2] = name + " (" + jQuery.trim(jQuery(jQuery(this).find('td').get(4)).text()) + ")";
          if (jQuery(jQuery(this).find('td').get(1)).text().search("Çarşamba") == 1)
            onWeek[2][jQuery.trim(jQuery(jQuery(this).find('td').get(2)).text()) - 2] = name + " (" + jQuery.trim(jQuery(jQuery(this).find('td').get(4)).text()) + ")";
          if (jQuery(jQuery(this).find('td').get(1)).text().search("Perşembe") == 1)
            onWeek[3][jQuery.trim(jQuery(jQuery(this).find('td').get(2)).text()) - 2] = name + " (" + jQuery.trim(jQuery(jQuery(this).find('td').get(4)).text()) + ")";
          if (jQuery(jQuery(this).find('td').get(1)).text().search("Cuma") == 1 && jQuery(jQuery(this).find('td').get(1)).text().search("Cumartesi") != 1)
            onWeek[4][jQuery.trim(jQuery(jQuery(this).find('td').get(2)).text()) - 2] = name + " (" + jQuery.trim(jQuery(jQuery(this).find('td').get(4)).text()) + ")";
          if (jQuery(jQuery(this).find('td').get(1)).text().search("Cumartesi") == 1)
            onWeek[5][jQuery.trim(jQuery(jQuery(this).find('td').get(2)).text()) - 2] = name + " (" + jQuery.trim(jQuery(jQuery(this).find('td').get(4)).text()) + ")";
          if (jQuery(jQuery(this).find('td').get(1)).text().search("Pazar") == 1 && jQuery(jQuery(this).find('td').get(1)).text().search("Pazartesi") != 1)
            onWeek[6][jQuery.trim(jQuery(jQuery(this).find('td').get(2)).text()) - 2] = name + " (" + jQuery.trim(jQuery(jQuery(this).find('td').get(4)).text()) + ")";
        }
      }
    });
    if (JSON.stringify(test) == JSON.stringify(onWeek))
      return false;
    var courses = [];
    courses = JSON.parse(localStorage.getItem("courses"));
    var index = courses.findIndex(p => p.name == name)
    courses[index]["onWeek"].push({
      [code]: onWeek
    });
    localStorage.setItem("courses", JSON.stringify(courses));

  }

  function fill2DimensionsArray(arr, rows, columns) {
    for (var i = 0; i < rows; i++) {
      arr.push([0])
      for (var j = 0; j < columns; j++) {
        arr[i][j] = 0;
      }
    }
  }
  window.calc = function () {
    if (jQuery.active > 0) {
      setTimeout(calc, 1000);
      console.log("bekle");
      return;
    }
    window.top.jQuery("table:eq(1)").width(1200);
    var chosen = [];
    jQuery('#window').find('table tr').each(function () {
      if (jQuery(this).find('input').is(':checked'))
        chosen.push(jQuery(this).find('input').val());
    });
    localStorage.setItem("chosen", JSON.stringify(chosen));
    jQuery('#window table').html('<colgroup><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"></colgroup><tr><th>Ders Saati</th><th>08:50 - 09:35</th><th>09:40 - 10:25</th><th>10:30 - 11:15</th><th>11:15 - 12:00</th><th>12:05 - 12:50</th><th>13:00 - 13:45</th><th>13:50 - 14:35</th><th>14:40 - 15:25</th><th>15:30 - 16:15</th><th>16:15 - 17:00</th></tr>')
    var parts = [];
    var parts2 = [];
    var parts3 = [];
    var courses = [];
    courses = JSON.parse(localStorage.getItem("courses"));
    for (var i = 0, len = chosen.length; i < len; i++) {
      parts.push(courses[chosen[i]].onWeek);
      parts2.push(courses[chosen[i]].name);
    }
    combine(parts, parts2);
    jQuery('#window div').append('<select style="width:  75px;" onchange="changeSelected()" id="select" size="5"></select>');
    var frag = document.createDocumentFragment();
    for (i = 1; i < final.length + 1; i++) {
      var option = document.createElement("option");
      option.text = i;
      option.value = i;
      frag.appendChild(option);
    }
    document.querySelector("#select").appendChild(frag);
    if ($('#select').children('option').length > 0) {
      $("#select").val($("#select option:first").val());
      $('#select').trigger('change');
    }
    else {
      alert("Bu dersler aynı anda alınamıyor.");
      jQuery('#window button').last().click();
    }
    jQuery('#calc').hide();
    jQuery('#info').show();
    jQuery('#freeDay').show();
    //jQuery('#freeSleep').show();
  }
  window.changeSelected = function () {
    var selected = document.querySelector("#select").options[document.querySelector("#select").selectedIndex].value;
    var days = ['Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi', 'Pazar'];
    var tbody = $('#window table');
    tbody.html('<colgroup><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"><col style="width: 80px"></colgroup><tr><th>Ders Saati</th><th>08:50 - 09:35</th><th>09:40 - 10:25</th><th>10:30 - 11:15</th><th>11:15 - 12:00</th><th>12:05 - 12:50</th><th>13:00 - 13:45</th><th>13:50 - 14:35</th><th>14:40 - 15:25</th><th>15:30 - 16:15</th><th>16:15 - 17:00</th></tr>')
    for (var i = 0; i < 7; i++) {
      var tr = "<tr>";
      tr += '<td>' + days[i] + '</td>';
      for (var j = 0; j < 10; j++) {
        if (final[selected - 1].onWeek[i][j] == 0)
          tr += '<td></td>';
        else
          tr += '<td>' + final[selected - 1].onWeek[i][j] + '</td>';
      }
      document.querySelector("#window table").innerHTML = document.querySelector("#window table").innerHTML + tr;
    }
    console.log(final[selected - 1]);
    $('#info').text("Seçenek:" + selected + "\n" + final[selected - 1].info.join("\n"));
  }
  window.haveAFreeDay = function () {
    $('#select').remove();
    jQuery('#window div').append('<select style="width:  75px;" onchange="changeSelected()" id="select" size="5"></select>');
    var frag = document.createDocumentFragment();
    for (var i = 1; i < final.length + 1; i++) {
      if (final[i - 1].freeDay) {
        var option = document.createElement("option");
        option.text = i;
        option.value = i;
        frag.appendChild(option);
      }
    }
    document.querySelector("#select").appendChild(frag);
    if ($('#select').children('option').length > 0) {
      $("#select").val($("#select option:first").val());
      $('#select').trigger('change');
    }
    else {
      alert("Bu dersler aynı anda alınamıyor.");
      jQuery('#window button').last().click();
    }
  }
  window.haveASleepyDay = function () {
    $('#select').remove();
    jQuery('#window div').append('<select style="width:  75px;" onchange="changeSelected()" id="select" size="5"></select>');
    var frag = document.createDocumentFragment();
    for (var i = 1; i < final.length + 1; i++) {
      if (final[i - 1].freeSleep) {
        var option = document.createElement("option");
        option.text = i;
        option.value = i;
        frag.appendChild(option);
      }
    }
    document.querySelector("#select").appendChild(frag);
    $("#select").val($("#select option:first").val());
    $('#select').trigger('change');
  }

  function fancyMixer(arr, arr2) {
    var blankArr = [];
    var freeDay = [];
    fill2DimensionsArray(freeDay, 1, 10)
    var freeInfo = false;
    var freeSleep = true;
    fill2DimensionsArray(blankArr, 7, 10);
    for (var i = 0; i < arr.length; i++) {
      for (var j = 0; j < 7; j++) {
        for (var k = 0; k < 10; k++) {
          if (blankArr[j][k] == 0)
            blankArr[j][k] = arr[i][j][k];
          else if (arr[i][j][k] != 0)
            return false;
        }

      }
    }
    for (var lel = 0; lel < 5; lel++) {
      if (blankArr[lel].toString() == freeDay[0].toString())
        freeInfo = "is:" + lel;
    }
    for (var ada = 0; ada < 5; ada++) {
      if (blankArr[ada][0] != 0 || blankArr[ada][1] != 0)
        freeSleep = false;
    }
    return {
      info: arr2,
      onWeek: blankArr,
      freeDay: freeInfo,
      freeSleep: freeSleep
    };
  }

  function combine(array, array2) {
      $.ajax({
  type: 'POST',
  url: "https://yoktur.org/scriptApi/uludag.php",
  data: { array: JSON.stringify(array), array2: JSON.stringify(array2) },
  success: function( data ) {
          final=JSON.parse(data);
      },
  async:false
});
    /*function c(part, index) {
      array[index].forEach(function (a) {
        var p = part.concat(a);
        if (p.length === array.length) {
          r.push(p);
          return;
        }
        c(p, index + 1);
      });
    }

    var r = [];

    c([], 0);*/
    /*final = [];
    for (var i = 0; i < r.length; i++) {
      /*var splitResult = r[i].substring(3).split("|||");
      for (var j = 0; j < splitResult.length; j++) {
      splitResult[j]=JSON.parse(splitResult[j]);
      }*/
      /*var temp = [];
      var temp2 = [];*/
      /*for (var k = 0; k < splitResult.length; k++) {
      temp.push(Object.values(splitResult[k])[0]);
      temp2.push(array2[k]+"  /  "+Object.keys(splitResult[k])[0]);
      }*/
      /*for (var k = 0; k < r[i].length; k++) {
        temp.push(Object.values(r[i][k])[0]);
        console.log(Object.values(r[i][k])[0]);
        console.log(r[i][k]);
        temp2.push(array2[k] + "  /  " + Object.keys(r[i][k])[0]);
      }
      var toPush = fancyMixer(temp, temp2);
      if (toPush)
        final.push(fancyMixer(temp, temp2));
    }
    return r;*/
  }
})();