from flask import Flask, jsonify, request, render_template, redirect, url_for import os from pymongo import MongoClient from pymongo.errors import ConnectionFailure import logging # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) app = Flask(__name__) # MongoDB Configuration MONGODB_URI = os.getenv('MONGODB_URI', 'mongodb://localhost:27017/') DATABASE_NAME = 'code_snippets' COLLECTION_NAME = 'snippets' def get_db_connection(): """Get MongoDB connection""" try: client = MongoClient(MONGODB_URI) # Test connection client.admin.command('ping') db = client[DATABASE_NAME] return db except ConnectionFailure as e: logger.error(f"MongoDB connection failed: {e}") return None def initialize_db(): """Initialize database with default entries""" db = get_db_connection() if db is None: return False collection = db[COLLECTION_NAME] # Check if entries already exist if collection.count_documents({}) > 0: return True # Default entries with proper indentation examples (multiple languages) default_entries = [ {"endpoint": "navn1", "text": "#include \n#include \nusing namespace std;\n\nint main() {\n vector nums = {1, 2, 3, 4, 5};\n \n for(int i = 0; i < nums.size(); i++) {\n cout << \"Number: \" << nums[i] << endl;\n }\n \n return 0;\n}"}, {"endpoint": "navn2", "text": "def python_function():\n data = {\n 'name': 'python',\n 'values': [1, 2, 3, 4, 5]\n }\n for key, value in data.items():\n print(f'{key}: {value}')"}, {"endpoint": "navn3", "text": "class MyClass {\npublic:\n int value;\n \n MyClass(int v) : value(v) {}\n \n void display() {\n if (value > 0) {\n cout << \"Value: \" << value << endl;\n } else {\n cout << \"Invalid value\" << endl;\n }\n }\n};"}, {"endpoint": "navn4", "text": "function calculateSum(arr) {\n let sum = 0;\n \n for (let i = 0; i < arr.length; i++) {\n if (arr[i] > 0) {\n sum += arr[i];\n }\n }\n \n return sum;\n}"}, {"endpoint": "chiku1", "text": "#include \n#include \n\ntemplate\nclass SmartPointer {\nprivate:\n T* ptr;\n \npublic:\n SmartPointer(T* p = nullptr) : ptr(p) {}\n \n ~SmartPointer() {\n delete ptr;\n }\n \n T& operator*() {\n return *ptr;\n }\n};"}, {"endpoint": "chiku2", "text": "try {\n int* arr = new int[100];\n \n for(int i = 0; i < 100; i++) {\n arr[i] = i * i;\n \n if(i % 10 == 0) {\n cout << \"Progress: \" << i << \"%\" << endl;\n }\n }\n \n delete[] arr;\n} catch(const exception& e) {\n cerr << \"Error: \" << e.what() << endl;\n}"}, {"endpoint": "chiku3", "text": "struct Node {\n int data;\n Node* next;\n \n Node(int val) {\n data = val;\n next = nullptr;\n }\n};\n\nvoid printList(Node* head) {\n while(head != nullptr) {\n cout << head->data << \" -> \";\n head = head->next;\n }\n cout << \"NULL\" << endl;\n}"}, {"endpoint": "chiku4", "text": "public class JavaExample {\n private List items;\n \n public JavaExample() {\n this.items = new ArrayList<>();\n }\n \n public void addItem(String item) {\n if (item != null && !item.isEmpty()) {\n items.add(item);\n System.out.println(\"Added: \" + item);\n }\n }\n}"}, ] try: collection.insert_many(default_entries) logger.info("Database initialized with default entries") return True except Exception as e: logger.error(f"Failed to initialize database: {e}") return False # Initialize database on startup initialize_db() @app.route('/') def index(): """Main page with admin interface""" return render_template('index.html') @app.route('/admin') def admin(): """Admin page to manage snippets""" db = get_db_connection() if db is None: return "Database connection failed", 500 collection = db[COLLECTION_NAME] snippets = list(collection.find({}, {"_id": 0}).sort("endpoint", 1)) return render_template('admin.html', snippets=snippets) @app.route('/update_snippet', methods=['POST']) def update_snippet(): """Update a code snippet""" endpoint = request.form.get('endpoint') text = request.form.get('text') if not endpoint or text is None: return "Missing endpoint or text", 400 db = get_db_connection() if db is None: return "Database connection failed", 500 collection = db[COLLECTION_NAME] try: result = collection.update_one( {"endpoint": endpoint}, {"$set": {"text": text}}, upsert=True ) logger.info(f"Updated {endpoint}: {result.modified_count} documents modified") return redirect(url_for('admin')) except Exception as e: logger.error(f"Failed to update snippet: {e}") return f"Failed to update snippet: {e}", 500 # navn endpoints @app.route('/navn1') def navn1(): return get_snippet_response('navn1') @app.route('/navn2') def navn2(): return get_snippet_response('navn2') @app.route('/navn3') def navn3(): return get_snippet_response('navn3') @app.route('/navn4') def navn4(): return get_snippet_response('navn4') # chiku endpoints @app.route('/chiku1') def chiku1(): return get_snippet_response('chiku1') @app.route('/chiku2') def chiku2(): return get_snippet_response('chiku2') @app.route('/chiku3') def chiku3(): return get_snippet_response('chiku3') @app.route('/chiku4') def chiku4(): return get_snippet_response('chiku4') def get_snippet_response(endpoint): """Get snippet from database for given endpoint""" db = get_db_connection() if db is None: return jsonify({"error": "Database connection failed"}), 500 collection = db[COLLECTION_NAME] try: snippet = collection.find_one({"endpoint": endpoint}, {"_id": 0}) if snippet: return jsonify({"text": snippet["text"]}) else: return jsonify({"error": f"Snippet not found for {endpoint}"}), 404 except Exception as e: logger.error(f"Failed to fetch snippet: {e}") return jsonify({"error": f"Failed to fetch snippet: {e}"}), 500 # Keep original /replacement endpoint for backward compatibility @app.route('/replacement') def replacement(): return get_snippet_response('navn1') # Default to navn1 @app.route('/health') def health(): """Health check endpoint""" db = get_db_connection() if db is not None: return jsonify({"status": "healthy", "database": "connected"}) else: return jsonify({"status": "unhealthy", "database": "disconnected"}), 500 if __name__ == '__main__': port = int(os.environ.get('PORT', 7860)) app.run(host='0.0.0.0', port=port, debug=True)