Ejemplo n.º 1
0
    class IcerikOkuma(QDialog):
        def __init__(self, ctx, sayfalar, Kaydet):
            super(QDialog, self).__init__()
            self.ctx = ctx
            self.title = 'İçerik Okuma'
            self.initUI()
            self.sayfalar = sayfalar
            self.Kaydet = Kaydet
            self.sayfano = 0
            self.toplamsayfa = 0
            self.saniye = 0
            self.toplamsure = 0
            self.run = False
            if Kaydet: self.otomatikZamanla(1, self.IcerikKaydet)
            elif self.ctx.IcerikOto:
                self.otomatikZamanla(
                    10, self.otomatikBasla)  # 10 saniye sonra otomatik başla
            self.exec_()

        def initUI(self):
            self.setWindowTitle(self.title)
            self.lblDersAd = QLabel('Ders Adı', self)
            self.txtLink = QLineEdit('Ders Bağlantısı', self)
            self.btnBar = QHBoxLayout()
            self.lblStatus = QLabel('<Status>', self)
            self.btnGeri = QPushButton('Geri', self)
            self.btnBaslat = QPushButton('Başlat', self)
            self.btnIleri = QPushButton('İleri', self)
            self.btnBar.addWidget(self.lblStatus)
            self.btnBar.addWidget(self.btnGeri)
            self.btnBar.addWidget(self.btnBaslat)
            self.btnBar.addWidget(self.btnIleri)
            self.txtDers = QPlainTextEdit('İçerik', self)
            self.vlayout = QVBoxLayout()
            self.vlayout.addWidget(self.lblDersAd)
            self.vlayout.addWidget(self.txtLink)
            self.vlayout.addLayout(self.btnBar)
            self.btnGeri.clicked.connect(self.GeriClicked)
            self.btnBaslat.clicked.connect(self.BaslatClicked)
            self.btnIleri.clicked.connect(self.IleriClicked)
            self.vlayout.addWidget(self.txtDers)
            self.setLayout(self.vlayout)
            self.setGeometry(115, 115, 800, 511)

        @pyqtSlot()
        def closeEvent(self, event):
            if self.run:
                self.BaslatClicked()
            event.accept()

        def otomatikZamanla(self, sure, func):
            self.timerX = QTimer()
            self.timerX.timeout.connect(func)
            self.timerX.start(1000 * sure)

        def otomatikBasla(self):
            self.timerX.stop()
            self.timerX = None
            self.BaslatClicked()

        @pyqtSlot()
        def BaslatClicked(self):
            if self.timerX is not None:
                self.timerX.stop()
                self.timerX = None
            if not self.run:
                self.run = True
                self.timer = QTimer()
                self.timer.timeout.connect(self.IcerikOkuTimer)
                self.timer.start(1000)
                self.IcerikOkuTimer()
            else:
                self.run = False
                self.timer.stop()
                self.timer = None
                self.btnBaslat.setText(
                    f"({(self.saniye % self.ctx.SureArtim) + 1})..{self.ctx.SureArtim} Devam Et"
                )
                self.ctx.logYaz(
                    f"BaslaClicked: {self.toplamsayfa} adet sayfa toplam {self.toplamsure} saniye  okundu."
                )
                self.otomatikZamanla(
                    180, self.close
                )  #oturum kapanabilir, 3 dakika sonra pencereyi kapat

        def sayacSifirla(self):
            self.saniye -= (self.saniye % self.ctx.SureArtim)

        def GeriClicked(self):
            if self.run:
                if self.sayfano > 1:
                    self.sayfano -= 2
                    self.sayacSifirla()

        def IleriClicked(self):
            if self.run:
                self.sayfano += 0
                self.sayacSifirla()

        def IcerikOkuTimer(self):
            if (self.saniye % self.ctx.SureArtim) == 0:
                if self.sayfano < len(self.sayfalar):
                    self.IcerikOku(self.sayfano)
                self.sayfano += 1
                self.toplamsayfa += 1
                if self.sayfano > len(self.sayfalar):
                    self.sayfano = 0
                    self.BaslatClicked()
                    self.btnBaslat.setText('Tekrar Başlat')
                    if self.ctx.IcerikOto: self.close()
                    self.sayacSifirla()
            else:
                self.btnBaslat.setText(
                    f"({(self.saniye % self.ctx.SureArtim) + 1})..{self.ctx.SureArtim} Durdur"
                )
                self.setWindowTitle(
                    f"{self.title} Geçen süre: {self.toplamsure+1}")
            self.saniye += 1
            self.toplamsure += 1

        def IcerikKaydet(self):
            klasor = f"{self.ctx.anaKlasor}{ICERIKKLASOR}"
            self.Belge = Document()
            self.Belge.add_heading(f"{self.ctx.IcerikDers} Ders İçeriği", 0)
            self.btnBar.setEnabled(False)
            self.timerX.stop()
            for no in range(len(self.sayfalar)):
                self.IcerikOku(no)
                if no % 10 == 0: QCoreApplication.processEvents()
            dosya = f"{klasor}\\{self.ctx.IcerikDers[:8]}.docx"
            self.Belge.save(dosya)
            self.close()
            os.system(f'"{dosya}"')

        def IcerikOku(self, no):
            sayfalar = self.sayfalar
            yanit = self.ctx.getSession().get(sayfalar[no]['link'],
                                              cookies=self.ctx.cerezler)
            yanit.encoding = 'utf-8'
            durum = yanit.status_code
            if durum == 200:
                sonuc = yanit.text
                bolumadi = sayfalar[no]['ad']
                self.lblDersAd.setText(f"{bolumadi} {no+1}/{len(sayfalar)}")
                self.txtLink.setText(sayfalar[no]['link'])
                self.lblStatus.setText(f"Durum= HTTP<{durum}>")
                self.txtDers.clear()
                if self.Kaydet:
                    paragraf = self.Belge.add_heading(bolumadi, level=1)
                    self.Paragraf = paragraf.add_run()
                soup = BeautifulSoup(sonuc, features='html.parser')
                # div = soup.find('div', {'id': 'sound'})
                # div = soup.select('div#iceriksayfa,div.icerik_sayfasi') # iki attribute'dan birini aramak için
                div = soup.find('div', {'class': 'icerik_sayfasi'})
                if not div:
                    div = soup.find('div', {'id': 'iceriksayfa'})
                if not div:
                    div = soup.find('div', {'id': 'icerik'})
                if not div:
                    div = soup.find('table', {'class': 'content'})
                if div:
                    metin = str(div.text)
                    metin = metin.replace('\n', ' ')
                    metin = metin.replace('\0', ' ')
                    self.txtDers.setPlainText(metin)
                    if self.Kaydet:
                        paragraf = self.Belge.add_paragraph(metin)
                        self.Paragraf = paragraf.add_run()
                imgs = soup.find_all('img')
                if imgs:
                    self.txtDers.appendHtml(self.imgGetir(imgs))
                if not div:
                    div = soup.find('div', {'id': 'guizno'})
                    if div:
                        html, metin = self.degerlendirmeSorulariGetir(
                            soup, div.text)
                        self.txtDers.appendHtml(html)
                        if self.Kaydet: self.Belge.add_paragraph(metin)
                    else:
                        self.ctx.responseYaz(
                            self.ctx.anaKlasor +
                            f"{ICERIKKLASOR}\\oys-{self.ctx.IcerikDers[5:8]}no-{no}.html",
                            sonuc)
                        div = soup.find('table')
                        if div:
                            sonuc = div.text
                        self.txtDers.appendHtml(sonuc)
                        if self.Kaydet:
                            self.Belge.add_paragraph(
                                '<HTML OKUNAMADI (flash vs olabilir)>')
                if debug:
                    print(
                        f"IcerikOku: ders={bolumadi} status={durum} link={sayfalar[no]['link']}"
                    )
                return self.txtDers.toPlainText()

        def imgGetir(self, imgs, baseurl=''):
            html = ''
            for img in imgs:
                kaynak = baseurl + img['src']
                dosyaadi = kaynak.split('/')[-1]
                kaynak = self.ctx.adres + '/' + kaynak  #Viewer/temp/AYU/176/72/LRN//pics/2/bolum2.PNG
                new_kaynak = self.resimIndir(kaynak, dosyaadi)
                if debug:
                    print(
                        f"imgGetir img={img,img['src']} new_kaynak={new_kaynak}"
                    )
                new_img = img.text.replace(kaynak, new_kaynak)
                html += new_img
                if self.Kaydet:
                    en = int(img.get('width', '200')) - 20
                    boy = int(img.get('height', '150'))  #- 10
                    if debug: print(f"imgGetir en={en} boy={boy}")
                    try:
                        self.Paragraf.add_picture(new_kaynak,
                                                  width=Pt(en),
                                                  height=Pt(boy))
                    except:
                        self.Paragraf.add_text('<IMG hatalı>')
            return html

        def resimIndir(self, kaynak, dosyaadi):
            klasor = f"{self.ctx.anaKlasor}{ICERIKKLASOR}\\img"
            os.makedirs(klasor, exist_ok=True)
            new_kaynak = f"{klasor}\\{dosyaadi}"
            #print("new_kaynak=",new_kaynak)
            yanit = self.ctx.getSession().get(kaynak,
                                              cookies=self.ctx.cerezler,
                                              stream=True)
            with open(new_kaynak, 'wb') as dosya:
                for chunk in yanit.iter_content(chunk_size=512):
                    dosya.write(chunk)
            return new_kaynak

        def degerlendirmeSorulariGetir(self, soup, quizname):
            sorular = []
            scripts = soup.find_all('script')
            kaynak = ''
            for script in scripts:
                script = script.text
                if 'var deger' in script:
                    kaynak = re.findall('deger=\"(.*?)\"', script)
                    if kaynak == []:
                        kaynak = ''
                    else:
                        kaynak = kaynak[0]
            baseurl = '/' + kaynak[:-9]
            kaynak = self.ctx.adres + '/' + kaynak + quizname  #Viewer/temp/AYU/700/912/LRN//sorular/quiz1.txt
            if debug:
                print(
                    f"degerlendirmeSorulariGetir: baseurl={baseurl} kaynak={kaynak}"
                )
            yanit = self.ctx.getSession().get(kaynak,
                                              cookies=self.ctx.cerezler)
            # if debug: print(f"degerlendirmeSorulariGetir:", yanit.encoding)
            yanit.encoding = 'utf-8'
            if yanit.status_code != 200: return yanit.status_code
            try:
                sonuc = yanit.json()
            except:  #json.decoder.JSONDecodeError
                if debug:
                    print(
                        f"degerlendirmeSorulariGetir: yanit={yanit} kaynak={kaynak} status={yanit.status_code} text=\n{yanit.text}"
                    )
                return yanit.text
            if debug: print("degerlendirmeSorulariGetir: sonuc=", sonuc)
            quiz = sonuc['quiz']
            i = 0
            for soru in quiz:
                if soru['question'].find("img") > 0:
                    imgs = []
                    soruimg = BeautifulSoup(soru['question'],
                                            features='html.parser').find('img')
                    if debug:
                        print(f"degerlendirmeSorulariGetir: soruimg={soruimg}")
                    if soruimg:
                        imgs.append(soruimg)
                        self.imgGetir(imgs, baseurl)
                sorular.append({'soru': soru['question']})
                sorular[i]['siklar'] = soru['option']
                sorular[i]['cevap'] = soru['ans']
                i += 1
            html = ''
            metin = ''
            i = 0
            for soru in sorular:
                html += f"<b>Soru {i+1} : </b>" + soru['soru'] + '<br><ul>'
                metin += f"Soru {i+1} : " + soru['soru'] + '\n'
                # if debug: print(f"degerlendirmeSorulariGetir: siklar=", soru['siklar'])
                for opt, deger in soru['siklar'].items():
                    # if debug: print (f"degerlendirmeSorulariGetir: opt=", opt,"deger=",deger)
                    if deger.find("img") > 0:
                        imgs = []
                        soruimg = BeautifulSoup(
                            deger, features='html.parser').find('img')
                        if debug:
                            print(
                                f"degerlendirmeSorulariGetir: şık.soruimg={soruimg}"
                            )
                        if soruimg:
                            imgs.append(soruimg)
                            self.imgGetir(imgs, baseurl)
                    if opt == soru['cevap']:
                        html += '<li><b>' + opt + ')' + deger + '</b></li>'
                        metin += '\n(' + opt + ') ' + deger
                    else:
                        html += '<li>' + opt + ')' + deger + '</li>'
                        metin += '\n ' + opt + ') ' + deger
                html += '</ul><br><br>'
                metin += '\n\n'
                i += 1
                # html += soru['cevap']
            return html, metin
