-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
7493 lines (6233 loc) · 310 KB
/
app.py
File metadata and controls
7493 lines (6233 loc) · 310 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, render_template, request, jsonify, redirect, url_for, flash, session
import threading
import time
import os
import json
import time
import threading
from datetime import datetime, timedelta
from dotenv import load_dotenv
from functools import wraps
from werkzeug.utils import secure_filename
import tweepy
import smtplib
import random
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from bs4 import BeautifulSoup
import hashlib
import uuid
import secrets
# .env dosyasını yükle
load_dotenv()
# PythonAnywhere konfigürasyonu
try:
from pythonanywhere_config import configure_for_pythonanywhere
is_pythonanywhere = configure_for_pythonanywhere()
except ImportError:
is_pythonanywhere = False
# Debug mode kontrolü
DEBUG_MODE = os.environ.get('DEBUG', 'True').lower() == 'true'
from utils import (
fetch_latest_ai_articles, generate_ai_tweet_with_mcp_analysis,
generate_ai_tweet_with_content, post_tweet, mark_article_as_posted, load_json, save_json,
get_posted_articles_summary, reset_all_data, clear_pending_tweets,
get_data_statistics, load_automation_settings, save_automation_settings,
get_automation_status, send_telegram_notification, test_telegram_connection,
check_telegram_configuration, auto_detect_and_save_chat_id,
setup_twitter_api, send_gmail_notification, test_gmail_connection,
check_gmail_configuration, get_rate_limit_info, terminal_log,
create_automatic_backup, load_ai_keywords_config, save_ai_keywords_config,
get_all_active_keywords, fetch_ai_news_with_advanced_keywords,
update_ai_keyword_category, get_ai_keywords_stats, analyze_tweet_quality,
safe_log, get_trending_ai_hashtags, remove_emojis_from_text, enhance_hashtags_with_trending,
reset_rate_limit_status
)
# GitHub modülü kaldırıldı
# Security manager import - SQLite kullanacağız
# Version Information
APP_VERSION = "1.4.2"
APP_RELEASE_DATE = "2025-08-24"
VERSION_CHANGELOG = {
"1.4.2": "🔐 Şifre Yönetici Güvenlik İyileştirmeleri - 3 yanlış deneme sonrası otomatik veri silme, Gelişmiş session güvenliği, Detaylı hata yönetimi, Template güvenlik uyarıları, Kapsamlı test sistemi",
"1.4.1": "🔧 Sistem Kontrolü ve İyileştirmeleri - Duplicate kontrol sistemi kapsamlı kontrol ve doğrulama, Toplu tweet sistemi güvenlik kontrolleri, Haber çekme sistemi multi-source duplicate prevention, Version tracking sistemi otomatik güncelleme",
"1.4.0": "🚀 OpenRouter OCR Entegrasyonu - Ücretsiz vision modelleri ile gelişmiş OCR sistemi, Çok katmanlı fallback sistemi, Gelişmiş hata yönetimi, OCR test sistemi, Kapsamlı dokümantasyon",
"1.3.0": "🔄 GitHub modülü kaldırıldı, Footer düzeltildi, Navbar yenilendi",
"1.2.0": "✨ UI iyileştirmeleri ve performans optimizasyonları",
"1.1.0": "🚀 Otomatik tweet sistemi ve AI entegrasyonu"
}
app = Flask(__name__)
app.secret_key = os.environ.get('SECRET_KEY', 'your-secret-key-here')
# Security Manager instance - JSON kullan (basit ve güvenilir)
try:
from security_manager import SecurityManager
security_manager = SecurityManager()
print("JSON SecurityManager kullaniliyor")
except ImportError as e:
print(f"❌ SecurityManager yüklenemedi: {e}")
security_manager = None
# Markdown filter for Jinja2 templates
import re
def markdown_filter(text):
"""Basit markdown to HTML converter"""
if not text:
return ""
# Headers
text = re.sub(r'^# (.*$)', r'<h1>\1</h1>', text, flags=re.MULTILINE)
text = re.sub(r'^## (.*$)', r'<h2>\1</h2>', text, flags=re.MULTILINE)
text = re.sub(r'^### (.*$)', r'<h3>\1</h3>', text, flags=re.MULTILINE)
# Bold
text = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', text)
# Italic
text = re.sub(r'\*(.*?)\*', r'<em>\1</em>', text)
# Code blocks
text = re.sub(r'```(.*?)```', r'<pre><code>\1</code></pre>', text, flags=re.DOTALL)
# Inline code
text = re.sub(r'`(.*?)`', r'<code>\1</code>', text)
# Lists
text = re.sub(r'^- (.*$)', r'<li>\1</li>', text, flags=re.MULTILINE)
text = re.sub(r'(<li>.*</li>)', r'<ul>\1</ul>', text, flags=re.DOTALL)
# Line breaks
text = text.replace('\n\n', '<br><br>')
text = text.replace('\n', '<br>')
return text
app.jinja_env.filters['markdown'] = markdown_filter
# Test route'u
@app.route('/test')
def test():
return render_template('test.html')
# Favicon 404 hatasını önle
@app.route('/favicon.ico')
def favicon():
return app.send_static_file('favicon.ico')
# Template context processor for global variables
@app.context_processor
def inject_globals():
return {
'app_version': APP_VERSION,
'version_changelog': VERSION_CHANGELOG,
'is_pythonanywhere': is_pythonanywhere,
'use_local_assets': os.environ.get('USE_LOCAL_ASSETS', 'false').lower() == 'true'
}
# Global değişkenler ve sabitler
HISTORY_FILE = "posted_articles.json"
last_check_time = None
automation_running = False
background_scheduler_running = False
# Global ilerleme durumu değişkenleri
progress_status = {
'is_running': False,
'current_step': '',
'total_steps': 0,
'current_step_number': 0,
'message': '',
'start_time': None,
'estimated_time': 0
}
progress_lock = threading.Lock()
def update_progress(step, message, step_number=None, total_steps=None):
"""İlerleme durumunu güncelle"""
global progress_status
with progress_lock:
progress_status['current_step'] = step
progress_status['message'] = message
if step_number is not None:
progress_status['current_step_number'] = step_number
if total_steps is not None:
progress_status['total_steps'] = total_steps
# Tahmini süre hesapla
if progress_status['start_time']:
elapsed = time.time() - progress_status['start_time']
if step_number and total_steps and step_number > 0:
avg_time_per_step = elapsed / step_number
remaining_steps = total_steps - step_number
progress_status['estimated_time'] = avg_time_per_step * remaining_steps
def start_progress():
"""İlerleme takibini başlat"""
global progress_status
with progress_lock:
progress_status['is_running'] = True
progress_status['current_step'] = 'Başlatılıyor...'
progress_status['message'] = 'Sistem hazırlanıyor...'
progress_status['current_step_number'] = 0
progress_status['total_steps'] = 0
progress_status['start_time'] = time.time()
progress_status['estimated_time'] = 0
def end_progress():
"""İlerleme takibini sonlandır"""
global progress_status
with progress_lock:
progress_status['is_running'] = False
progress_status['current_step'] = 'Tamamlandı'
progress_status['message'] = 'İşlem başarıyla tamamlandı'
def ensure_tweet_ids(pending_tweets):
"""Pending tweets'lerin ID'lerini güvenli şekilde kontrol et ve düzelt"""
try:
for i, tweet in enumerate(pending_tweets):
if isinstance(tweet, dict):
if 'id' not in tweet or tweet['id'] is None:
tweet['id'] = i + 1
else:
# Object ise dict'e çevir
try:
tweet_dict = dict(tweet) if hasattr(tweet, '__dict__') else {}
tweet_dict['id'] = i + 1
pending_tweets[i] = tweet_dict
except:
# Son çare: yeni dict oluştur
pending_tweets[i] = {'id': i + 1, 'error': 'Tweet format hatası'}
return pending_tweets
except Exception as e:
terminal_log(f"❌ Tweet ID düzeltme hatası: {e}", "error")
return pending_tweets
# Giriş kontrolü decorator'ı
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'logged_in' not in session:
# AJAX isteği ise JSON ve 401 döndür
try:
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return jsonify({
'success': False,
'error': 'auth_required',
'login_url': url_for('login', _external=False)
}), 401
except Exception:
pass
return redirect(url_for('login'))
# "Beni Hatırla" süresini kontrol et
if session.get('remember_me') and session.get('remember_until'):
try:
remember_until = datetime.fromisoformat(session['remember_until'])
if datetime.now() > remember_until:
# Süre dolmuş, çıkış yap
session.clear()
flash('Oturum süreniz doldu. Lütfen tekrar giriş yapın.', 'info')
try:
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return jsonify({
'success': False,
'error': 'session_expired',
'login_url': url_for('login', _external=False)
}), 401
except Exception:
pass
return redirect(url_for('login'))
except:
# Hatalı tarih formatı, güvenlik için çıkış yap
session.clear()
try:
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return jsonify({
'success': False,
'error': 'session_invalid',
'login_url': url_for('login', _external=False)
}), 401
except Exception:
pass
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
def send_otp_email(email, otp_code):
"""E-posta ile OTP kodu gönder"""
try:
# E-posta ayarlarını kontrol et
if not EMAIL_SETTINGS['email'] or not EMAIL_SETTINGS['password']:
return False, "E-posta ayarları yapılandırılmamış"
# E-posta içeriği
subject = "AI Tweet Bot - Giriş Doğrulama Kodu"
body = f"""
Merhaba,
AI Tweet Bot uygulamasına giriş yapmak için doğrulama kodunuz:
{otp_code}
Bu kod 5 dakika geçerlidir.
Eğer bu giriş denemesi size ait değilse, bu e-postayı görmezden gelebilirsiniz.
İyi günler,
AI Tweet Bot
"""
# E-posta oluştur
msg = MIMEMultipart()
msg['From'] = EMAIL_SETTINGS['email']
msg['To'] = email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain', 'utf-8'))
# SMTP ile gönder
server = smtplib.SMTP(EMAIL_SETTINGS['smtp_server'], EMAIL_SETTINGS['smtp_port'])
server.starttls()
server.login(EMAIL_SETTINGS['email'], EMAIL_SETTINGS['password'])
server.send_message(msg)
server.quit()
return True, "E-posta başarıyla gönderildi"
except Exception as e:
return False, f"E-posta gönderme hatası: {str(e)}"
@app.route('/send_otp', methods=['POST'])
def send_otp():
"""OTP kodu gönder"""
try:
data = request.get_json()
email = data.get('email', '').strip().lower()
if not email:
return jsonify({"success": False, "error": "E-posta adresi gerekli"})
# Admin e-posta kontrolü
admin_email = EMAIL_SETTINGS['admin_email'].lower()
if not admin_email:
return jsonify({"success": False, "error": "Admin e-posta adresi yapılandırılmamış"})
if email != admin_email:
return jsonify({"success": False, "error": "Yetkisiz e-posta adresi"})
# 6 haneli güvenli rastgele kod oluştur
import secrets
otp_code = ''.join([str(secrets.randbelow(10)) for _ in range(6)])
# E-posta gönder
success, message = send_otp_email(email, otp_code)
if success:
# OTP kodunu kaydet (5 dakika geçerli)
email_otp_codes[email] = {
'code': otp_code,
'timestamp': datetime.now(),
'attempts': 0
}
return jsonify({"success": True, "message": "Doğrulama kodu gönderildi"})
else:
return jsonify({"success": False, "error": message})
except Exception as e:
return jsonify({"success": False, "error": f"Sistem hatası: {str(e)}"})
@app.route('/login', methods=['GET', 'POST'])
def login():
"""E-posta OTP ile güvenli giriş"""
if request.method == 'POST':
auth_method = request.form.get('auth_method', 'email_otp')
if auth_method == 'email_otp':
email = request.form.get('email', '').strip().lower()
otp_code = request.form.get('otp_code', '').strip()
# Giriş verilerini kontrol et
if not email:
flash('E-posta adresi gerekli!', 'error')
return render_template('login.html', error='E-posta adresi eksik')
if not otp_code:
flash('Doğrulama kodu gerekli!', 'error')
return render_template('login.html', error='Doğrulama kodu eksik')
# OTP kod formatını kontrol et
if len(otp_code) != 6 or not otp_code.isdigit():
flash('Doğrulama kodu 6 haneli rakam olmalıdır!', 'error')
return render_template('login.html', error='Geçersiz kod formatı')
# Admin e-posta kontrolü
admin_email = EMAIL_SETTINGS['admin_email'].lower()
if not admin_email:
flash('Sistem yapılandırma hatası!', 'error')
return render_template('login.html', error='Admin e-posta yapılandırılmamış')
if email != admin_email:
flash('Bu e-posta adresi ile giriş yetkiniz yok!', 'error')
return render_template('login.html', error='Yetkisiz e-posta adresi')
# OTP kontrolü
if email not in email_otp_codes:
flash('Geçersiz veya süresi dolmuş doğrulama kodu! Yeni kod talep edin.', 'error')
return render_template('login.html', error='Kod bulunamadı')
otp_data = email_otp_codes[email]
# Süre kontrolü (5 dakika = 300 saniye)
time_elapsed = (datetime.now() - otp_data['timestamp']).total_seconds()
if time_elapsed > 300:
del email_otp_codes[email]
flash('Doğrulama kodunun süresi doldu! Yeni kod talep edin.', 'error')
return render_template('login.html', error='Kod süresi doldu')
# Deneme sayısı kontrolü
if otp_data['attempts'] >= 3:
del email_otp_codes[email]
flash('Çok fazla hatalı deneme! Güvenlik nedeniyle kod iptal edildi.', 'error')
return render_template('login.html', error='Çok fazla hatalı deneme')
# Kod kontrolü
if otp_code == otp_data['code']:
# Başarılı giriş
del email_otp_codes[email]
session['logged_in'] = True
session['login_time'] = datetime.now().isoformat()
session['auth_method'] = 'email_otp'
session['user_email'] = email
# "Beni Hatırla" kontrolü
remember_me = request.form.get('remember_me')
if remember_me:
# 30 gün boyunca hatırla
session.permanent = True
app.permanent_session_lifetime = timedelta(days=30)
session['remember_me'] = True
session['remember_until'] = (datetime.now() + timedelta(days=30)).isoformat()
terminal_log(f"✅ Başarılı giriş (30 gün hatırlanacak): {email}", "success")
flash('E-posta doğrulama ile başarıyla giriş yaptınız! 30 gün boyunca hatırlanacaksınız.', 'success')
else:
# Normal session (tarayıcı kapanınca sona erer)
session.permanent = False
terminal_log(f"✅ Başarılı giriş: {email}", "success")
flash('E-posta doğrulama ile başarıyla giriş yaptınız!', 'success')
return redirect(url_for('index'))
else:
# Hatalı kod
otp_data['attempts'] += 1
remaining_attempts = 3 - otp_data['attempts']
# Terminal log
terminal_log(f"❌ Hatalı giriş denemesi: {email} - Kalan deneme: {remaining_attempts}", "warning")
if remaining_attempts > 0:
flash(f'Hatalı doğrulama kodu! {remaining_attempts} deneme hakkınız kaldı.', 'error')
return render_template('login.html', error=f'Hatalı kod - {remaining_attempts} deneme kaldı')
else:
del email_otp_codes[email]
flash('Çok fazla hatalı deneme! Yeni kod talep edin.', 'error')
return render_template('login.html', error='Deneme hakkı bitti')
# Eğer zaten giriş yapmışsa ana sayfaya yönlendir
if 'logged_in' in session:
return redirect(url_for('index'))
return render_template('login.html')
@app.route('/logout')
def logout():
"""Çıkış yap"""
user_email = session.get('user_email', 'Bilinmeyen kullanıcı')
was_remembered = session.get('remember_me', False)
session.clear()
if was_remembered:
terminal_log(f"🚪 Çıkış yapıldı (hatırlanan oturum): {user_email}", "info")
flash('Başarıyla çıkış yaptınız! Hatırlanan oturum temizlendi.', 'info')
else:
terminal_log(f"🚪 Çıkış yapıldı: {user_email}", "info")
flash('Başarıyla çıkış yaptınız!', 'info')
return redirect(url_for('login'))
# E-posta OTP sistemi için global değişken
email_otp_codes = {}
# E-posta ayarları
EMAIL_SETTINGS = {
'smtp_server': 'smtp.gmail.com',
'smtp_port': 587,
'email': os.environ.get('EMAIL_ADDRESS', ''),
'password': os.environ.get('EMAIL_PASSWORD', ''),
'admin_email': os.environ.get('ADMIN_EMAIL', '')
}
# Terminal log sistemi için global değişkenler
import queue
log_queue = queue.Queue(maxsize=1000)
@app.route('/')
@login_required
def index():
"""Ana sayfa - Minimal versiyon"""
try:
# Temel verileri yükle - performans için limit kullan
all_articles = load_json("posted_articles.json", limit=100) # Son 100 makale
pending_tweets = load_json("pending_tweets.json", limit=50) # Son 50 pending tweet
rejected_articles = load_json("rejected_articles.json", []) # Reddedilen makaleler
# Reddedilen makalelerin tarih formatını düzelt
for article in rejected_articles:
if 'rejected_at' in article:
try:
from datetime import datetime
rejected_date = datetime.fromisoformat(article['rejected_at'].replace('Z', '+00:00'))
article['rejected_at_formatted'] = rejected_date.strftime('%d.%m.%Y %H:%M')
except:
article['rejected_at_formatted'] = article.get('rejected_at', 'Bilinmiyor')
else:
article['rejected_at_formatted'] = 'Bilinmiyor'
# Aktif makaleleri filtrele
articles = [article for article in all_articles if not article.get('deleted', False)]
# Tweet ID'lerini güvenli şekilde kontrol et
pending_tweets = ensure_tweet_ids(pending_tweets)
# Tweet içeriklerini düzenle
for tweet in pending_tweets:
# Tweet metnini bul - farklı alan isimleri dene
tweet_text = ''
if 'tweet_data' in tweet and 'tweet' in tweet['tweet_data']:
tweet_text = tweet['tweet_data']['tweet']
elif 'content' in tweet:
tweet_text = tweet['content']
elif 'article' in tweet:
tweet_text = tweet['article'].get('title', 'İçerik bulunamadı')
# Tweet content alanını ayarla
tweet['content'] = tweet_text
# Başlık ve URL bilgilerini ekle
tweet['title'] = tweet['article'].get('title', 'Başlık bulunamadı') if 'article' in tweet else tweet.get('content', 'Başlık bulunamadı')
tweet['url'] = tweet['article'].get('url', '') if 'article' in tweet else ''
# Tarihe göre sırala
pending_tweets.sort(key=lambda x: x.get('created_at', ''), reverse=True)
# News count hesapla (haber kaynaklı tweet'ler)
news_count = 0
for tweet in pending_tweets:
if 'article' in tweet and tweet['article'].get('source_type') == 'news':
news_count += 1
# İstatistikleri ve durumu al
stats = get_data_statistics()
automation_status = get_automation_status()
# Terminal log
terminal_log(f"📊 Ana sayfa yüklendi: {len(pending_tweets)} bekleyen tweet, {len(articles)} son makale, {news_count} haber", "info")
# API durumu kontrolü - geliştirilmiş versiyon
try:
api_check = {
"twitter_api_available": bool(os.environ.get('TWITTER_BEARER_TOKEN') and os.environ.get('TWITTER_API_KEY')),
"telegram_available": bool(os.environ.get('TELEGRAM_BOT_TOKEN')),
"openrouter_api_available": bool(os.environ.get('OPENROUTER_API_KEY')),
"google_api_available": bool(os.environ.get('GOOGLE_API_KEY'))
}
except Exception as e:
terminal_log(f"⚠️ API durumu kontrol edilemedi: {str(e)}", "warning")
api_check = {
"twitter_api_available": False,
"telegram_available": False,
"google_api_available": False,
"openrouter_api_available": False
}
# Ayarları yükle - hata yakalama ile
try:
settings = load_automation_settings()
except Exception as e:
terminal_log(f"⚠️ Otomasyon ayarları yüklenemedi: {str(e)}", "warning")
settings = {}
# Gelişmiş özellikler için gerekli verileri hazırla
try:
# API durumu kontrolü
api_check = {
'openrouter_api_available': bool(os.getenv('OPENROUTER_API_KEY')),
'twitter_api_available': bool(os.getenv('TWITTER_API_KEY') and os.getenv('TWITTER_API_SECRET')),
'google_api_available': bool(os.getenv('GOOGLE_API_KEY')),
'telegram_available': bool(os.getenv('TELEGRAM_BOT_TOKEN'))
}
except:
api_check = {}
# Versiyon bilgisi
app_version = APP_VERSION
app_release_date = APP_RELEASE_DATE
# İstatistikler
stats = {
'today_articles': len(articles),
'today_pending': len(pending_tweets),
'today_total_activity': len(articles) + len(pending_tweets)
}
# Otomasyon durumu
automation_status = {
'auto_mode': True,
'check_interval_hours': 1,
'min_score_threshold': 7,
'max_articles_per_run': 5
}
# Haber sayısı
news_count = len(pending_tweets)
return render_template('index.html',
pending_tweets=pending_tweets[:20], # Maksimum 20 pending tweet
posted_count=len(articles),
rejected_count=len(rejected_articles),
rejected_articles=rejected_articles[:10], # İlk 10 reddedilen makale
api_check=api_check,
app_version=app_version,
app_release_date=app_release_date,
stats=stats,
automation_status=automation_status,
news_count=news_count)
except Exception as e:
safe_log(f"Ana sayfa hatası: {str(e)}", "ERROR")
return render_template('index.html',
pending_tweets=[],
posted_count=0,
rejected_count=0,
rejected_articles=[],
stats={},
automation_status={},
api_check={},
app_version=APP_VERSION,
app_release_date=APP_RELEASE_DATE,
news_count=0,
error=str(e))
@app.route('/api/progress')
@login_required
def get_progress():
"""İlerleme durumunu döndür"""
global progress_status
with progress_lock:
return jsonify(progress_status)
@app.route('/check_articles', methods=['GET', 'POST'])
@login_required
def check_articles():
"""Manuel makale kontrolü"""
try:
result = check_and_post_articles()
# AJAX isteği mi kontrol et
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
posted_count = result.get('posted_count', 0)
pending_count = result.get('pending_count', 0)
new_articles = posted_count + pending_count # Toplam yeni tweet sayısı
return jsonify({
'success': True,
'message': result['message'],
'new_articles': new_articles,
'posted_count': posted_count,
'pending_count': pending_count,
'total_pending': len(load_json("pending_tweets.json")),
'should_refresh': new_articles > 0
})
else:
flash(f"Kontrol tamamlandı: {result['message']}", 'success')
return redirect(url_for('index'))
except Exception as e:
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return jsonify({
'success': False,
'error': str(e),
'message': f"Hata: {str(e)}"
})
else:
flash(f"Hata: {str(e)}", 'error')
return redirect(url_for('index'))
def fetch_latest_ai_articles_with_mcp():
"""Özel haber kaynaklarından ve MCP ile AI makalelerini çek"""
try:
import hashlib
# Önce mevcut yayınlanan makaleleri yükle
posted_articles = load_json("posted_articles.json")
posted_urls = [article.get('url', '') for article in posted_articles]
posted_hashes = [article.get('hash', '') for article in posted_articles]
safe_log("Özel haber kaynaklarından makale çekiliyor...", "INFO")
# Önce özel kaynaklardan makale çek
try:
from utils import fetch_articles_from_custom_sources
terminal_log("🔍 Özel haber kaynaklarından makale çekiliyor...", "info")
custom_articles = fetch_articles_from_custom_sources()
if custom_articles:
terminal_log(f"✅ Özel kaynaklardan {len(custom_articles)} makale bulundu", "success")
# Makale hash'lerini oluştur ve tekrar kontrolü yap
filtered_articles = []
for article in custom_articles:
title = article.get('title', '')
url = article.get('url', '')
if title and url:
article_hash = hashlib.md5(title.encode()).hexdigest()
if url not in posted_urls and article_hash not in posted_hashes:
article['hash'] = article_hash
filtered_articles.append(article)
terminal_log(f"🆕 Yeni makale: {title[:50]}...", "success")
else:
terminal_log(f"✅ Makale zaten paylaşılmış: {title[:50]}...", "info")
if filtered_articles:
terminal_log(f"📊 {len(filtered_articles)} yeni makale filtrelendi", "info")
# Duplikat filtreleme uygula
from utils import filter_duplicate_articles
final_articles = filter_duplicate_articles(filtered_articles)
if final_articles:
terminal_log(f"✅ Duplikat filtreleme sonrası {len(final_articles)} benzersiz makale", "success")
return final_articles[:10] # İlk 10 makaleyi döndür
else:
terminal_log("⚠️ Duplikat filtreleme sonrası hiç makale kalmadı", "warning")
else:
terminal_log("⚠️ Özel kaynaklardan yeni makale bulunamadı", "warning")
else:
terminal_log("⚠️ Özel kaynaklardan hiç makale çekilemedi", "warning")
except Exception as custom_error:
terminal_log(f"❌ Özel kaynaklardan makale çekme hatası: {custom_error}", "error")
import traceback
traceback.print_exc()
# Eğer özel kaynaklardan yeterli makale bulunamadıysa MCP dene
terminal_log("🔄 Özel kaynaklardan yeterli makale bulunamadı, MCP deneniyor...", "info")
try:
# MCP Firecrawl kullanarak gerçek zamanlı veri çek (PythonAnywhere fallback sistemi)
from utils import mcp_firecrawl_scrape
scrape_result = mcp_firecrawl_scrape({
"url": "https://techcrunch.com/category/artificial-intelligence/",
"formats": ["markdown"],
"onlyMainContent": True,
"waitFor": 2000,
"removeBase64Images": True
})
if scrape_result and scrape_result.get("success"):
techcrunch_content = scrape_result.get("content", "")
terminal_log("✅ MCP Firecrawl ile gerçek zamanlı veri alındı", "success")
# Markdown'dan makale linklerini çıkar
import re
url_pattern = r'https://techcrunch\.com/\d{4}/\d{2}/\d{2}/[^)\s]+'
found_urls = re.findall(url_pattern, techcrunch_content)
article_urls = []
for url in found_urls:
if (url not in posted_urls and
"/2025/" in url and
len(article_urls) < 4): # Sadece son 4 makale
article_urls.append(url)
terminal_log(f"🔗 {len(article_urls)} yeni makale URL'si bulundu", "info")
articles_data = []
for url in article_urls:
try:
# URL'den başlığı çıkar (basit yöntem)
title_part = url.split('/')[-1].replace('-', ' ').title()
# Fallback yöntemi ile içeriği çek
from utils import fetch_article_content_advanced_fallback
article_result = fetch_article_content_advanced_fallback(url)
if article_result and article_result.get("content"):
title = article_result.get("title", title_part)
content = article_result.get("content", "")
# Makale hash'i oluştur
article_hash = hashlib.md5(title.encode()).hexdigest()
# Tekrar kontrolü
if article_hash not in posted_hashes:
articles_data.append({
"title": title,
"url": url,
"content": content,
"hash": article_hash,
"fetch_date": datetime.now().isoformat(),
"is_new": True,
"already_posted": False,
"source": "TechCrunch AI (MCP)"
})
terminal_log(f"🆕 MCP ile yeni makale: {title[:50]}...", "success")
else:
terminal_log(f"✅ Makale zaten paylaşılmış: {title[:50]}...", "info")
else:
terminal_log(f"⚠️ İçerik çekilemedi: {url}", "warning")
except Exception as article_error:
terminal_log(f"❌ Makale çekme hatası ({url}): {article_error}", "error")
continue
if articles_data:
terminal_log(f"📊 MCP ile {len(articles_data)} yeni makale bulundu", "success")
return articles_data
except Exception as mcp_error:
terminal_log(f"❌ MCP Firecrawl hatası: {mcp_error}", "error")
# Son fallback
terminal_log("🔄 Fallback yönteme geçiliyor...", "info")
return fetch_latest_ai_articles()
except Exception as e:
terminal_log(f"❌ Makale çekme hatası: {e}", "error")
terminal_log("🔄 Fallback yönteme geçiliyor...", "info")
return fetch_latest_ai_articles()
def check_and_post_articles():
"""Makale kontrol ve paylaşım fonksiyonu - MCP Firecrawl entegrasyonlu"""
try:
# İlerleme takibini başlat
start_progress()
update_progress("Sistem Başlatılıyor", "Makale kontrol sistemi hazırlanıyor...", 1, 8)
safe_log("Yeni makaleler kontrol ediliyor...", "INFO")
# Ayarları yükle
update_progress("Ayarlar Yükleniyor", "Sistem ayarları kontrol ediliyor...", 2, 8)
settings = load_automation_settings()
# AI API anahtarı opsiyonel olmalı: OpenRouter öncelikli, Google yedek, yoksa yerel fallback
api_key = os.environ.get('OPENROUTER_API_KEY') or ""
if not os.environ.get('OPENROUTER_API_KEY'):
# Uyarı ver, fakat işlemi durdurma (yerel fallback tweet üretimi mevcut)
terminal_log("⚠️ Hiçbir AI API anahtarı bulunamadı – fallback tweet oluşturma kullanılacak", "warning")
# Yeni makaleleri çek (akıllı sistem ile)
update_progress("Haberler Çekiliyor", "Güncel haberler toplanıyor...", 3, 8)
try:
from utils import fetch_latest_ai_articles_smart
terminal_log("🔍 Akıllı haber çekme sistemi başlatılıyor...", "info")
articles = fetch_latest_ai_articles_smart()
terminal_log(f"📊 {len(articles) if articles else 0} makale bulundu", "info")
except Exception as fetch_error:
terminal_log(f"❌ Haber çekme hatası: {fetch_error}", "error")
import traceback
terminal_log(f"🔍 Hata detayı: {traceback.format_exc()}", "error")
end_progress()
return {"success": False, "message": f"Haber çekme hatası: {str(fetch_error)}"}
if not articles:
end_progress()
return {"success": True, "message": "Yeni makale bulunamadı"}
posted_count = 0
pending_count = 0
ai_failures = 0 # AI API başarısızlık sayacı
max_articles = settings.get('max_articles_per_run', 3)
min_score = settings.get('min_score_threshold', 5)
auto_post = settings.get('auto_post_enabled', False)
# İşlenmiş makaleleri yükle (duplikat kontrolü için)
posted_articles = load_json("posted_articles.json")
pending_tweets = load_json("pending_tweets.json")
update_progress("Makaleler İşleniyor", f"{len(articles[:max_articles])} makale işleniyor...", 4, 8)
for i, article in enumerate(articles[:max_articles]):
try:
# İlerleme güncelle - makale işleme aşaması
update_progress("Makale İşleniyor", f"Makale {i+1}/{len(articles[:max_articles])}: {article.get('title', '')[:50]}...", 4 + i, 4 + len(articles[:max_articles]))
# Önce makale içeriğinin kaliteli olup olmadığını kontrol et
from utils import is_article_content_valid
is_valid, reason = is_article_content_valid(article)
if not is_valid:
terminal_log(f"❌ Kalitesiz makale atlandı: {article['title'][:50]}... - Sebep: {reason}", "warning")
# Kalitesiz makaleleri ayrı dosyaya kaydet
try:
rejected_articles = load_json("rejected_articles.json", [])
rejected_article = {
"title": article.get('title', ''),
"url": article.get('url', ''),
"reason": reason,
"rejected_at": datetime.now().isoformat(),
"content_preview": article.get('content', '')[:200] + "..." if article.get('content') else ""
}
rejected_articles.append(rejected_article)
# Son 100 rejected makaleyi tut
if len(rejected_articles) > 100:
rejected_articles = rejected_articles[-100:]
save_json("rejected_articles.json", rejected_articles)
except Exception as save_error:
terminal_log(f"⚠️ Rejected article kaydetme hatası: {save_error}", "warning")
continue
# Makale zaten işlenmiş mi kontrol et
article_url = article.get('url', '')
article_title = article.get('title', '')
article_hash = article.get('hash', '')
# Hash yoksa oluştur
if not article_hash and article_title:
import hashlib
article_hash = hashlib.md5(article_title.encode()).hexdigest()
article['hash'] = article_hash
terminal_log(f"🔧 Hash oluşturuldu: {article_title[:50]}...", "info")
# Boş başlık kontrolü
if not article_title or not article_title.strip():
terminal_log(f"⚠️ Boş başlık, atlanıyor: {article_url[:50]}...", "warning")
continue
# Posted articles kontrolü
already_posted = False
for posted in posted_articles:
posted_url = posted.get('url', '')
posted_hash = posted.get('hash', '')
# URL kontrolü
if article_url and article_url == posted_url:
already_posted = True
break
# Hash kontrolü
if article_hash and article_hash == posted_hash:
already_posted = True
break
# Pending tweets kontrolü
already_pending = False
for pending in pending_tweets:
pending_article = pending.get('article', {})
pending_url = pending_article.get('url', '')
pending_hash = pending_article.get('hash', '')
# URL kontrolü
if article_url and article_url == pending_url:
already_pending = True
break
# Hash kontrolü
if article_hash and article_hash == pending_hash:
already_pending = True
break
if already_posted:
terminal_log(f"⏭️ Makale zaten paylaşılmış, atlanıyor: {article['title'][:50]}...", "info")
continue
if already_pending:
terminal_log(f"⏭️ Makale zaten onay bekliyor, atlanıyor: {article['title'][:50]}...", "info")
continue
# Tweet oluştur - tema ile
update_progress("Tweet Oluşturuluyor", f"AI ile tweet oluşturuluyor: {article['title'][:50]}...", 4 + i, 4 + len(articles[:max_articles]))
theme = settings.get('tweet_theme', 'bilgilendirici')
terminal_log(f"🤖 Tweet oluşturuluyor (tema: {theme}): {article['title'][:50]}...", "info")
tweet_data = generate_ai_tweet_with_content(article, api_key, theme)
if not tweet_data or not tweet_data.get('tweet'):
terminal_log(f"❌ Tweet oluşturulamadı: {article['title'][:50]}...", "error")
ai_failures += 1
# AI API sürekli başarısız oluyorsa sistemi durdur
if ai_failures >= 3:
terminal_log(f"🚫 AI API'lar sürekli başarısız oluyor ({ai_failures} başarısızlık). Sistem durduruluyor.", "warning")
# Otomatik paylaşımı durdur ama auto_mode'u koruma (sadece haber kontrolü için)
settings['auto_post_enabled'] = False
# settings['auto_mode'] = False # Bunu kapatmayalım ki haber kontrolü devam etsin
save_automation_settings(settings)
return {"success": False, "message": f"AI API'lar sürekli başarısız olduğu için sistem durdu. API kotalarınızı kontrol edin.", "posted_count": posted_count, "pending_count": pending_count}
continue
# Tweet kalite kontrolü - OTOMATIK SİSTEMDE KALİTELİ TWEET ZORUNLULUĞU
update_progress("Kalite Kontrolü", f"Tweet kalitesi değerlendiriliyor: {article['title'][:50]}...", 4 + i, 4 + len(articles[:max_articles]))
if tweet_data.get('is_valid') == False:
quality_issues = tweet_data.get('quality_analysis', {}).get('issues', [])
terminal_log(f"❌ Tweet kalite kontrolünden geçemedi: {', '.join(quality_issues[:2])}", "error")
terminal_log(f"🚫 Kalitesiz tweet otomatik sistemde paylaşılmayacak: {article['title'][:50]}...", "warning")
continue
# Skor kontrolü
impact_score = tweet_data.get('impact_score', 0)
quality_score = tweet_data.get('quality_score', 7)
terminal_log(f"📊 Tweet skoru: {impact_score} (minimum: {min_score}), Kalite: {quality_score}/10", "info")
if impact_score < min_score:
terminal_log(f"⚠️ Düşük skor ({impact_score}), atlanıyor: {article['title'][:50]}...", "warning")
continue