Ejemplo n.º 2
0
class EditOthers(QMdiSubWindow):
    def __init__(self, main, op):
        """
        Class for edit category, actor, character, box, media and keyword
        according given op.

        :param main: Reference for main windows.
        :param op: String representing the class to be edited.
        """
        super(EditOthers, self).__init__()

        self.main = main
        self.op = op
        self.session = DB.get_session()
        self.cls = None
        self.obj = None

        self.name = ''
        if self.op == 'category':
            self.cls = Category
            self.name = texts.category_s
        elif self.op == 'actor':
            self.cls = Actor
            self.name = texts.actor_s
        elif self.op == 'character':
            self.cls = Character
            self.name = texts.character_s
        elif self.op == 'box':
            self.cls = Box
            self.name = texts.box
        elif self.op == 'media':
            self.cls = Media
            self.name = texts.media_s
        elif self.op == 'keyword':
            self.cls = Keyword
            self.name = texts.keyword

        self.window_title = texts.edit + ' ' + self.name
        self.setWindowTitle(self.window_title)
        self.setGeometry(0, 0, 511, 205)

        self.subwindow = QWidget()
        p = self.palette()
        p.setColor(self.backgroundRole(), QColor(230, 230, 250))
        self.setPalette(p)
        self.setWidget(self.subwindow)

        font = QFont()
        font.setPointSize(11)

        # Vbox Main
        self.vbox_main = QVBoxLayout(self.subwindow)
        self.vbox_main.setContentsMargins(20, 20, 20, 20)
        self.vbox_main.setSpacing(10)

        # Select Label and Combobox
        objs = db_select_all(self.session, self.cls)
        text = texts.select + ' ' + self.name
        self.lb_select = QLabel(text)
        self.lb_select.setFont(font)
        self.lb_select.setFixedHeight(25)
        self.cb_select = cb_create('')
        self.cb_select.setFont(font)
        self.cb_select.setFixedHeight(30)
        populate_combobox(self.cb_select, objs)
        self.cb_select.setEditable(False)
        self.vbox_main.addWidget(self.lb_select)
        self.vbox_main.addWidget(self.cb_select)

        # PB Select
        self.pb_select = pb_create(texts.pb_leave)
        self.pb_select.setFixedHeight(40)
        self.pb_select.setEnabled(True)
        self.pb_select.setHidden(False)
        self.pb_select.clicked.connect(self.close)

        self.pb_help_1 = pb_create(texts.pb_help)
        self.pb_help_1.setFixedHeight(40)
        self.pb_help_1.setEnabled(True)
        self.pb_help_1.setHidden(False)
        self.pb_help_1.clicked.connect(self.help)
        self.pb_help_1.setShortcut('Ctrl+H')

        self.hbox_select = QHBoxLayout()
        spacer = QSpacerItem(40, 20, QSizePolicy.Expanding,
                             QSizePolicy.Minimum)
        self.hbox_select.addItem(spacer)
        self.hbox_select.addWidget(self.pb_select)
        self.hbox_select.addWidget(self.pb_help_1)
        self.hbox_select.addItem(spacer)
        self.vbox_main.addLayout(self.hbox_select)

        # Title
        text = texts.actual_value + ' ' + self.name
        self.lb = QLabel(text)
        self.lb.setFont(font)
        self.lb.setFixedHeight(25)
        self.le = le_create()
        self.le.setFont(font)
        self.lb.setEnabled(False)
        self.lb.setHidden(True)
        self.le.setEnabled(False)
        self.le.setHidden(True)
        self.vbox_main.addWidget(self.lb)
        self.vbox_main.addWidget(self.le)

        # Buttons
        self.pb_save = pb_create(texts.pb_save)
        self.pb_save.setShortcut('Ctrl+S')
        self.pb_save.clicked.connect(self.edit_object)
        self.pb_save.setMaximumHeight(40)

        self.pb_help_2 = pb_create(texts.pb_help)
        self.pb_help_2.clicked.connect(self.help)
        self.pb_help_2.setShortcut('Ctrl+H')
        self.pb_help_2.setMaximumHeight(40)

        self.pb_leave = pb_create(texts.pb_leave)
        self.pb_leave.clicked.connect(self.close)
        self.pb_leave.setShortcut('Ctrl+Q')
        self.pb_leave.setMaximumHeight(40)

        self.hb_pb = hbox_create([self.pb_save, self.pb_help_2, self.pb_leave])

        self.pb_save.setEnabled(False)
        self.pb_save.setHidden(True)
        self.pb_help_2.setEnabled(False)
        self.pb_help_2.setHidden(True)
        self.pb_leave.setEnabled(False)
        self.pb_leave.setHidden(True)

        self.vbox_main.addLayout(self.hb_pb)

        self.cb_select.currentIndexChanged.connect(self.obj_selected)

    def help(self):
        """
        Call for help.

        :return: Show a help view.
        """
        # I have to perform help preview functions on the main because the bug
        # "stack_trace posix.cc (699)" does not let the page find its directory.
        dir = os.getcwd()
        url = 'file:///' + dir + '/views_help/help_edit_box_others.html'
        self.main.views_help(url, texts.help_insert_series)

    # OBJ Select
    def obj_selected(self):
        """
        When object is selected in combobox get it in database and start new
        windows to edit it.
        """
        id, name = get_combobox_info(self.cb_select)

        self.obj = self.session.query(self.cls).get(id)

        if self.obj and id != 0:
            self.lb_select.setEnabled(False)
            self.lb_select.setHidden(True)
            self.cb_select.setEnabled(False)
            self.cb_select.setHidden(True)
            self.pb_select.setEnabled(False)
            self.pb_select.setHidden(True)
            self.pb_help_1.setEnabled(False)
            self.pb_help_1.setHidden(True)
            self.hbox_select.setEnabled(False)

            self.vbox_main.setContentsMargins(20, 0, 20, 20)
            self.setGeometry(0, 0, 511, 205)

            self.lb.setEnabled(True)
            self.lb.setHidden(False)
            self.le.setEnabled(True)
            self.le.setHidden(False)
            self.pb_save.setEnabled(True)
            self.pb_save.setHidden(False)
            self.pb_help_2.setEnabled(True)
            self.pb_help_2.setHidden(False)
            self.pb_leave.setEnabled(True)
            self.pb_leave.setHidden(False)
            self.le.setText(self.obj.name)

            self.le.returnPressed.connect(self.edit_object)
            self.cb_select.currentIndexChanged.disconnect()

    def edit_object(self):
        """
        Save object in database.
        """
        self.obj.name = self.le.text()
        result = db_insert_obj(self.session, self.obj)

        if result:
            text = texts.msg_edit_ok(self.obj.name)
            show_msg(texts.edit_ok, text, QMessageBox.Information,
                     QMessageBox.Close)
        else:
            text = texts.msg_edit_erro(self.obj.name)
            show_msg(texts.edit_error, text, QMessageBox.Critical,
                     QMessageBox.Close)

        self.le.setText('')
        objs = db_select_all(self.session, self.cls)
        populate_combobox(self.cb_select, objs)

        self.lb.setEnabled(False)
        self.lb.setHidden(True)
        self.le.setEnabled(False)
        self.le.setHidden(True)
        self.pb_save.setEnabled(False)
        self.pb_save.setHidden(True)
        self.pb_help_2.setEnabled(False)
        self.pb_help_2.setHidden(True)
        self.pb_leave.setEnabled(False)
        self.pb_leave.setHidden(True)

        self.vbox_main.setContentsMargins(20, 0, 20, 40)
        self.setGeometry(0, 0, 511, 205)

        self.lb_select.setEnabled(True)
        self.lb_select.setHidden(False)
        self.cb_select.setEnabled(True)
        self.cb_select.setHidden(False)
        self.pb_select.setEnabled(True)
        self.pb_select.setHidden(False)
        self.pb_help_1.setEnabled(True)
        self.pb_help_1.setHidden(False)
        self.hbox_select.setEnabled(True)

        self.le.setText('')

        self.le.returnPressed.disconnect()
        self.cb_select.currentIndexChanged.connect(self.obj_selected)

    def help(self):
        """
        Call for help.

        :return: Show a help view.
        """
        # I have to perform help preview functions on the main because the bug
        # "stack_trace posix.cc (699)" does not let the page find its directory.
        dir = os.getcwd()
        url = 'file:///' + dir + '/views_help/help_edit_box_others.html'
        self.main.views_help(url, texts.help_insert_series)

    # Close Event
    def closeEvent(self, event):
        self.session.close()