<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by محمد ساعد on Medium]]></title>
        <description><![CDATA[Stories by محمد ساعد on Medium]]></description>
        <link>https://medium.com/@saadmoooooha2000?source=rss-d8240f0f2bb5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MhMnrkeFZ0li3xuI.jpg</url>
            <title>Stories by محمد ساعد on Medium</title>
            <link>https://medium.com/@saadmoooooha2000?source=rss-d8240f0f2bb5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:52:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saadmoooooha2000/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[EPANET PLUGIN لحساب ال Demand Allocation و توزيع أنماط الاستهلاك بشكل آلي]]></title>
            <link>https://medium.com/@saadmoooooha2000/epanet-plugin-%D9%84%D8%AD%D8%B3%D8%A7%D8%A8-%D8%A7%D9%84-demand-allocation-%D9%88-%D8%AA%D9%88%D8%B2%D9%8A%D8%B9-%D8%A3%D9%86%D9%85%D8%A7%D8%B7-%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D9%87%D9%84%D8%A7%D9%83-%D8%A8%D8%B4%D9%83%D9%84-%D8%A2%D9%84%D9%8A-95d2e676ccf8?source=rss-d8240f0f2bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/95d2e676ccf8</guid>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[محمد ساعد]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 01:13:36 GMT</pubDate>
            <atom:updated>2026-01-21T01:13:36.900Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eBxY9A2TfqIl6GcB" /></figure><p>تعد النمذجة الهيدروليكية لشبكات المياه حجر الزاوية في تصميم المدن الذكية والمستدامة. ومع ذلك، يواجه المهندسون تحدياً كلاسيكياً: <strong>كيف نوزع استهلاك المياه الكلي للمدينة على آلاف العقد (Junctions) في الشبكة بدقة وسرعة؟</strong></p><p>في هذا المقال، سأستعرض رحلتي في تطوير إضافة (Plugin) متقدمة لبرنامج <strong>EPANET-UI</strong>، تجمع بين قوة البرمجة بلغة Python وجمال واجهات PyQt5، لحل هذه المعضلة الهندسية.</p><h3>المعضلة الهندسية: توزيع الطلب (Demand Allocation)</h3><p>في الطريقة التقليدية، قد يضطر المهندس لتوزيع الطلب يدوياً بناءً على تقديرات تقريبية أو تقسيمات إدارية، وهو أمر يستهلك وقتاً هائلاً في الشبكات التي تحتوي على أكثر من 500 عقدة.</p><h3>لماذا اخترت “طريقة طول الأنابيب” (Pipe Length Method)؟</h3><p>تعتبر هذه الطريقة من أكثر الطرق عدالة ودقة في غياب بيانات العدادات الذكية (GIS-based billing data). الفكرة بسيطة رياضياً ولكنها معقدة تنفيذياً:</p><ul><li>كل أنبوب في الشبكة يخدم منطقة محيطة به.</li><li>نصيب العقدة من الاستهلاك يتناسب طردياً مع مجموع أطوال الأنابيب المرتبطة بها.</li><li><strong>المعادلة الرياضية:</strong></li></ul><pre>Q_node = Q_total × (Σ(L_connected_pipes / 2) / L_total_network)</pre><h3>الحل البرمجي: بنية الإضافة (Plugin Architecture)</h3><p>لقد صممت الإضافة لتكون وحدة مستقلة داخل بيئة <strong>EPANET-UI</strong>، مع التركيز على فصل المنطق البرمجي (Business Logic) عن واجهة المستخدم (UI).</p><h3>1. قلب المحرك الهيدروليكي: DemandCalculator</h3><p>هذا الكلاس هو المسؤول عن كافة الحسابات الثقيلة. يقوم بمسح الشبكة وتحديد العلاقات بين الأنابيب والعقد.</p><pre># مقتطف من ملف demand_calculator.py<br>def calculate_pipe_length_demands(self, total_city_demand):<br>    node_pipe_lengths = {}<br>    total_network_length = 0<br>    <br>    # خطوة 1: مسح كافة الأنابيب وحساب الأطوال<br>    for pipe in self.project.pipes.value:<br>        length = float(pipe.length)<br>        total_network_length += length<br>        <br>        # خطوة 2: توزيع نصيب كل أنبوب على عقدتي البداية والنهاية<br>        # (كل عقدة تأخذ نصف طول الأنبوب المرتبط بها)<br>        start_node = pipe.start_node_name<br>        end_node = pipe.end_node_name<br>        <br>        node_pipe_lengths[start_node] = node_pipe_lengths.get(start_node, 0) + (length / 2)<br>        node_pipe_lengths[end_node] = node_pipe_lengths.get(end_node, 0) + (length / 2)<br>            <br>    # خطوة 3: تحويل الأطوال النسبية إلى تدفقات (Flows)<br>    node_demands = {node: (length / total_network_length) * total_city_demand <br>                   for node, length in node_pipe_lengths.items()}<br>        <br>    return node_demands</pre><h3>2. واجهة المستخدم (UX/UI): تجربة سلسة بـ PyQt5</h3><p>لم أرد أن تكون الأداة مجرد سكريبت يعمل في الخلفية، بل أردتها واجهة تفاعلية توفر:</p><ul><li><strong>تحويل الوحدات</strong>: دعم الإدخال بـ (LPS, GPM, m³/h) وتحويلها آلياً لوحدات المشروع.</li><li><strong>المعاينة الفورية</strong>: جدول يعرض النتائج قبل تطبيقها على المشروع الفعلي.</li><li><strong>التحقق من التوازن</strong>: نظام فحص يضمن أن مجموع الطلبات الموزعة يساوي تماماً الطلب الكلي المدخل (Mass Balance Check).</li></ul><h3>التغلب على “كوابيس” التوافقية</h3><p>أثناء التطوير، واجهت مشكلة تقنية حرجة: اختلاف إصدارات المكتبات البرمجية داخل EPANET أدى لاختلاف مسميات الخصائص (مثل base_demand مقابل base_demand_flow).</p><p>بدلاً من جعل الأداة تعمل على إصدار واحد، قمت ببناء <strong>نظام محاولة ذكي (Smart Attribute Mapping)</strong>:</p><pre># آلية التوافق الذكية لضمان عمل الإضافة على أي بيئة<br>def apply_value(element, attr_list, value):<br>    for attr in attr_list:<br>        try:<br>            setattr(element, attr, value)<br>            return True<br>        except AttributeError:<br>            continue<br>    return False</pre><pre># الاستخدام<br>apply_value(junction, [&quot;base_demand_name&quot;, &quot;demand_pattern&quot;], &quot;Residential_Pattern&quot;)</pre><h3>إدارة أنماط الاستهلاك (Demand Patterns)</h3><p>الابتكار الآخر في هذه الإضافة هو سهولة إنشاء <strong>الأنماط الزمنية</strong>. عادة ما يضطر المهندس لإدخال 24 معاملاً (Multipliers) يدوياً لكل نمط.</p><p>توفر الإضافة الآن:</p><ol><li><strong>قوالب جاهزة (Presets)</strong>: لأنماط الاستهلاك السكني والتجاري بناءً على الأكواد العالمية.</li><li><strong>أداة تطبيق ذكية</strong>: تتيح اختيار مجموعة محددة من العقد أو كامل الشبكة لتطبيق النمط عليها بضغطة زر.</li></ol><h3>النتائج والأثر التقني</h3><p>بعد اختبار الإضافة على شبكة حقيقية تحتوي على أكثر من <strong>1200 عقدة</strong>:</p><ul><li><strong>توفير الوقت</strong>: تم إنجاز عملية توزيع الطلبات في <strong>1.5 ثانية</strong> بدلاً من <strong>3 ساعات</strong> من العمل اليدوي.</li><li><strong>الدقة</strong>: نسبة الخطأ في ميزان المياه (Water Balance) كانت <strong>0.0001%</strong> فقط، ناتجة عن التقريب العشري.</li><li><strong>سهولة التعديل</strong>: يمكن للمهندس الآن إعادة حساب التوزيع في ثوانٍ بمجرد تغيير إجمالي الطلب.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95d2e676ccf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Professional EPANET-UI Plugin from Scratch: A Comprehensive Developer’s Guide]]></title>
            <link>https://medium.com/@saadmoooooha2000/how-to-build-a-professional-epanet-ui-plugin-from-scratch-a-comprehensive-developers-guide-9e878be96b45?source=rss-d8240f0f2bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e878be96b45</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[water-distribution]]></category>
            <dc:creator><![CDATA[محمد ساعد]]></dc:creator>
            <pubDate>Sat, 17 Jan 2026 06:55:50 GMT</pubDate>
            <atom:updated>2026-02-02T06:25:22.864Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A complete technical guide for creating EPANET-UI plugins using Python, with practical examples and best practices</em></p><h3>Introduction</h3><h3>What is an EPANET-UI Plugin?</h3><p>A <strong>Plugin</strong> is an add-on component for EPANET-UI that allows you to extend the program’s capabilities and add custom functionality. Plugins are developed using <strong>Python</strong> and can interact directly with the project open in EPANET-UI.</p><h3>Why Build a Plugin?</h3><p><strong>Extend Functionality:</strong> Add features not available in the original version</p><p><strong>Automate Tasks:</strong> Execute repetitive operations with a single click</p><p><strong>Integrate with External Tools:</strong> Connect EPANET with Python libraries or external services</p><p><strong>Customize Interface:</strong> Add custom dialogs and menus</p><h3>Basic Plugin Structure</h3><p>This is the standard structure for any EPANET-UI plugin:</p><pre>my_plugin/<br>├── __init__.py          # Entry point (required)<br>├── metadata.txt         # Plugin metadata (required)<br>├── main.py              # Main plugin code<br>├── ui/                  # User interfaces (optional)<br>│   └── dialog.py<br>├── settings.json        # Plugin settings (optional)<br>└── README.md            # Plugin documentation (optional)</pre><h3>📑 Table of Contents</h3><p><strong>Section 1: Introduction and Basics</strong></p><ul><li>What is an EPANET-UI Plugin?</li><li>Why Build a Plugin?</li><li>Basic Plugin Structure</li></ul><p><strong>Section 2: Building the Plugin</strong></p><ul><li>The __init__.py File — Entry Point</li><li>The metadata.txt File — Metadata</li><li>Plugin Naming Convention and Its Importance</li></ul><p><strong>Section 3: Working with the Network</strong></p><ul><li>Accessing the INP File</li><li>Modifying Network Elements (Junctions, Pipes, Pumps)</li><li>Finding and Deleting Elements</li></ul><p><strong>Section 4: Advanced Capabilities</strong></p><ul><li>Running Simulations and Retrieving Results</li><li>Handling Units and Conversions</li><li>Batch Modification and Smart Modification</li><li>Working with Pump Curves</li><li>Export and Import</li></ul><p><strong>Section 5: Practical Implementation</strong></p><ul><li>Example 1: Network Statistics Plugin</li><li>Example 2: Network Optimization Plugin</li><li>Example 3: Plugin with PyQt5 Interface</li></ul><p><strong>Section 6: Best Practices</strong></p><ul><li>Error Handling and Data Validation</li><li>Using Logging</li><li>Settings Management and Documentation</li></ul><p><strong>Conclusion and Additional Resources</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*oHcTHdgmco6X_SLLwa4wTw.jpeg" /></figure><h3>Basic Plugin Structure</h3><h3>1. The __init__.py File — Entry Point</h3><p>This is the most important file in the plugin and is read by EPANET-UI when loading plugins.</p><p><strong>Required Variables:</strong></p><pre># Plugin name (appears in the plugins menu)<br>plugin_name = &quot;MyPlugin&quot;</pre><pre># Should a submenu be created in plugins?<br>plugin_create_menu = True</pre><pre># Submenu: {&quot;command_name&quot;: choice_number, ...}<br>__all__ = {<br>    &quot;First Command&quot;: 1,<br>    &quot;Second Command&quot;: 2,<br>    &quot;Settings&quot;: 3,<br>}</pre><p><strong>The </strong><strong>run() Function — Execution Point:</strong></p><pre>def run(session=None, choice=None):<br>    &quot;&quot;&quot;<br>    The function called by EPANET-UI</pre><pre>    Parameters:<br>        session: Current EPANET session (contains the project)<br>        choice: Selected command number from __all__<br>    &quot;&quot;&quot;<br>    if choice == 1:<br>        # Execute first command<br>        pass<br>    elif choice == 2:<br>        # Execute second command<br>        pass<br>    elif choice == 3:<br>        # Open settings<br>        pass</pre><h3>2. The metadata.txt File — Metadata</h3><pre>[general]<br>name=MyPlugin<br>description=Short description of the plugin<br>author=Developer Name<br>email=email@example.com<br>version=1.0.0<br>category=Analysis<br>tags=analysis, water, network<br>icon=icon.png</pre><h3>Plugin Naming Convention</h3><h3>Why Folder Name Must Match Plugin Name</h3><p>In the EPANET-UI plugin system, the folder name <strong>must</strong> match the plugin name specified in metadata.txt. If they don&#39;t match, user interfaces will fail to load.</p><h3>How Plugin Loading Works</h3><p>EPANET-UI follows this process to load plugins:</p><p><strong>Discovery:</strong> Scans the plugins/ directory for subdirectories</p><p><strong>Verification:</strong> Reads metadata.txt in each folder to get the plugin name</p><p><strong>Import:</strong> Imports __init__.py using the folder name as the module name</p><p><strong>Registration:</strong> Registers the plugin and its UI components</p><h3>The Triple Naming Relationship</h3><p>For the plugin to work correctly, these three names must match:</p><pre>Folder name: PipOpt<br>├── metadata.txt (name: PipOpt)<br>└── __init__.py (plugin_name: PipOpt)</pre><h3>Why Mismatches Cause UI Failures</h3><p>When names don’t match, several technical failures occur:</p><p><strong>Plugin Import Failure:</strong> Python cannot import the module if the folder name doesn’t match the expected module name</p><p><strong>Dynamic UI Loading Failure:</strong> The plugin cannot dynamically load UI files (like ui/calculation_dialog.py)</p><p><strong>Relative Import Failure:</strong> Relative imports within the plugin fail to resolve correctly</p><h3>Example Scenarios</h3><p>✅ <strong>Correct Configuration:</strong></p><pre>plugins/PipOpt/<br>├── metadata.txt (name: PipOpt)<br>└── __init__.py (plugin_name: PipOpt)</pre><p><em>Result: Plugin loads successfully, UI works</em></p><p>❌ <strong>Typo in Folder Name:</strong></p><pre>plugins/PipOptt/<br>├── metadata.txt (name: PipOpt)<br>└── __init__.py (plugin_name: PipOpt)</pre><p><em>Result: Plugin loading fails, UI doesn’t appear</em></p><p>❌ <strong>Mismatch in metadata.txt:</strong></p><pre>plugins/PipOpt/<br>├── metadata.txt (name: PipeOptimizer)<br>└── __init__.py (plugin_name: PipOpt)</pre><p><em>Result: Plugin loads but UI components fail</em></p><h3>The Role of init.py</h3><p>The __init__.py file serves several critical functions:</p><p><strong>Entry Point:</strong> Defines the run() function called by EPANET-UI</p><p><strong>Command List:</strong> Defines the __all__ list of available commands</p><p><strong>Plugin Name:</strong> Defines plugin_name for identification</p><p><strong>Dynamic UI Loading:</strong> Dynamically loads UI files using the plugin name</p><h3>Best Practices</h3><p>Always use consistent naming across folder, metadata.txt, and <strong>init</strong>.py</p><p>Use PascalCase for plugin names (e.g., PipOpt not pipopt)</p><p>Avoid special characters and spaces in plugin names</p><p>Test plugin loading immediately after creating the folder structure</p><h3>Troubleshooting</h3><p>If your UI doesn’t appear:</p><p>Verify that the folder name matches name in metadata.txt</p><p>Verify that plugin_name in __init__.py matches both</p><p>Look for import errors in the console/log</p><p>Ensure __init__.py exists and is properly formatted</p><h3>Accessing the INP File</h3><h3>Method 1: Via Session</h3><p>When run(session=None) is called, session contains the current project:</p><pre>def run(session=None, choice=None):<br>    # Access the project<br>    project = session.project</pre><pre>    # Project information<br>    print(project.info)  # General information<br>    print(project.fileName)  # INP file path</pre><h3>Method 2: Via Plugin Class</h3><p>You can create a plugin class that holds a reference to the project:</p><pre>class MyPlugin:<br>    def __init__(self, session):<br>        self.session = session<br>        self.project = session.project<br>        self.network_file = project.fileName</pre><pre>    def get_project_info(self):<br>        &quot;&quot;&quot;Get project information&quot;&quot;&quot;<br>        return {<br>            &quot;filename&quot;: self.project.fileName,<br>            &quot;title&quot;: self.project.info.title,<br>            &quot;junctions_count&quot;: len(self.project.junctions.value),<br>            &quot;pipes_count&quot;: len(self.project.pipes.value),<br>        }</pre><h3>Reading INP File Content Directly</h3><pre>import os</pre><pre>def read_inp_file(project):<br>    &quot;&quot;&quot;Read INP file content&quot;&quot;&quot;<br>    inp_file = project.fileName</pre><pre>    if not os.path.exists(inp_file):<br>        return {&quot;error&quot;: &quot;File does not exist&quot;}</pre><pre>    with open(inp_file, &#39;r&#39;, encoding=&#39;utf-8&#39;) as f:<br>        content = f.read()</pre><pre>    return {&quot;content&quot;: content, &quot;path&quot;: inp_file}</pre><h3>Modifying the Network</h3><h3>Project Structure in EPANET-UI</h3><p>The project contains collections for different elements:</p><p>junctions.value — Junctions</p><p>pipes.value — Pipes</p><p>pumps.value — Pumps</p><p>tanks.value — Tanks</p><p>reservoirs.value — Reservoirs</p><p>valves.value — Valves</p><p>curves.value — Curves</p><h3>Finding Elements</h3><pre>def find_junction(project, junction_id):<br>    &quot;&quot;&quot;Find a junction&quot;&quot;&quot;<br>    for j in project.junctions.value:<br>        if j.name == junction_id:<br>            return j<br>    return None</pre><pre>def find_pipe(project, pipe_id):<br>    &quot;&quot;&quot;Find a pipe&quot;&quot;&quot;<br>    for p in project.pipes.value:<br>        if p.name == pipe_id:<br>            return p<br>    return None</pre><h3>Creating New Elements</h3><p><strong>1️⃣ Creating a Junction</strong></p><pre>def create_junction(project, junction_id: str, elevation: float, demand: float):<br>    &quot;&quot;&quot;Create a new junction</pre><pre>    Parameters:<br>        junction_id: Junction ID (e.g., &quot;J1&quot;)<br>        elevation: Elevation (in meters)<br>        demand: Base demand flow (LPM)<br>    &quot;&quot;&quot;<br>    # Create junction object<br>    new_junction = project.junctions.element_class()<br>    new_junction.name = junction_id<br>    new_junction.elevation = elevation<br>    new_junction.base_demand_flow = demand</pre><pre>    # Add to collection<br>    project.junctions.value.append(new_junction)</pre><pre>    return {&quot;success&quot;: True, &quot;message&quot;: f&quot;Created {junction_id}&quot;}</pre><p><strong>2️⃣ Creating a Pipe</strong></p><pre>def create_pipe(project, pipe_id: str, node1: str, node2: str,<br>                length: float, diameter: float, roughness: float = 100.0):<br>    &quot;&quot;&quot;Create a new pipe</pre><pre>    Parameters:<br>        pipe_id: Pipe ID (e.g., &quot;P1&quot;)<br>        node1: First node (junction/tank/reservoir name)<br>        node2: Second node<br>        length: Length (meters)<br>        diameter: Diameter (inches)<br>        roughness: Roughness coefficient (default 100)<br>    &quot;&quot;&quot;<br>    # Find nodes<br>    n1 = find_node_object(project, node1)<br>    n2 = find_node_object(project, node2)</pre><pre>    if not n1 or not n2:<br>        return {&quot;success&quot;: False, &quot;error&quot;: &quot;Nodes not found&quot;}</pre><pre>    # Create pipe<br>    new_pipe = project.pipes.element_class()<br>    new_pipe.name = pipe_id<br>    new_pipe.inlet_node = n1<br>    new_pipe.outlet_node = n2<br>    new_pipe.length = length<br>    new_pipe.diameter = diameter<br>    new_pipe.roughness = roughness</pre><pre>    project.pipes.value.append(new_pipe)</pre><pre>    return {&quot;success&quot;: True, &quot;message&quot;: f&quot;Created {pipe_id}&quot;}</pre><p><strong>3️⃣ Creating a Pump</strong></p><pre>def create_pump(project, pump_id: str, node1: str, node2: str, head: float):<br>    &quot;&quot;&quot;Create a new pump&quot;&quot;&quot;<br>    n1 = find_node_object(project, node1)<br>    n2 = find_node_object(project, node2)</pre><pre>    new_pump = project.pumps.element_class()<br>    new_pump.name = pump_id<br>    new_pump.inlet_node = n1<br>    new_pump.outlet_node = n2<br>    new_pump.curve = f&quot;Curve_{pump_id}&quot;</pre><pre>    project.pumps.value.append(new_pump)</pre><pre>    return {&quot;success&quot;: True, &quot;message&quot;: f&quot;Created {pump_id}&quot;}</pre><h3>Modifying Existing Elements</h3><pre>def modify_junction_demand(project, junction_id: str, new_demand: float):<br>    &quot;&quot;&quot;Modify junction demand&quot;&quot;&quot;<br>    j = find_junction(project, junction_id)<br>    if not j:<br>        return {&quot;success&quot;: False, &quot;error&quot;: &quot;Junction not found&quot;}</pre><pre>    old_demand = j.base_demand_flow<br>    j.base_demand_flow = new_demand</pre><pre>    return {<br>        &quot;success&quot;: True,<br>        &quot;old_demand&quot;: old_demand,<br>        &quot;new_demand&quot;: new_demand<br>    }</pre><pre>def modify_pipe_diameter(project, pipe_id: str, new_diameter: float):<br>    &quot;&quot;&quot;Modify pipe diameter&quot;&quot;&quot;<br>    p = find_pipe(project, pipe_id)<br>    if not p:<br>        return {&quot;success&quot;: False, &quot;error&quot;: &quot;Pipe not found&quot;}</pre><pre>    old_diameter = p.diameter<br>    p.diameter = new_diameter</pre><pre>    return {<br>        &quot;success&quot;: True,<br>        &quot;old_diameter&quot;: old_diameter,<br>        &quot;new_diameter&quot;: new_diameter<br>    }</pre><h3>Deleting Elements</h3><pre>def delete_junction(project, junction_id: str):<br>    &quot;&quot;&quot;Delete a junction&quot;&quot;&quot;<br>    for i, j in enumerate(project.junctions.value):<br>        if j.name == junction_id:<br>            del project.junctions.value[i]<br>            return {&quot;success&quot;: True, &quot;message&quot;: f&quot;Deleted {junction_id}&quot;}<br>    return {&quot;success&quot;: False, &quot;error&quot;: &quot;Junction not found&quot;}</pre><h3>Available Capabilities</h3><h3>1️⃣ Running Simulation</h3><pre>def run_simulation(session):<br>    &quot;&quot;&quot;Run hydraulic simulation and prepare results&quot;&quot;&quot;<br>    try:<br>        # Standard method in EPANET-UI<br>        if hasattr(session, &quot;run_simulation&quot;):<br>            session.run_simulation()<br>            return {&quot;success&quot;: True}</pre><pre>        # Alternative if run from custom dialog<br>        project = session.project<br>        if hasattr(project, &quot;run_simulation&quot;):<br>            project.run_simulation()<br>            return {&quot;success&quot;: True}</pre><pre>        return {&quot;success&quot;: False, &quot;error&quot;: &quot;Simulation method not found&quot;}</pre><pre>    except Exception as e:<br>        return {&quot;success&quot;: False, &quot;error&quot;: str(e)}</pre><h3>2️⃣ Retrieving Simulation Results (Professional Method)</h3><p>After running the simulation, results are stored in a binary output file and can be accessed via session.output.</p><pre>from Externals.epanet.outputapi.ENOutputWrapper import ENR_link_type</pre><pre>def get_pipe_results(session):<br>    &quot;&quot;&quot;Retrieve flow and velocity for all pipes&quot;&quot;&quot;<br>    output = getattr(session, &quot;output&quot;, None)<br>    if not output:<br>        return {&quot;success&quot;: False, &quot;error&quot;: &quot;Simulation output not found&quot;}</pre><pre>    # 1. Determine time step (usually from time list in UI)<br>    time_index = 0<br>    if hasattr(session, &quot;cboTime&quot;):<br>        time_index = session.cboTime.currentIndex()</pre><pre>    # 2. Get attributes for all links at once<br>    flows_all = ENR_link_type.get_attribute_for_all_at_time(<br>        output, ENR_link_type.AttributeFlow, time_index<br>    )<br>    vels_all = ENR_link_type.get_attribute_for_all_at_time(<br>        output, ENR_link_type.AttributeVelocity, time_index<br>    )</pre><pre>    # 3. Map results to pipe names<br>    results = {&quot;flows&quot;: {}, &quot;velocities&quot;: {}}<br>    for name, link in output.links.items():<br>        idx = link.index<br>        # Use abs() for flow/velocity to get absolute values<br>        results[&quot;flows&quot;][name] = abs(flows_all[idx])<br>        results[&quot;velocities&quot;][name] = abs(vels_all[idx])</pre><pre>    return {&quot;success&quot;: True, &quot;data&quot;: results}</pre><h3>3️⃣ Handling Units and Conversions</h3><p>Professional plugins should handle both metric (SI) and US customary units.</p><pre>def is_metric(project):<br>    &quot;&quot;&quot;Check if project uses metric units&quot;&quot;&quot;<br>    if not project or not hasattr(project, &quot;options&quot;):<br>        return True # Default</pre><pre>    # Get flow units (0-4 US, 5-9 metric)<br>    units = project.options.hydraulics.flow_units<br>    unit_val = getattr(units, &#39;value&#39;, units)</pre><pre>    # LPS(5), LPM(6), MLD(7), CMH(8), CMD(9) are metric<br>    return unit_val &gt;= 5</pre><pre>def get_flow_conversion_to_m3s(project):<br>    &quot;&quot;&quot;Get project flow conversion factor to m³/s&quot;&quot;&quot;<br>    units = project.options.hydraulics.flow_units<br>    unit_val = getattr(units, &#39;value&#39;, units)</pre><pre>    factors = {<br>        5: 0.001,      # LPS -&gt; m3/s<br>        6: 1.6667e-5,  # LPM -&gt; m3/s<br>        7: 0.01157,    # MLD -&gt; m3/s<br>        8: 0.0002778,  # CMH -&gt; m3/s<br>        9: 1.1574e-5   # CMD -&gt; m3/s<br>    }<br>    return factors.get(unit_val, 1.0)</pre><h3>4️⃣ Saving the Network</h3><pre>def save_network(project, filepath: str = None):<br>    &quot;&quot;&quot;Save the network</pre><pre>    Parameters:<br>        filepath: Save path (optional)<br>    &quot;&quot;&quot;<br>    try:<br>        if filepath:<br>            project.save(filepath)<br>        else:<br>            project.save()</pre><pre>        return {&quot;success&quot;: True, &quot;filepath&quot;: filepath}</pre><pre>    except Exception as e:<br>        return {&quot;success&quot;: False, &quot;error&quot;: str(e)}</pre><h3>5️⃣ Getting Network Information</h3><pre>def get_network_info(project):<br>    &quot;&quot;&quot;Get network information&quot;&quot;&quot;<br>    return {<br>        &quot;junctions&quot;: len(project.junctions.value),<br>        &quot;pipes&quot;: len(project.pipes.value),<br>        &quot;pumps&quot;: len(project.pumps.value),<br>        &quot;tanks&quot;: len(project.tanks.value),<br>        &quot;reservoirs&quot;: len(project.reservoirs.value),<br>        &quot;valves&quot;: len(project.valves.value),<br>        &quot;curves&quot;: len(project.curves.value),<br>    }</pre><h3>6️⃣ Batch Modification</h3><pre>def modify_all_junctions_demand(project, multiplier: float):<br>    &quot;&quot;&quot;Modify all junctions demand&quot;&quot;&quot;<br>    count = 0<br>    for j in project.junctions.value:<br>        j.base_demand_flow *= multiplier<br>        count += 1</pre><pre>    return {&quot;success&quot;: True, &quot;count&quot;: count}</pre><h3>7️⃣ Smart Modification with Filters</h3><pre>def modify_by_filter(project, element_type: str, filter_type: str,<br>                     property_name: str, value, filter_params: dict = None):<br>    &quot;&quot;&quot;Smart modification based on filters</pre><pre>    Parameters:<br>        element_type: Element type (junction, pipe, pump, etc.)<br>        filter_type: Filter type (all, near, condition, spatial)<br>        property_name: Property to modify<br>        value: New value<br>        filter_params: Filter parameters<br>    &quot;&quot;&quot;<br>    collection = getattr(project, f&quot;{element_type}s&quot;)<br>    target_elements = []</pre><pre>    if filter_type == &quot;all&quot;:<br>        target_elements = collection.value</pre><pre>    elif filter_type == &quot;condition&quot;:<br>        prop = filter_params.get(&quot;property&quot;)<br>        operator = filter_params.get(&quot;operator&quot;, &quot;==&quot;)<br>        cond_value = filter_params.get(&quot;value&quot;)</pre><pre>        for el in collection.value:<br>            if not hasattr(el, prop):<br>                continue<br>            actual_val = getattr(el, prop)<br>            if operator == &quot;&gt;&quot; and actual_val &gt; cond_value:<br>                target_elements.append(el)<br>            elif operator == &quot;&lt;&quot; and actual_val &lt; cond_value:<br>                target_elements.append(el)<br>            elif operator == &quot;==&quot; and actual_val == cond_value:<br>                target_elements.append(el)</pre><pre>    # Execute modification<br>    count = 0<br>    for el in target_elements:<br>        if hasattr(el, property_name):<br>            setattr(el, property_name, value)<br>            count += 1</pre><pre>    return {&quot;success&quot;: True, &quot;count&quot;: count}</pre><h3>8️⃣ Working with Pump Curves</h3><pre>def create_pump_curve(project, curve_id: str, points: list):<br>    &quot;&quot;&quot;Create a pump curve</pre><pre>    Parameters:<br>        curve_id: Curve ID (e.g., &quot;Curve1&quot;)<br>        points: List of points [(flow1, head1), (flow2, head2), ...]<br>    &quot;&quot;&quot;<br>    new_curve = project.curves.element_class()<br>    new_curve.name = curve_id<br>    new_curve.points = points</pre><pre>    project.curves.value.append(new_curve)</pre><pre>    return {&quot;success&quot;: True, &quot;curve_id&quot;: curve_id}</pre><h3>9️⃣ Export and Import</h3><pre>def export_to_json(project, filepath: str):<br>    &quot;&quot;&quot;Export network to JSON&quot;&quot;&quot;<br>    data = {<br>        &quot;junctions&quot;: [],<br>        &quot;pipes&quot;: [],<br>        &quot;pumps&quot;: [],<br>    }</pre><pre>    for j in project.junctions.value:<br>        data[&quot;junctions&quot;].append({<br>            &quot;name&quot;: j.name,<br>            &quot;elevation&quot;: j.elevation,<br>            &quot;demand&quot;: j.base_demand_flow,<br>        })</pre><pre>    for p in project.pipes.value:<br>        data[&quot;pipes&quot;].append({<br>            &quot;name&quot;: p.name,<br>            &quot;node1&quot;: p.inlet_node.name,<br>            &quot;node2&quot;: p.outlet_node.name,<br>            &quot;length&quot;: p.length,<br>            &quot;diameter&quot;: p.diameter,<br>        })</pre><pre>    with open(filepath, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f:<br>        json.dump(data, f, indent=2, ensure_ascii=False)</pre><pre>    return {&quot;success&quot;: True, &quot;filepath&quot;: filepath}</pre><h3>Practical Examples</h3><h3>📌 Example 1: Simple Network Statistics Plugin</h3><p><strong>File </strong><strong>__init__.py:</strong></p><pre>plugin_name = &quot;StatsPlugin&quot;<br>plugin_create_menu = True<br>__all__ = {&quot;Show Statistics&quot;: 1}</pre><pre>def run(session=None, choice=None):<br>    from .main import StatsPlugin</pre><pre>    if choice == 1:<br>        plugin = StatsPlugin(session)<br>        stats = plugin.get_statistics()<br>        print(stats)</pre><p><strong>File </strong><strong>main.py:</strong></p><pre>class StatsPlugin:<br>    def __init__(self, session):<br>        self.project = session.project</pre><pre>    def get_statistics(self):<br>        &quot;&quot;&quot;Network statistics&quot;&quot;&quot;<br>        junctions = len(self.project.junctions.value)<br>        pipes = len(self.project.pipes.value)</pre><pre>        total_demand = sum(j.base_demand_flow for j in self.project.junctions.value)<br>        total_length = sum(p.length for p in self.project.pipes.value)</pre><pre>        return {<br>            &quot;junctions&quot;: junctions,<br>            &quot;pipes&quot;: pipes,<br>            &quot;total_demand_LPM&quot;: total_demand,<br>            &quot;total_length_m&quot;: total_length,<br>            &quot;avg_demand_per_junction&quot;: total_demand / junctions if junctions &gt; 0 else 0,<br>        }</pre><h3>📌 Example 2: Network Optimization Plugin</h3><p><strong>File </strong><strong>__init__.py:</strong></p><pre>plugin_name = &quot;OptimizerPlugin&quot;<br>plugin_create_menu = True<br>__all__ = {&quot;Optimize Diameters&quot;: 1, &quot;Optimize Demand&quot;: 2}</pre><pre>def run(session=None, choice=None):<br>    from .main import OptimizerPlugin</pre><pre>    plugin = OptimizerPlugin(session)</pre><pre>    if choice == 1:<br>        result = plugin.optimize_diameters()<br>        print(result[&quot;message&quot;])<br>    elif choice == 2:<br>        result = plugin.optimize_demand()<br>        print(result[&quot;message&quot;])</pre><p><strong>File </strong><strong>main.py:</strong></p><pre>class OptimizerPlugin:<br>    def __init__(self, session):<br>        self.project = session.project</pre><pre>    def optimize_diameters(self):<br>        &quot;&quot;&quot;Optimize pipe diameters&quot;&quot;&quot;<br>        count = 0<br>        for pipe in self.project.pipes.value:<br>            # Optimization logic<br>            if pipe.length &gt; 500 and pipe.diameter &lt; 12:<br>                pipe.diameter = 12<br>                count += 1</pre><pre>        return {&quot;success&quot;: True, &quot;message&quot;: f&quot;Optimized {count} pipes&quot;}</pre><pre>    def optimize_demand(self):<br>        &quot;&quot;&quot;Optimize demand distribution&quot;&quot;&quot;<br>        # Optimization logic<br>        return {&quot;success&quot;: True, &quot;message&quot;: &quot;Demand optimized&quot;}</pre><h3>📌 Example 3: Plugin with PyQt5 Interface</h3><p><strong>File </strong><strong>ui/dialog.py:</strong></p><pre>from PyQt5 import QtWidgets</pre><pre>class MyDialog(QtWidgets.QDialog):<br>    def __init__(self, plugin, parent=None):<br>        super().__init__(parent)<br>        self.plugin = plugin<br>        self.setup_ui()</pre><pre>    def setup_ui(self):<br>        layout = QtWidgets.QVBoxLayout()</pre><pre>        label = QtWidgets.QLabel(&quot;Hello!&quot;)<br>        layout.addWidget(label)</pre><pre>        button = QtWidgets.QPushButton(&quot;Show Statistics&quot;)<br>        button.clicked.connect(self.show_stats)<br>        layout.addWidget(button)</pre><pre>        self.setLayout(layout)</pre><pre>    def show_stats(self):<br>        stats = self.plugin.get_statistics()<br>        QtWidgets.QMessageBox.information(<br>            self, &quot;Statistics&quot;, str(stats)<br>        )</pre><h3>Best Practices</h3><h3>✅ 1. Error Handling</h3><pre>def safe_operation(project):<br>    &quot;&quot;&quot;Safe execution with error handling&quot;&quot;&quot;<br>    try:<br>        # Operation<br>        result = do_something(project)<br>        return {&quot;success&quot;: True, &quot;data&quot;: result}<br>    except AttributeError as e:<br>        return {&quot;success&quot;: False, &quot;error&quot;: f&quot;Specific error: {str(e)}&quot;}<br>    except Exception as e:<br>        return {&quot;success&quot;: False, &quot;error&quot;: f&quot;General error: {str(e)}&quot;}</pre><h3>✅ 2. Data Validation</h3><pre>def validate_junction(junction_id, elevation, demand):<br>    &quot;&quot;&quot;Validate junction data&quot;&quot;&quot;<br>    if not junction_id:<br>        return False, &quot;Junction ID is required&quot;<br>    if not isinstance(elevation, (int, float)):<br>        return False, &quot;Elevation must be a number&quot;<br>    if not isinstance(demand, (int, float)):<br>        return False, &quot;Demand must be a number&quot;<br>    if elevation &lt; 0:<br>        return False, &quot;Elevation cannot be negative&quot;<br>    if demand &lt; 0:<br>        return False, &quot;Demand cannot be negative&quot;</pre><pre>    return True, &quot;Valid&quot;</pre><h3>✅ 3. Using Logging</h3><pre>import logging<br>import os</pre><pre># Setup logging<br>logger = logging.getLogger(&quot;MyPlugin&quot;)<br>logger.setLevel(logging.DEBUG)</pre><pre>log_file = os.path.join(os.path.dirname(__file__), &quot;plugin.log&quot;)<br>handler = logging.FileHandler(log_file, encoding=&#39;utf-8&#39;)<br>formatter = logging.Formatter(&#39;%(asctime)s - %(levelname)s - %(message)s&#39;)<br>handler.setFormatter(formatter)<br>logger.addHandler(handler)</pre><pre># Usage<br>logger.info(&quot;Plugin started&quot;)<br>logger.error(f&quot;Failed to create junction: {str(e)}&quot;)</pre><h3>✅ 4. Settings Management</h3><pre>import json<br>import os</pre><pre>class SettingsManager:<br>    def __init__(self, settings_file=None):<br>        self.settings_file = settings_file or &quot;settings.json&quot;<br>        self.settings = self.load()</pre><pre>    def load(self):<br>        &quot;&quot;&quot;Load settings&quot;&quot;&quot;<br>        defaults = {<br>            &quot;option1&quot;: True,<br>            &quot;option2&quot;: 100,<br>            &quot;option3&quot;: &quot;value&quot;,<br>        }</pre><pre>        if os.path.exists(self.settings_file):<br>            try:<br>                with open(self.settings_file, &#39;r&#39;, encoding=&#39;utf-8&#39;) as f:<br>                    defaults.update(json.load(f))<br>            except:<br>                pass</pre><pre>        return defaults</pre><pre>    def save(self):<br>        &quot;&quot;&quot;Save settings&quot;&quot;&quot;<br>        with open(self.settings_file, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f:<br>            json.dump(self.settings, f, indent=2, ensure_ascii=False)</pre><pre>    def get(self, key, default=None):<br>        return self.settings.get(key, default)</pre><pre>    def set(self, key, value):<br>        self.settings[key] = value<br>        self.save()</pre><h3>✅ 5. Documentation</h3><pre>def create_element(project, element_type, element_id, **kwargs):<br>    &quot;&quot;&quot;<br>    Create a new element in the network</pre><pre>    Parameters:<br>        project: EPANET project<br>        element_type: Element type (junction, pipe, pump, tank, reservoir)<br>        element_id: Element ID<br>        **kwargs: Element properties</pre><pre>    Returns:<br>        dict: {<br>            &quot;success&quot;: bool,<br>            &quot;message&quot;: str,<br>            &quot;element_id&quot;: str<br>        }</pre><pre>    Raises:<br>        ValueError: If element_type is invalid<br>    &quot;&quot;&quot;<br>    pass</pre><h3>Conclusion</h3><p>This guide covers the essentials needed to create professional EPANET-UI plugins. Using these tools, you can:</p><p><strong>Extend program capabilities</strong> by adding custom features</p><p><strong>Automate repetitive tasks</strong> to save time and effort</p><p><strong>Integrate with Python libraries</strong> for advanced capabilities</p><p><strong>Improve analysis workflow</strong> using custom algorithms</p><h3>🔗 Additional Resources</h3><p>For more information and updates, refer to:</p><p><strong>EPANET-UI Source Code:</strong> on GitHub</p><p><strong>Official EPANET Documentation:</strong> from EPA website</p><p><strong>Existing Plugin Examples:</strong> in the plugins/ folder</p><p><strong>EPyT Library:</strong> Official documentation</p><p>💡 <strong>Final Tip:</strong> All modifications made through plugins apply directly to the open project. Always save your work before major modifications, and test plugins on a test copy before using in production.</p><p><em>This article was written to provide a comprehensive guide for developers who want to build EPANET-UI plugins. If you have any questions or inquiries, feel free to reach out or leave a comment!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e878be96b45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[كيفية بناء مكون إضافي احترافي لـ EPANET-UI من الصفر: دليل المطور الشامل]]></title>
            <link>https://medium.com/@saadmoooooha2000/%D9%83%D9%8A%D9%81-%D8%AA%D8%A8%D9%86%D9%8A-plugin-%D8%A7%D8%AD%D8%AA%D8%B1%D8%A7%D9%81%D9%8A-%D9%84%D9%80-epanet-ui-%D9%85%D9%86-%D8%A7%D9%84%D8%B5%D9%81%D8%B1-%D8%AF%D9%84%D9%8A%D9%84-%D8%B4%D8%A7%D9%85%D9%84-%D9%84%D9%84%D9%85%D8%B7%D9%88%D8%B1%D9%8A%D9%86-b2749b7fb428?source=rss-d8240f0f2bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2749b7fb428</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[water-distribution-system]]></category>
            <category><![CDATA[epanet]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[محمد ساعد]]></dc:creator>
            <pubDate>Sat, 17 Jan 2026 06:50:38 GMT</pubDate>
            <atom:updated>2026-02-02T06:22:00.147Z</atom:updated>
            <content:encoded><![CDATA[<p><em>دليل تقني كامل لإنشاء المكونات الإضافية لـ EPANET-UI باستخدام Python، مع أمثلة عملية وأفضل الممارسات</em></p><h3>مقدمة</h3><h3>ما هو المكون الإضافي لـ EPANET-UI؟</h3><p>المكون الإضافي (<strong>Plugin</strong>) هو مكون إضافي لـ EPANET-UI يسمح لك بتوسيع قدرات البرنامج وإضافة وظائف مخصصة. يتم تطوير المكونات الإضافية باستخدام <strong>Python</strong> ويمكنها التفاعل مباشرة مع المشروع المفتوح في EPANET-UI.</p><h3>لماذا نبني مكونًا إضافيًا؟</h3><p><strong>توسيع الوظائف:</strong> إضافة ميزات غير متوفرة في الإصدار الأصلي</p><p><strong>أتمتة المهام:</strong> تنفيذ العمليات المتكررة بنقرة زر واحدة</p><p><strong>التكامل مع الأدوات الخارجية:</strong> ربط EPANET بمكتبات Python أو خدمات خارجية</p><p><strong>تخصيص الواجهة:</strong> إضافة مربعات حوار وقوائم مخصصة</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*oHcTHdgmco6X_SLLwa4wTw.jpeg" /></figure><h3>📑 فهرس المحتويات</h3><p><strong>القسم الأول: المقدمة والأساسيات</strong></p><ul><li>ما هو المكون الإضافي لـ EPANET-UI؟</li><li>لماذا نبني مكونًا إضافيًا؟</li><li>الهيكل الأساسي للمكون الإضافي</li></ul><p><strong>القسم الثاني: بناء المكون الإضافي</strong></p><ul><li>ملف __init__.py — نقطة الدخول</li><li>ملف metadata.txt — البيانات الوصفية</li><li>اصطلاح تسمية المكون الإضافي وأهميته</li></ul><p><strong>القسم الثالث: التعامل مع الشبكة</strong></p><ul><li>الوصول إلى ملف INP</li><li>تعديل عناصر الشبكة (العقد، الأنابيب، المضخات)</li><li>البحث عن العناصر وحذفها</li></ul><p><strong>القسم الرابع: القدرات المتقدمة</strong></p><ul><li>تشغيل المحاكاة واسترجاع النتائج</li><li>معالجة الوحدات والتحويلات</li><li>التعديل المجمع والتعديل الذكي</li><li>العمل مع منحنيات المضخات</li><li>التصدير والاستيراد</li></ul><p><strong>القسم الخامس: التطبيق العملي</strong></p><ul><li>مثال 1: مكون إضافي لإحصائيات الشبكة</li><li>مثال 2: مكون إضافي لتحسين الشبكة</li><li>مثال 3: مكون إضافي مع واجهة PyQt5</li></ul><p><strong>القسم السادس: أفضل الممارسات</strong></p><ul><li>معالجة الأخطاء والتحقق من البيانات</li><li>استخدام التسجيل (Logging)</li><li>إدارة الإعدادات والتوثيق</li></ul><p><strong>الخاتمة والموارد الإضافية</strong></p><h3>الهيكل الأساسي للمكون الإضافي</h3><p>هذا هو الهيكل القياسي لأي مكون إضافي لـ EPANET-UI:</p><pre>my_plugin/<br>├── __init__.py          # نقطة الدخول (مطلوب)<br>├── metadata.txt         # بيانات المكون الإضافي (مطلوب)<br>├── main.py              # الكود الرئيسي للمكون الإضافي<br>├── ui/                  # واجهات المستخدم (اختياري)<br>│   └── dialog.py<br>├── settings.json        # إعدادات المكون الإضافي (اختياري)<br>└── README.md            # وثائق المكون الإضافي (اختياري)</pre><h3>الهيكل الأساسي للمكون الإضافي</h3><h3>1. ملف __init__.py — نقطة الدخول</h3><p>هذا هو أهم ملف في المكون الإضافي ويتم قراءته بواسطة EPANET-UI عند تحميل الإضافات.</p><p><strong>المتغيرات المطلوبة:</strong></p><pre># اسم المكون الإضافي (يظهر في قائمة المكونات الإضافية)<br>plugin_name = &quot;MyPlugin&quot;</pre><pre># هل يجب إنشاء قائمة فرعية في المكونات الإضافية؟<br>plugin_create_menu = True</pre><pre># القائمة الفرعية: {&quot;اسم الأمر&quot;: رقم_الاختيار، ...}<br>__all__ = {<br>    &quot;الأمر الأول&quot;: 1,<br>    &quot;الأمر الثاني&quot;: 2,<br>    &quot;الإعدادات&quot;: 3,<br>}</pre><p><strong>دالة </strong><strong>run() — نقطة التنفيذ:</strong></p><pre>def run(session=None, choice=None):<br>    &quot;&quot;&quot;<br>    الدالة التي يتم استدعاؤها بواسطة EPANET-UI</pre><pre>    المعاملات:<br>        session: جلسة EPANET الحالية (تحتوي على المشروع)<br>        choice: رقم الأمر المحدد من __all__<br>    &quot;&quot;&quot;<br>    if choice == 1:<br>        # تنفيذ الأمر الأول<br>        pass<br>    elif choice == 2:<br>        # تنفيذ الأمر الثاني<br>        pass<br>    elif choice == 3:<br>        # فتح الإعدادات<br>        pass</pre><h3>2. ملف metadata.txt — البيانات الوصفية</h3><pre>[general]<br>name=MyPlugin<br>description=وصف قصير للمكون الإضافي<br>author=اسم المطور<br>email=email@example.com<br>version=1.0.0<br>category=Analysis<br>tags=analysis, water, network<br>icon=icon.png</pre><h3>اصطلاح تسمية المكون الإضافي</h3><h3>لماذا يجب أن يتطابق اسم المجلد مع اسم المكون الإضافي</h3><p>في نظام المكونات الإضافية لـ EPANET-UI، يجب أن يتطابق اسم المجلد <strong>مع</strong> اسم المكون الإضافي المحدد في metadata.txt. إذا لم يتطابقان، فستفشل واجهات المستخدم في التحميل.</p><h3>كيفية عمل تحميل المكونات الإضافية</h3><p>يتبع EPANET-UI هذه العملية لتحميل المكونات الإضافية:</p><p><strong>الاكتشاف:</strong> يفحص دليل plugins/ بحثًا عن الأدلة الفرعية</p><p><strong>التحقق:</strong> يقرأ metadata.txt في كل مجلد للحصول على اسم المكون الإضافي</p><p><strong>الاستيراد:</strong> يستورد __init__.py باستخدام اسم المجلد كاسم الوحدة</p><p><strong>التسجيل:</strong> يسجل المكون الإضافي ومكونات واجهة المستخدم الخاصة به</p><h3>علاقة التسمية الثلاثية</h3><p>لكي يعمل المكون الإضافي بشكل صحيح، يجب أن تتطابق هذه الأسماء الثلاثة:</p><pre>اسم المجلد: PipOpt<br>├── metadata.txt (name: PipOpt)<br>└── __init__.py (plugin_name: PipOpt)</pre><h3>لماذا يسبب عدم التطابق فشل واجهة المستخدم</h3><p>عندما لا تتطابق الأسماء، تحدث عدة فشل تقني:</p><p><strong>فشل استيراد المكون الإضافي:</strong> لا يمكن لـ Python استيراد الوحدة إذا لم يتطابق اسم المجلد مع اسم الوحدة المتوقع</p><p><strong>فشل التحميل الديناميكي لواجهة المستخدم:</strong> لا يمكن للمكون الإضافي تحميل ملفات واجهة المستخدم ديناميكيًا (مثل ui/calculation_dialog.py)</p><p><strong>فشل الاستيراد النسبي:</strong> تفشل الاستيرادات النسبية داخل المكون الإضافي في الحل بشكل صحيح</p><h3>سيناريوهات المثال</h3><p>✅ <strong>التكوين الصحيح:</strong></p><pre>plugins/PipOpt/<br>├── metadata.txt (name: PipOpt)<br>└── __init__.py (plugin_name: PipOpt)</pre><p><em>النتيجة: يتم تحميل المكون الإضافي بنجاح، تعمل واجهة المستخدم</em></p><p>❌ <strong>خطأ مطبعي في اسم المجلد:</strong></p><pre>plugins/PipOptt/<br>├── metadata.txt (name: PipOpt)<br>└── __init__.py (plugin_name: PipOpt)</pre><p><em>النتيجة: يفشل تحميل المكون الإضافي، لا تظهر واجهة المستخدم</em></p><p>❌ <strong>عدم تطابق في metadata.txt:</strong></p><pre>plugins/PipOpt/<br>├── metadata.txt (name: PipeOptimizer)<br>└── __init__.py (plugin_name: PipOpt)</pre><p><em>النتيجة: يتم تحميل المكون الإضافي لكن تفشل مكونات واجهة المستخدم</em></p><h3>دور init.py</h3><p>يخدم ملف __init__.py عدة وظائف حرجة:</p><p><strong>نقطة الدخول:</strong> يحدد دالة run() التي يستدعيها EPANET-UI</p><p><strong>قائمة الأوامر:</strong> يحدد قائمة __all__ للأوامر المتاحة</p><p><strong>اسم المكون الإضافي:</strong> يحدد plugin_name للتعريف</p><p><strong>التحميل الديناميكي لواجهة المستخدم:</strong> يحمل ملفات واجهة المستخدم ديناميكيًا باستخدام اسم المكون الإضافي</p><h3>أفضل الممارسات</h3><p>استخدم دائمًا تسمية متسقة عبر المجلد و metadata.txt و <strong>init</strong>.py</p><p>استخدم PascalCase لأسماء المكونات الإضافية (مثل PipOpt وليس pipopt)</p><p>تجنب الأحرف الخاصة والمسافات في أسماء المكونات الإضافية</p><p>اختبر تحميل المكون الإضافي فورًا بعد إنشاء هيكل المجلد</p><h3>استكشاف الأخطاء وإصلاحها</h3><p>إذا لم تظهر واجهة المستخدم الخاصة بك:</p><p>تحقق من أن اسم المجلد يتطابق مع name في metadata.txt</p><p>تحقق من أن plugin_name في __init__.py يتطابق مع كليهما</p><p>ابحث عن أخطاء الاستيراد في وحدة التحكم/السجل</p><p>تأكد من وجود __init__.py وتنسيقه بشكل صحيح</p><h3>الوصول إلى ملف INP</h3><h3>الطريقة 1: عبر الجلسة</h3><p>عند استدعاء run(session=None)، تحتوي session على المشروع الحالي:</p><pre>def run(session=None, choice=None):<br>    # الوصول إلى المشروع<br>    project = session.project</pre><pre>    # معلومات المشروع<br>    print(project.info)  # معلومات عامة<br>    print(project.fileName)  # مسار ملف INP</pre><h3>الطريقة 2: عبر فئة المكون الإضافي</h3><p>يمكنك إنشاء فئة مكون إضافي تحتوي على مرجع للمشروع:</p><pre>class MyPlugin:<br>    def __init__(self, session):<br>        self.session = session<br>        self.project = session.project<br>        self.network_file = project.fileName</pre><pre>    def get_project_info(self):<br>        &quot;&quot;&quot;الحصول على معلومات المشروع&quot;&quot;&quot;<br>        return {<br>            &quot;filename&quot;: self.project.fileName,<br>            &quot;title&quot;: self.project.info.title,<br>            &quot;junctions_count&quot;: len(self.project.junctions.value),<br>            &quot;pipes_count&quot;: len(self.project.pipes.value),<br>        }</pre><h3>قراءة محتوى ملف INP مباشرة</h3><pre>import os</pre><pre>def read_inp_file(project):<br>    &quot;&quot;&quot;قراءة محتوى ملف INP&quot;&quot;&quot;<br>    inp_file = project.fileName</pre><pre>    if not os.path.exists(inp_file):<br>        return {&quot;error&quot;: &quot;الملف غير موجود&quot;}</pre><pre>    with open(inp_file, &#39;r&#39;, encoding=&#39;utf-8&#39;) as f:<br>        content = f.read()</pre><pre>    return {&quot;content&quot;: content, &quot;path&quot;: inp_file}</pre><h3>تعديل الشبكة</h3><h3>هيكل المشروع في EPANET-UI</h3><p>يحتوي المشروع على مجموعات لعناصر مختلفة:</p><p>junctions.value — العقد</p><p>pipes.value — الأنابيب</p><p>pumps.value — المضخات</p><p>tanks.value — الخزانات</p><p>reservoirs.value — الخزانات/الخزانات المفتوحة</p><p>valves.value — الصمامات</p><p>curves.value — المنحنيات</p><h3>البحث عن العناصر</h3><pre>def find_junction(project, junction_id):<br>    &quot;&quot;&quot;البحث عن عقدة&quot;&quot;&quot;<br>    for j in project.junctions.value:<br>        if j.name == junction_id:<br>            return j<br>    return None</pre><pre>def find_pipe(project, pipe_id):<br>    &quot;&quot;&quot;البحث عن أنبوب&quot;&quot;&quot;<br>    for p in project.pipes.value:<br>        if p.name == pipe_id:<br>            return p<br>    return None</pre><h3>إنشاء عناصر جديدة</h3><p><strong>1️⃣ إنشاء عقدة</strong></p><pre>def create_junction(project, junction_id: str, elevation: float, demand: float):<br>    &quot;&quot;&quot;إنشاء عقدة جديدة</pre><pre>    المعاملات:<br>        junction_id: معرف العقدة (مثل &quot;J1&quot;)<br>        elevation: الارتفاع (بالأمتار)<br>        demand: تدفق الطلب الأساسي (لتر/دقيقة)<br>    &quot;&quot;&quot;<br>    # إنشاء كائن العقدة<br>    new_junction = project.junctions.element_class()<br>    new_junction.name = junction_id<br>    new_junction.elevation = elevation<br>    new_junction.base_demand_flow = demand</pre><pre>    # إضافة إلى المجموعة<br>    project.junctions.value.append(new_junction)</pre><pre>    return {&quot;success&quot;: True, &quot;message&quot;: f&quot;تم إنشاء {junction_id}&quot;}</pre><p><strong>2️⃣ إنشاء أنبوب</strong></p><pre>def create_pipe(project, pipe_id: str, node1: str, node2: str,<br>                length: float, diameter: float, roughness: float = 100.0):<br>    &quot;&quot;&quot;إنشاء أنبوب جديد</pre><pre>    المعاملات:<br>        pipe_id: معرف الأنبوب (مثل &quot;P1&quot;)<br>        node1: العقدة الأولى (اسم العقدة/الخزان/الخزان المفتوح)<br>        node2: العقدة الثانية<br>        length: الطول (أمتار)<br>        diameter: القطر (بوصة)<br>        roughness: معامل الخشونة (الافتراضي 100)<br>    &quot;&quot;&quot;<br>    # البحث عن العقد<br>    n1 = find_node_object(project, node1)<br>    n2 = find_node_object(project, node2)</pre><pre>    if not n1 or not n2:<br>        return {&quot;success&quot;: False, &quot;error&quot;: &quot;العقد غير موجودة&quot;}</pre><pre>    # إنشاء الأنبوب<br>    new_pipe = project.pipes.element_class()<br>    new_pipe.name = pipe_id<br>    new_pipe.inlet_node = n1<br>    new_pipe.outlet_node = n2<br>    new_pipe.length = length<br>    new_pipe.diameter = diameter<br>    new_pipe.roughness = roughness</pre><pre>    project.pipes.value.append(new_pipe)</pre><pre>    return {&quot;success&quot;: True, &quot;message&quot;: f&quot;تم إنشاء {pipe_id}&quot;}</pre><p><strong>3️⃣ إنشاء مضخة</strong></p><pre>def create_pump(project, pump_id: str, node1: str, node2: str, head: float):<br>    &quot;&quot;&quot;إنشاء مضخة جديدة&quot;&quot;&quot;<br>    n1 = find_node_object(project, node1)<br>    n2 = find_node_object(project, node2)</pre><pre>    new_pump = project.pumps.element_class()<br>    new_pump.name = pump_id<br>    new_pump.inlet_node = n1<br>    new_pump.outlet_node = n2<br>    new_pump.curve = f&quot;Curve_{pump_id}&quot;</pre><pre>    project.pumps.value.append(new_pump)</pre><pre>    return {&quot;success&quot;: True, &quot;message&quot;: f&quot;تم إنشاء {pump_id}&quot;}</pre><h3>تعديل العناصر الموجودة</h3><pre>def modify_junction_demand(project, junction_id: str, new_demand: float):<br>    &quot;&quot;&quot;تعديل طلب العقدة&quot;&quot;&quot;<br>    j = find_junction(project, junction_id)<br>    if not j:<br>        return {&quot;success&quot;: False, &quot;error&quot;: &quot;العقدة غير موجودة&quot;}</pre><pre>    old_demand = j.base_demand_flow<br>    j.base_demand_flow = new_demand</pre><pre>    return {<br>        &quot;success&quot;: True,<br>        &quot;old_demand&quot;: old_demand,<br>        &quot;new_demand&quot;: new_demand<br>    }</pre><pre>def modify_pipe_diameter(project, pipe_id: str, new_diameter: float):<br>    &quot;&quot;&quot;تعديل قطر الأنبوب&quot;&quot;&quot;<br>    p = find_pipe(project, pipe_id)<br>    if not p:<br>        return {&quot;success&quot;: False, &quot;error&quot;: &quot;الأنبوب غير موجود&quot;}</pre><pre>    old_diameter = p.diameter<br>    p.diameter = new_diameter</pre><pre>    return {<br>        &quot;success&quot;: True,<br>        &quot;old_diameter&quot;: old_diameter,<br>        &quot;new_diameter&quot;: new_diameter<br>    }</pre><h3>حذف العناصر</h3><pre>def delete_junction(project, junction_id: str):<br>    &quot;&quot;&quot;حذف عقدة&quot;&quot;&quot;<br>    for i, j in enumerate(project.junctions.value):<br>        if j.name == junction_id:<br>            del project.junctions.value[i]<br>            return {&quot;success&quot;: True, &quot;message&quot;: f&quot;تم حذف {junction_id}&quot;}<br>    return {&quot;success&quot;: False, &quot;error&quot;: &quot;العقدة غير موجودة&quot;}</pre><h3>القدرات المتاحة</h3><h3>1️⃣ تشغيل المحاكاة</h3><pre>def run_simulation(session):<br>    &quot;&quot;&quot;تشغيل المحاكاة الهيدروليكية وإعداد النتائج&quot;&quot;&quot;<br>    try:<br>        # الطريقة القياسية في EPANET-UI<br>        if hasattr(session, &quot;run_simulation&quot;):<br>            session.run_simulation()<br>            return {&quot;success&quot;: True}</pre><pre>        # البديل إذا تم التشغيل من مربع حوار مخصص<br>        project = session.project<br>        if hasattr(project, &quot;run_simulation&quot;):<br>            project.run_simulation()<br>            return {&quot;success&quot;: True}</pre><pre>        return {&quot;success&quot;: False, &quot;error&quot;: &quot;طريقة المحاكاة غير موجودة&quot;}</pre><pre>    except Exception as e:<br>        return {&quot;success&quot;: False, &quot;error&quot;: str(e)}</pre><h3>2️⃣ استرجاع نتائج المحاكاة (الطريقة الاحترافية)</h3><p>بعد تشغيل المحاكاة، يتم تخزين النتائج في ملف الإخراج الثنائي ويمكن الوصول إليها عبر session.output.</p><pre>from Externals.epanet.outputapi.ENOutputWrapper import ENR_link_type</pre><pre>def get_pipe_results(session):<br>    &quot;&quot;&quot;استرجاع التدفق والسرعة لجميع الأنابيب&quot;&quot;&quot;<br>    output = getattr(session, &quot;output&quot;, None)<br>    if not output:<br>        return {&quot;success&quot;: False, &quot;error&quot;: &quot;لم يتم العثور على إخراج المحاكاة&quot;}</pre><pre>    # 1. تحديد خطوة الوقت (عادة من قائمة الوقت في واجهة المستخدم)<br>    time_index = 0<br>    if hasattr(session, &quot;cboTime&quot;):<br>        time_index = session.cboTime.currentIndex()</pre><pre>    # 2. الحصول على السمات لجميع الروابط مرة واحدة<br>    flows_all = ENR_link_type.get_attribute_for_all_at_time(<br>        output, ENR_link_type.AttributeFlow, time_index<br>    )<br>    vels_all = ENR_link_type.get_attribute_for_all_at_time(<br>        output, ENR_link_type.AttributeVelocity, time_index<br>    )</pre><pre>    # 3. تعيين النتائج إلى أسماء الأنابيب<br>    results = {&quot;flows&quot;: {}, &quot;velocities&quot;: {}}<br>    for name, link in output.links.items():<br>        idx = link.index<br>        # استخدام abs() للتدفق/السرعة للحصول على القيم المطلقة<br>        results[&quot;flows&quot;][name] = abs(flows_all[idx])<br>        results[&quot;velocities&quot;][name] = abs(vels_all[idx])</pre><pre>    return {&quot;success&quot;: True, &quot;data&quot;: results}</pre><h3>3️⃣ معالجة الوحدات والتحويلات</h3><p>يجب أن تتعامل المكونات الإضافية الاحترافية مع وحدات النظام المتري (SI) والوحدات الأمريكية المخصصة.</p><pre>def is_metric(project):<br>    &quot;&quot;&quot;التحقق مما إذا كان المشروع يستخدم وحدات مترية&quot;&quot;&quot;<br>    if not project or not hasattr(project, &quot;options&quot;):<br>        return True # الافتراضي</pre><pre>    # الحصول على وحدات التدفق (0-4 أمريكية، 5-9 مترية)<br>    units = project.options.hydraulics.flow_units<br>    unit_val = getattr(units, &#39;value&#39;, units)</pre><pre>    # LPS(5)، LPM(6)، MLD(7)، CMH(8)، CMD(9) هي مترية<br>    return unit_val &gt;= 5</pre><pre>def get_flow_conversion_to_m3s(project):<br>    &quot;&quot;&quot;الحصول على عامل تحويل تدفق المشروع إلى م^3/ث&quot;&quot;&quot;<br>    units = project.options.hydraulics.flow_units<br>    unit_val = getattr(units, &#39;value&#39;, units)</pre><pre>    factors = {<br>        5: 0.001,      # LPS -&gt; m3/s<br>        6: 1.6667e-5,  # LPM -&gt; m3/s<br>        7: 0.01157,    # MLD -&gt; m3/s<br>        8: 0.0002778,  # CMH -&gt; m3/s<br>        9: 1.1574e-5   # CMD -&gt; m3/s<br>    }<br>    return factors.get(unit_val, 1.0)</pre><h3>4️⃣ حفظ الشبكة</h3><pre>def save_network(project, filepath: str = None):<br>    &quot;&quot;&quot;حفظ الشبكة</pre><pre>    المعاملات:<br>        filepath: مسار الحفظ (اختياري)<br>    &quot;&quot;&quot;<br>    try:<br>        if filepath:<br>            project.save(filepath)<br>        else:<br>            project.save()</pre><pre>        return {&quot;success&quot;: True, &quot;filepath&quot;: filepath}</pre><pre>    except Exception as e:<br>        return {&quot;success&quot;: False, &quot;error&quot;: str(e)}</pre><h3>5️⃣ الحصول على معلومات الشبكة</h3><pre>def get_network_info(project):<br>    &quot;&quot;&quot;الحصول على معلومات الشبكة&quot;&quot;&quot;<br>    return {<br>        &quot;junctions&quot;: len(project.junctions.value),<br>        &quot;pipes&quot;: len(project.pipes.value),<br>        &quot;pumps&quot;: len(project.pumps.value),<br>        &quot;tanks&quot;: len(project.tanks.value),<br>        &quot;reservoirs&quot;: len(project.reservoirs.value),<br>        &quot;valves&quot;: len(project.valves.value),<br>        &quot;curves&quot;: len(project.curves.value),<br>    }</pre><h3>6️⃣ التعديل المجمّع</h3><pre>def modify_all_junctions_demand(project, multiplier: float):<br>    &quot;&quot;&quot;تعديل طلب جميع العقد&quot;&quot;&quot;<br>    count = 0<br>    for j in project.junctions.value:<br>        j.base_demand_flow *= multiplier<br>        count += 1</pre><pre>    return {&quot;success&quot;: True, &quot;count&quot;: count}</pre><h3>7️⃣ التعديل الذكي مع الفلاتر</h3><pre>def modify_by_filter(project, element_type: str, filter_type: str,<br>                     property_name: str, value, filter_params: dict = None):<br>    &quot;&quot;&quot;تعديل ذكي بناءً على الفلاتر</pre><pre>    المعاملات:<br>        element_type: نوع العنصر (junction، pipe، pump، إلخ)<br>        filter_type: نوع الفلتر (all، near، condition، spatial)<br>        property_name: الخاصية المراد تعديلها<br>        value: القيمة الجديدة<br>        filter_params: معاملات الفلتر<br>    &quot;&quot;&quot;<br>    collection = getattr(project, f&quot;{element_type}s&quot;)<br>    target_elements = []</pre><pre>    if filter_type == &quot;all&quot;:<br>        target_elements = collection.value</pre><pre>    elif filter_type == &quot;condition&quot;:<br>        prop = filter_params.get(&quot;property&quot;)<br>        operator = filter_params.get(&quot;operator&quot;, &quot;==&quot;)<br>        cond_value = filter_params.get(&quot;value&quot;)</pre><pre>        for el in collection.value:<br>            if not hasattr(el, prop):<br>                continue<br>            actual_val = getattr(el, prop)<br>            if operator == &quot;&gt;&quot; and actual_val &gt; cond_value:<br>                target_elements.append(el)<br>            elif operator == &quot;&lt;&quot; and actual_val &lt; cond_value:<br>                target_elements.append(el)<br>            elif operator == &quot;==&quot; and actual_val == cond_value:<br>                target_elements.append(el)</pre><pre>    # تنفيذ التعديل<br>    count = 0<br>    for el in target_elements:<br>        if hasattr(el, property_name):<br>            setattr(el, property_name, value)<br>            count += 1</pre><pre>    return {&quot;success&quot;: True, &quot;count&quot;: count}</pre><h3>8️⃣ العمل مع منحنيات المضخات</h3><pre>def create_pump_curve(project, curve_id: str, points: list):<br>    &quot;&quot;&quot;إنشاء منحنى مضخة</pre><pre>    المعاملات:<br>        curve_id: معرف المنحنى (مثل &quot;Curve1&quot;)<br>        points: قائمة النقاط [(flow1, head1), (flow2, head2), ...]<br>    &quot;&quot;&quot;<br>    new_curve = project.curves.element_class()<br>    new_curve.name = curve_id<br>    new_curve.points = points</pre><pre>    project.curves.value.append(new_curve)</pre><pre>    return {&quot;success&quot;: True, &quot;curve_id&quot;: curve_id}</pre><h3>9️⃣ التصدير والاستيراد</h3><pre>def export_to_json(project, filepath: str):<br>    &quot;&quot;&quot;تصدير الشبكة إلى JSON&quot;&quot;&quot;<br>    data = {<br>        &quot;junctions&quot;: [],<br>        &quot;pipes&quot;: [],<br>        &quot;pumps&quot;: [],<br>    }</pre><pre>    for j in project.junctions.value:<br>        data[&quot;junctions&quot;].append({<br>            &quot;name&quot;: j.name,<br>            &quot;elevation&quot;: j.elevation,<br>            &quot;demand&quot;: j.base_demand_flow,<br>        })</pre><pre>    for p in project.pipes.value:<br>        data[&quot;pipes&quot;].append({<br>            &quot;name&quot;: p.name,<br>            &quot;node1&quot;: p.inlet_node.name,<br>            &quot;node2&quot;: p.outlet_node.name,<br>            &quot;length&quot;: p.length,<br>            &quot;diameter&quot;: p.diameter,<br>        })</pre><pre>    with open(filepath, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f:<br>        json.dump(data, f, indent=2, ensure_ascii=False)</pre><pre>    return {&quot;success&quot;: True, &quot;filepath&quot;: filepath}</pre><h3>أمثلة عملية</h3><h3>📌 مثال 1: مكون إضافي بسيط لإحصائيات الشبكة</h3><p><strong>ملف </strong><strong>__init__.py:</strong></p><pre>plugin_name = &quot;StatsPlugin&quot;<br>plugin_create_menu = True<br>__all__ = {&quot;عرض الإحصائيات&quot;: 1}</pre><pre>def run(session=None, choice=None):<br>    from .main import StatsPlugin</pre><pre>    if choice == 1:<br>        plugin = StatsPlugin(session)<br>        stats = plugin.get_statistics()<br>        print(stats)</pre><p><strong>ملف </strong><strong>main.py:</strong></p><pre>class StatsPlugin:<br>    def __init__(self, session):<br>        self.project = session.project</pre><pre>    def get_statistics(self):<br>        &quot;&quot;&quot;إحصائيات الشبكة&quot;&quot;&quot;<br>        junctions = len(self.project.junctions.value)<br>        pipes = len(self.project.pipes.value)</pre><pre>        total_demand = sum(j.base_demand_flow for j in self.project.junctions.value)<br>        total_length = sum(p.length for p in self.project.pipes.value)</pre><pre>        return {<br>            &quot;junctions&quot;: junctions,<br>            &quot;pipes&quot;: pipes,<br>            &quot;total_demand_LPM&quot;: total_demand,<br>            &quot;total_length_m&quot;: total_length,<br>            &quot;avg_demand_per_junction&quot;: total_demand / junctions if junctions &gt; 0 else 0,<br>        }</pre><h3>📌 مثال 2: مكون إضافي لتحسين الشبكة</h3><p><strong>ملف </strong><strong>__init__.py:</strong></p><pre>plugin_name = &quot;OptimizerPlugin&quot;<br>plugin_create_menu = True<br>__all__ = {&quot;تحسين الأقطار&quot;: 1, &quot;تحسين الطلب&quot;: 2}</pre><pre>def run(session=None, choice=None):<br>    from .main import OptimizerPlugin</pre><pre>    plugin = OptimizerPlugin(session)</pre><pre>    if choice == 1:<br>        result = plugin.optimize_diameters()<br>        print(result[&quot;message&quot;])<br>    elif choice == 2:<br>        result = plugin.optimize_demand()<br>        print(result[&quot;message&quot;])</pre><p><strong>ملف </strong><strong>main.py:</strong></p><pre>class OptimizerPlugin:<br>    def __init__(self, session):<br>        self.project = session.project</pre><pre>    def optimize_diameters(self):<br>        &quot;&quot;&quot;تحسين أقطار الأنابيب&quot;&quot;&quot;<br>        count = 0<br>        for pipe in self.project.pipes.value:<br>            # منطق التحسين<br>            if pipe.length &gt; 500 and pipe.diameter &lt; 12:<br>                pipe.diameter = 12<br>                count += 1</pre><pre>        return {&quot;success&quot;: True, &quot;message&quot;: f&quot;تم تحسين {count} أنبوب&quot;}</pre><pre>    def optimize_demand(self):<br>        &quot;&quot;&quot;تحسين توزيع الطلب&quot;&quot;&quot;<br>        # منطق التحسين<br>        return {&quot;success&quot;: True, &quot;message&quot;: &quot;تم تحسين الطلب&quot;}</pre><h3>📌 مثال 3: مكون إضافي مع واجهة PyQt5</h3><p><strong>ملف </strong><strong>ui/dialog.py:</strong></p><pre>from PyQt5 import QtWidgets</pre><pre>class MyDialog(QtWidgets.QDialog):<br>    def __init__(self, plugin, parent=None):<br>        super().__init__(parent)<br>        self.plugin = plugin<br>        self.setup_ui()</pre><pre>    def setup_ui(self):<br>        layout = QtWidgets.QVBoxLayout()</pre><pre>        label = QtWidgets.QLabel(&quot;مرحبًا!&quot;)<br>        layout.addWidget(label)</pre><pre>        button = QtWidgets.QPushButton(&quot;عرض الإحصائيات&quot;)<br>        button.clicked.connect(self.show_stats)<br>        layout.addWidget(button)</pre><pre>        self.setLayout(layout)</pre><pre>    def show_stats(self):<br>        stats = self.plugin.get_statistics()<br>        QtWidgets.QMessageBox.information(<br>            self, &quot;الإحصائيات&quot;, str(stats)<br>        )</pre><h3>أفضل الممارسات</h3><h3>✅ 1. معالجة الأخطاء</h3><pre>def safe_operation(project):<br>    &quot;&quot;&quot;تنفيذ آمن مع معالجة الأخطاء&quot;&quot;&quot;<br>    try:<br>        # العملية<br>        result = do_something(project)<br>        return {&quot;success&quot;: True, &quot;data&quot;: result}<br>    except AttributeError as e:<br>        return {&quot;success&quot;: False, &quot;error&quot;: f&quot;خطأ محدد: {str(e)}&quot;}<br>    except Exception as e:<br>        return {&quot;success&quot;: False, &quot;error&quot;: f&quot;خطأ عام: {str(e)}&quot;}</pre><h3>✅ 2. التحقق من البيانات</h3><pre>def validate_junction(junction_id, elevation, demand):<br>    &quot;&quot;&quot;التحقق من بيانات العقدة&quot;&quot;&quot;<br>    if not junction_id:<br>        return False, &quot;معرف العقدة مطلوب&quot;<br>    if not isinstance(elevation, (int, float)):<br>        return False, &quot;يجب أن يكون الارتفاع رقمًا&quot;<br>    if not isinstance(demand, (int, float)):<br>        return False, &quot;يجب أن يكون الطلب رقمًا&quot;<br>    if elevation &lt; 0:<br>        return False, &quot;لا يمكن أن يكون الارتفاع سالبًا&quot;<br>    if demand &lt; 0:<br>        return False, &quot;لا يمكن أن يكون الطلب سالبًا&quot;</pre><pre>    return True, &quot;صالح&quot;</pre><h3>✅ 3. استخدام التسجيل</h3><pre>import logging<br>import os</pre><pre># إعداد التسجيل<br>logger = logging.getLogger(&quot;MyPlugin&quot;)<br>logger.setLevel(logging.DEBUG)</pre><pre>log_file = os.path.join(os.path.dirname(__file__), &quot;plugin.log&quot;)<br>handler = logging.FileHandler(log_file, encoding=&#39;utf-8&#39;)<br>formatter = logging.Formatter(&#39;%(asctime)s - %(levelname)s - %(message)s&#39;)<br>handler.setFormatter(formatter)<br>logger.addHandler(handler)</pre><pre># الاستخدام<br>logger.info(&quot;بدأ المكون الإضافي&quot;)<br>logger.error(f&quot;فشل إنشاء العقدة: {str(e)}&quot;)</pre><h3>✅ 4. إدارة الإعدادات</h3><pre>import json<br>import os</pre><pre>class SettingsManager:<br>    def __init__(self, settings_file=None):<br>        self.settings_file = settings_file or &quot;settings.json&quot;<br>        self.settings = self.load()</pre><pre>    def load(self):<br>        &quot;&quot;&quot;تحميل الإعدادات&quot;&quot;&quot;<br>        defaults = {<br>            &quot;option1&quot;: True,<br>            &quot;option2&quot;: 100,<br>            &quot;option3&quot;: &quot;value&quot;,<br>        }</pre><pre>        if os.path.exists(self.settings_file):<br>            try:<br>                with open(self.settings_file, &#39;r&#39;, encoding=&#39;utf-8&#39;) as f:<br>                    defaults.update(json.load(f))<br>            except:<br>                pass</pre><pre>        return defaults</pre><pre>    def save(self):<br>        &quot;&quot;&quot;حفظ الإعدادات&quot;&quot;&quot;<br>        with open(self.settings_file, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f:<br>            json.dump(self.settings, f, indent=2, ensure_ascii=False)</pre><pre>    def get(self, key, default=None):<br>        return self.settings.get(key, default)</pre><pre>    def set(self, key, value):<br>        self.settings[key] = value<br>        self.save()</pre><h3>✅ 5. التوثيق</h3><pre>def create_element(project, element_type, element_id, **kwargs):<br>    &quot;&quot;&quot;<br>    إنشاء عنصر جديد في الشبكة</pre><pre>    المعاملات:<br>        project: مشروع EPANET<br>        element_type: نوع العنصر (junction، pipe، pump، tank، reservoir)<br>        element_id: معرف العنصر<br>        **kwargs: خصائص العنصر</pre><pre>    العائد:<br>        dict: {<br>            &quot;success&quot;: bool,<br>            &quot;message&quot;: str,<br>            &quot;element_id&quot;: str<br>        }</pre><pre>    الاستثناءات:<br>        ValueError: إذا كان element_type غير صالح<br>    &quot;&quot;&quot;<br>    pass</pre><h3>الخاتمة</h3><p>يغطي هذا الدليل الأساسيات اللازمة لإنشاء مكونات إضافية احترافية لـ EPANET-UI. باستخدام هذه الأدوات، يمكنك:</p><p><strong>توسيع قدرات البرنامج</strong> عن طريق إضافة ميزات مخصصة</p><p><strong>أتمتة المهام المتكررة</strong> لتوفير الوقت والجهد</p><p><strong>التكامل مع مكتبات Python</strong> للحصول على قدرات متقدمة</p><p><strong>تحسين سير عمل التحليل</strong> باستخدام خوارزميات مخصصة</p><h3>🔗 موارد إضافية</h3><p>لمزيد من المعلومات والتحديثات، يمكنك الرجوع إلى:</p><p><strong>كود مصدر EPANET-UI:</strong> على GitHub</p><p><strong>وثائق EPANET الرسمية:</strong> من موقع EPA</p><p><strong>أمثلة المكونات الإضافية الموجودة:</strong> في مجلد plugins/</p><p><strong>مكتبة EPyT:</strong> الوثائق الرسمية</p><p>💡 <strong>نصيحة أخيرة:</strong> جميع التعديلات التي يتم إجراؤها عبر المكونات الإضافية تطبق مباشرة على المشروع المفتوح. احفظ دائمًا عملك قبل التعديلات الرئيسية، واختبر المكونات الإضافية على نسخة اختبار قبل استخدامها في الإنتاج.</p><p><em>تم كتابة هذه المقالة لتوفير دليل شامل للمطورين الذين يرغبون في بناء مكونات إضافية لـ EPANET-UI. إذا كان لديك أي أسئلة أو استفسارات، فلا تتردد في التواصل أو ترك تعليق!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2749b7fb428" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Journey of Developing Flex Reminder: When a Backend Developer Teams Up with AI]]></title>
            <link>https://medium.com/@saadmoooooha2000/the-journey-of-developing-flex-reminder-when-a-backend-developer-teams-up-with-ai-427cc331cc07?source=rss-d8240f0f2bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/427cc331cc07</guid>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[prog]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[محمد ساعد]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 12:05:46 GMT</pubDate>
            <atom:updated>2025-10-17T12:07:37.895Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Beginning: A Personal Problem Turns into a Project</h3><p>“Let me save this video for later…” “I’ll add this article to my list…”<br> How many times have you said that — and never gone back?</p><p>That was my struggle. My “saved” lists kept growing endlessly, while valuable content got buried under good intentions.<br> As a backend developer, I didn’t have the mobile development expertise to build the solution myself — until AI opened a new door.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*XcdHayQ-zwzkkDV127DT-w.png" /></figure><p><a href="https://play.google.com/store/apps/details?id=com.saadmohammed2000.flex_reminder"><strong>Flex Reminder</strong> </a>was born from that need: an app that gathers all the content I want to revisit and uses AI to determine the best time to remind me about it — smartly and repeatedly — until I actually open it.<br> No more forgotten lists.</p><h3>The Strategy: Dividing the Work Between AI Platforms</h3><p>Being solely a backend developer posed a major challenge:<br> How could I build a professional Flutter app with no prior experience?</p><p>The solution was to strategically leverage the strengths of different AI platforms:</p><h3>1. Claude: The Thinker and Architect</h3><p><strong>Why Claude?</strong><br> From my experience, Claude excels at complex reasoning in programming.<br> Its ability to understand architectural problems and detect logical issues is unmatched.</p><p><strong>How I Used It:</strong></p><ul><li><strong>Architectural Planning:</strong> Designing the app’s structure and choosing the right state management system.</li><li><strong>Feature Selection:</strong> Deciding which features were essential and which could be postponed.</li><li><strong>Debugging:</strong> When something broke, Claude would analyze the code and pinpoint the cause precisely.</li><li><strong>Logic Review:</strong> Ensuring the business logic was efficient and consistent.</li></ul><p><strong>The Challenge with Claude:</strong><br> Claude tends to produce concise, summarized responses — great for planning and reasoning, but not ideal for writing full code files.<br> I needed another partner for hands-on implementation.</p><h3>2. Gemini: The Executor and Code Engine</h3><p><strong>Why Gemini?</strong><br> Here’s the clever part: Flutter is built by Google — and so is Gemini.<br> That means Gemini has deeper, more up-to-date knowledge of Flutter and its packages.</p><p><strong>How I Used It:</strong><br> Once I planned with Claude, I transferred the requirements and architecture decisions to Gemini:</p><ul><li><strong>Full Code Generation:</strong> Gemini wrote complete Dart files with detailed structure.</li><li><strong>Flutter Widgets Expertise:</strong> It had excellent understanding of the latest widgets and Flutter best practices.</li><li><strong>Package Integration:</strong> Gemini knew exactly how to implement Provider, Riverpod, and other common packages.</li></ul><p><strong>Personal Experience:</strong><br> The transition between Claude for planning and Gemini for execution was surprisingly smooth — like having a senior architect (Claude) and a skilled developer (Gemini) on the same team.</p><h3>3. FlutLab: The Beginner-Friendly Development Environment</h3><p><strong>Why FlutLab?</strong><br> As a Flutter beginner, the last thing I wanted was to spend days setting up Android Studio, SDKs, and emulators.</p><p><strong>What FlutLab Offered:</strong></p><ul><li><strong>Instant Environment:</strong> No installation, no setup — just open the browser and start coding.</li><li><strong>Web Emulator:</strong> I could instantly preview the app in a browser without needing a phone or Android emulator.</li><li><strong>Accessibility:</strong> I could work anywhere, from any device, as long as I had internet.</li></ul><p><strong>The Achievement:</strong><br> I managed to complete <strong>about 70% of the app</strong> using FlutLab — building the UI, the basic state management, and the core features.</p><p><strong>The Limitations:</strong><br> Once development advanced, I needed features beyond FlutLab’s capabilities:</p><ul><li><strong>Firebase Messaging:</strong> To send reminders to users.</li><li><strong>Firebase Auth:</strong> For user account management.</li><li><strong>Real Device Testing:</strong> Essential for real-world validation.</li></ul><p>While perfect for beginners, FlutLab wasn’t built for deep cloud integrations.</p><h3>4. Firebase AI Studio: The Game Changer</h3><p><strong>Why Switch?</strong><br> As development progressed, integrating Firebase became essential.<br> <strong>Firebase AI Studio</strong> (formerly Firebase Extensions, now part of Google Cloud AI) provided the next-level tools I needed.</p><p><strong>New Capabilities:</strong></p><ul><li><strong>Direct Firebase Integration:</strong> Smooth connection with Cloud Messaging, Auth, and Firestore.</li><li><strong>Broader Testing Environment:</strong> Realistic push notification and authentication testing.</li><li><strong>Advanced Development Tools:</strong> Better debugging, clearer logs, and production-ready deployment.</li></ul><p><strong>Personal Experience:</strong><br> Moving to Firebase AI Studio felt like stepping from the training field into a professional stadium.<br> Suddenly, the app could send real notifications, manage real users, and behave like a true product.</p><p><strong>Bonus:</strong><br> Because Firebase AI Studio is part of Google’s ecosystem, integration with Gemini became seamless — I could now use it to write Cloud Functions, configure Firebase Rules, and optimize Firestore queries.</p><h3>Technical Side: Challenges and Solutions</h3><h3>Challenge 1: State Management</h3><p><strong>The Problem:</strong> As a backend developer, concepts like StatefulWidget and Provider were new territory.<br> <strong>The Solution:</strong> I used Claude to understand the differences between Provider, Riverpod, and Bloc, then asked Gemini to write a full implementation for the chosen method.</p><h3>Challenge 2: UI/UX Design</h3><p><strong>The Problem:</strong> I had no background in interface design.<br> <strong>The Solution:</strong> Claude helped me study best practices for productivity apps, while Gemini translated those ideas into functional Flutter widgets.</p><h3>Challenge 3: The Smart Reminder Algorithm</h3><p><strong>The Problem:</strong> How can the app determine the <em>optimal</em> time to remind the user?<br> <strong>The Solution:</strong></p><ul><li>Claude designed the logic, factoring in user free time, content priority, and deferral frequency.</li><li>Gemini coded the algorithm in Dart.</li><li>Firebase AI Studio executed scheduled functions to trigger reminders at the right times.</li></ul><h3>Challenge 4: Firebase Integration</h3><p><strong>The Problem:</strong> FlutLab couldn’t properly test Firebase Auth or Messaging.<br> <strong>The Solution:</strong><br> Transitioning to Firebase AI Studio allowed me to:</p><ul><li>Configure Firebase with proper credentials and settings.</li><li>Test push notifications on real devices.</li><li>Apply Security Rules to protect user data.</li></ul><h3>Lessons Learned: Tips for Backend Developers Entering Mobile</h3><h3>1. Choose the Right Platform for Each Stage</h3><ul><li><strong>FlutLab</strong> → Perfect for prototyping and early-stage UI work.</li><li><strong>Firebase AI Studio</strong> or <strong>local environment</strong> → Essential for advanced integrations.</li></ul><h3>2. Leverage Each AI’s Strengths</h3><ul><li><strong>Claude</strong> → For planning, architecture, and debugging.</li><li><strong>Gemini</strong> → For implementation and Google-specific technologies.</li></ul><h3>3. Don’t Fear Switching Tools</h3><p>Moving from FlutLab to Firebase AI Studio wasn’t failure — it was natural progression.<br> Each tool served its purpose at the right time.</p><h3>4. Learn the Core Concepts</h3><p>Even with AI help, understanding the fundamentals (Widgets, State, Lifecycle) is critical to asking the right questions.</p><h3>5. Test on Real Devices Early</h3><p>Simulators are useful, but real devices reveal issues you won’t see in web previews.</p><h3>Conclusion: The Future of AI-Assisted Development</h3><p><strong>Flex Reminder</strong> wouldn’t exist without AI.<br> As a backend developer with no Flutter experience, I was able to build a fully functional app thanks to:</p><ol><li><strong>Strategic Planning with Claude</strong> — for architecture and problem-solving.</li><li><strong>Fast Implementation with Gemini</strong> — for actual Flutter code and Google integration.</li><li><strong>Easy Start with FlutLab</strong> — for beginner-friendly development.</li><li><strong>Professional Finish with Firebase AI Studio</strong> — for full-scale integration and deployment.</li></ol><p>This experience proves that entry barriers into new domains are lower than ever.<br> AI isn’t just a tool — it’s a true collaborator that bridges skill gaps and turns ideas into reality.</p><p><strong>Final Message:</strong><br> If you have an idea worth building, don’t let lack of expertise hold you back.<br> The tools are available, the knowledge is accessible, and AI is ready to help you — start today.</p><p><strong>Note:</strong> The app is still under development — the journey continues.<br> Every day brings new lessons and challenges, each unlocking fresh, creative solutions.<br> That’s the joy of building in the age of AI.</p><p><a href="https://play.google.com/store/apps/details?id=com.saadmohammed2000.flex_reminder">https://play.google.com/store/apps/details?id=com.saadmohammed2000.flex_reminder</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*XcdHayQ-zwzkkDV127DT-w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=427cc331cc07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[رحلة تطوير Flex Reminder: عندما يتعاون مطور Backend مع الذكاء الاصطناعي]]></title>
            <link>https://medium.com/@saadmoooooha2000/%D8%B1%D8%AD%D9%84%D8%A9-%D8%AA%D8%B7%D9%88%D9%8A%D8%B1-flex-reminder-%D8%B9%D9%86%D8%AF%D9%85%D8%A7-%D9%8A%D8%AA%D8%B9%D8%A7%D9%88%D9%86-%D9%85%D8%B7%D9%88%D8%B1-backend-%D9%85%D8%B9-%D8%A7%D9%84%D8%B0%D9%83%D8%A7%D8%A1-%D8%A7%D9%84%D8%A7%D8%B5%D8%B7%D9%86%D8%A7%D8%B9%D9%8A-3da481ec14da?source=rss-d8240f0f2bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3da481ec14da</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[saas]]></category>
            <dc:creator><![CDATA[محمد ساعد]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 12:04:08 GMT</pubDate>
            <atom:updated>2025-10-17T12:04:08.905Z</atom:updated>
            <content:encoded><![CDATA[<h3>البداية: مشكلة شخصية تتحول إلى مشروع</h3><p>“أحفظ هذا الفيديو لأشاهده لاحقاً”… “سأضع هذا المقال في القائمة”… كم مرة قلت هذا ولم تعد أبداً؟</p><p>هذه كانت معاناتي الشخصية. قوائم المحفوظات تتضخم، والمحتوى القيّم يختفي في زحام النوايا الحسنة. ومع أنني مطور Backend، لم تكن خبرتي في تطوير تطبيقات الموبايل كافية لبناء الحل بنفسي. لكن الذكاء الاصطناعي فتح لي باباً جديداً.</p><p><a href="https://play.google.com/store/apps/details?id=com.saadmohammed2000.flex_reminder"><strong>Flex Reminder</strong></a> ولد من هذه الحاجة: تطبيق يجمع كل المحتوى الذي أريد العودة إليه، ويستخدم الذكاء الاصطناعي ليحدد الوقت الأنسب لتذكيري به، بشكل متكرر وذكي حتى أفتحه فعلياً. لا مزيد من القوائم المنسية.</p><h3>الاستراتيجية: تقسيم العمل بين منصات الذكاء الاصطناعي</h3><p>كوني مطور Backend فقط، واجهت تحدياً حقيقياً: كيف أبني تطبيق Flutter احترافي دون خبرة سابقة؟ الحل كان في استخدام نقاط قوة كل منصة ذكاء اصطناعي بشكل استراتيجي:</p><h3>1. Claude: العقل المفكر والمخطط</h3><p><strong>لماذا Claude؟</strong> من تجربتي، Claude هو الأقوى في التفكير البرمجي المعقد. قدرته على فهم المشاكل المعمارية واكتشاف الأخطاء لا مثيل لها.</p><p><strong>كيف استخدمته؟</strong></p><ul><li><strong>التخطيط المعماري</strong>: رسم بنية التطبيق، وتحديد الـ State Management المناسب</li><li><strong>اختيار الـ Features</strong>: تقييم أي ميزة تستحق التنفيذ وأيها يمكن تأجيلها</li><li><strong>اكتشاف الأخطاء</strong>: عندما يتعطل شيء ما، Claude يحلل الكود ويحدد المشكلة بدقة</li><li><strong>مراجعة المنطق</strong>: التأكد من أن الـ Business Logic منطقية وفعالة</li></ul><p><strong>التحدي مع Claude:</strong> المشكلة الوحيدة كانت أن Claude يميل لإنتاج نصوص مختصرة ومقتضبة. رائع للتخطيط والتفكير، لكن لا يكفي لكتابة ملفات كود كاملة. كنت بحاجة لشريك آخر للتنفيذ الفعلي.</p><h3>2. Gemini: محرك الكتابة والتنفيذ</h3><p><strong>لماذا Gemini؟</strong> هنا تكمن الحيلة: Flutter هو منتج من Google، وGemini من Google أيضاً. هذا يعني أن Gemini لديه معرفة أعمق وأكثر تحديثاً بـ Flutter والـ packages المرتبطة به.</p><p><strong>كيف استخدمته؟</strong> بعد أن أخطط مع Claude، أنقل القرارات والمتطلبات إلى Gemini:</p><ul><li><strong>كتابة الكود الكامل</strong>: Gemini يكتب ملفات Dart كاملة بتفاصيلها</li><li><strong>استخدام Flutter Widgets</strong>: معرفته بأحدث الـ widgets والـ best practices في Flutter ممتازة</li><li><strong>Integration مع الـ Packages</strong>: يعرف كيف يدمج packages مثل Provider، Riverpod، أو أي حلول أخرى</li></ul><p><strong>التجربة الشخصية:</strong> كان الانتقال بين Claude للتفكير وGemini للتنفيذ سلساً بشكل مدهش. كأنني أملك مستشاراً معمارياً (Claude) ومطور تنفيذي (Gemini) في فريقي.</p><h3>3. FlutLab: البيئة التطويرية للمبتدئين</h3><p><strong>لماذا FlutLab؟</strong> كمبتدئ في Flutter، آخر شيء أريده هو قضاء أيام في إعداد البيئة التطويرية، تثبيت Android Studio، SDK، المحاكيات… إلخ.</p><p><strong>ما قدمته FlutLab:</strong></p><ul><li><strong>بيئة جاهزة فوراً</strong>: لا تثبيت، لا إعدادات معقدة — فقط افتح المتصفح وابدأ البرمجة</li><li><strong>محاكي Web</strong>: أرى التطبيق يعمل مباشرة على الويب بدون الحاجة لهاتف أو محاكي Android</li><li><strong>سهولة الوصول</strong>: أعمل من أي مكان، من أي جهاز، طالما لدي إنترنت</li></ul><p><strong>الإنجاز:</strong> نجحت في إنجاز <strong>70% من التطبيق</strong> على FlutLab. كانت مثالية للمراحل الأولى: بناء الـ UI، State Management الأساسي، والـ features الأساسية.</p><p><strong>حدود المنصة:</strong> عندما وصلت للمراحل المتقدمة، ظهرت الحاجة لميزات أكثر تعقيداً:</p><ul><li><strong>Firebase Messaging</strong>: لإرسال التذكيرات للمستخدمين</li><li><strong>Firebase Auth</strong>: لإدارة حسابات المستخدمين</li><li><strong>اختبار حقيقي</strong>: الحاجة لتجربة التطبيق على أجهزة حقيقية</li></ul><p>FlutLab، رغم روعتها للمبتدئين، لم تكن مصممة لهذا المستوى من التكامل مع الخدمات السحابية.</p><h3>4. Firebase AI Studio: القفزة النوعية</h3><p><strong>لماذا الانتقال؟</strong> في مرحلة متقدمة من التطوير، أصبح الربط مع Firebase ضرورياً لا خياراً. Firebase AI Studio (المعروف سابقاً باسم Firebase Extensions أو جزء من Google Cloud AI) قدم لي:</p><p><strong>الميزات الجديدة:</strong></p><ul><li><strong>تكامل Firebase مباشر</strong>: ربط سلس مع Firebase Cloud Messaging، Auth، Firestore</li><li><strong>بيئة أوسع للتجربة</strong>: القدرة على اختبار الـ push notifications والـ authentication بشكل واقعي</li><li><strong>أدوات تطوير متقدمة</strong>: Debugging أفضل، logs أوضح، وإمكانية Deploy حقيقية</li></ul><p><strong>التجربة الشخصية:</strong> الانتقال كان بمثابة الانتقال من “الملعب التدريبي” إلى “الملعب الاحترافي”. فجأة، التطبيق أصبح قادراً على إرسال تذكيرات حقيقية، إدارة مستخدمين حقيقيين، والعمل كمنتج فعلي.</p><p><strong>ميزة إضافية:</strong> كون Firebase AI Studio جزء من نظام Google البيئي، التكامل مع Gemini كان أسهل. أستطيع الآن استخدام Gemini لكتابة Cloud Functions، إعداد Firebase Rules، وحتى تحسين الـ queries.</p><h3>الجانب التقني: التحديات والحلول</h3><h3>التحدي الأول: State Management</h3><p><strong>المشكلة:</strong> كمطور Backend، مفاهيم مثل StatefulWidget و Provider كانت غريبة.</p><p><strong>الحل:</strong> استخدمت Claude لفهم الاختلافات بين الحلول المختلفة (Provider vs Riverpod vs Bloc)، ثم طلبت من Gemini كتابة implementation كامل للحل المختار.</p><h3>التحدي الثاني: UI/UX Design</h3><p><strong>المشكلة:</strong> لا خبرة لي في تصميم واجهات المستخدم.</p><p><strong>الحل:</strong> استخدمت Claude لمراجعة أفضل الممارسات في تصميم تطبيقات الإنتاجية، ثم Gemini لتحويل هذه الأفكار إلى Flutter widgets فعلية.</p><h3>التحدي الثالث: الخوارزمية الذكية للتذكير</h3><p><strong>المشكلة:</strong> كيف يحدد التطبيق الوقت “الأنسب” للتذكير؟</p><p><strong>الحل:</strong></p><ul><li>Claude صمم الخوارزمية بناءً على عوامل متعددة: أوقات فراغ المستخدم، أولوية المحتوى، عدد مرات التأجيل السابقة</li><li>Gemini كتب الكود الذي ينفذ هذه الخوارزمية في Dart</li><li>Firebase AI Studio ساعد في تنفيذ scheduled functions لإطلاق التذكيرات في الوقت المحدد</li></ul><h3>التحدي الرابع: Firebase Integration</h3><p><strong>المشكلة:</strong> FlutLab لم تكن كافية لاختبار Firebase Messaging و Auth بشكل حقيقي.</p><p><strong>الحل:</strong> الانتقال إلى Firebase AI Studio أتاح:</p><ul><li><strong>إعداد Firebase بشكل صحيح</strong>: مع جميع الـ credentials والـ configurations</li><li><strong>اختبار الـ Push Notifications</strong>: على أجهزة حقيقية</li><li><strong>تطبيق Security Rules</strong>: لحماية بيانات المستخدمين</li></ul><h3>الدروس المستفادة: نصائح لمطوري Backend الراغبين في بناء تطبيقات موبايل</h3><h3>1. اختر المنصة المناسبة للمرحلة المناسبة</h3><ul><li><strong>FlutLab</strong> رائعة للبداية والـ prototyping</li><li><strong>Firebase AI Studio</strong> أو <strong>بيئة محلية</strong> ضرورية للمراحل المتقدمة</li></ul><h3>2. استغل نقاط قوة كل أداة ذكاء اصطناعي</h3><ul><li><strong>Claude</strong>: للتخطيط، التفكير المعماري، واكتشاف الأخطاء</li><li><strong>Gemini</strong>: للكتابة التنفيذية، خاصة في تقنيات Google</li></ul><h3>3. لا تخف من النقل بين الأدوات</h3><p>الانتقال من FlutLab إلى Firebase AI Studio لم يكن فشلاً، بل تطوراً طبيعياً. كل أداة خدمت غرضها في الوقت المناسب.</p><h3>4. تعلم المفاهيم الأساسية</h3><p>حتى مع الذكاء الاصطناعي، فهم مفاهيم Flutter الأساسية (Widgets، State، Lifecycle) كان ضرورياً لطرح الأسئلة الصحيحة.</p><h3>5. اختبر على الـ Real Devices مبكراً</h3><p>المحاكيات جيدة، لكن الاختبار على هواتف حقيقية يكشف مشاكل لن تراها على الويب.</p><h3>الخلاصة: مستقبل التطوير التعاوني مع الذكاء الاصطناعي</h3><p>تطبيق <strong>Flex Reminder</strong> لم يكن ليرى النور لولا الذكاء الاصطناعي. كمطور Backend بدون خبرة في Flutter، استطعت بناء تطبيق وظيفي بنسبة إنجاز عالية عبر:</p><ol><li><strong>التخطيط الاستراتيجي مع Claude</strong>: للبنية المعمارية وحل المشاكل المعقدة</li><li><strong>التنفيذ السريع مع Gemini</strong>: لكتابة الكود الفعلي بمعرفة عميقة بـ Flutter</li><li><strong>البدء السهل مع FlutLab</strong>: بيئة صديقة للمبتدئين بدون تعقيدات</li><li><strong>الاحترافية مع Firebase AI Studio</strong>: للتكامل الكامل والإنتاج الفعلي</li></ol><p>هذه التجربة تثبت أن حواجز الدخول لمجالات جديدة أصبحت أقل من أي وقت مضى. الذكاء الاصطناعي ليس مجرد أداة مساعدة، بل شريك حقيقي يمكنه سد الفجوات المعرفية وتحويل الأفكار إلى واقع.</p><p><strong>الرسالة النهائية:</strong> إذا كانت لديك فكرة ومشكلة تستحق الحل، لا تدع نقص الخبرة في تقنية معينة يوقفك. الأدوات متاحة، المعرفة في متناول اليد، والذكاء الاصطناعي جاهز لمساعدتك. ابدأ اليوم.</p><p><strong>ملاحظة:</strong> التطبيق لا يزال قيد التطوير، والرحلة مستمرة. كل يوم أتعلم شيئاً جديداً، وكل تحدٍ يفتح أبواباً لحلول مبتكرة. هذه هي متعة البناء في عصر الذكاء الاصطناعي.</p><p><a href="https://play.google.com/store/apps/details?id=com.saadmohammed2000.flex_reminder">https://play.google.com/store/apps/details?id=com.saadmohammed2000.flex_reminder</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*XcdHayQ-zwzkkDV127DT-w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3da481ec14da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chrome extension to Keep your Reading list empty]]></title>
            <link>https://medium.com/@saadmoooooha2000/chrome-extension-to-keep-your-reading-list-empty-c46c0a45f233?source=rss-d8240f0f2bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c46c0a45f233</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[saas]]></category>
            <dc:creator><![CDATA[محمد ساعد]]></dc:creator>
            <pubDate>Thu, 22 May 2025 08:26:25 GMT</pubDate>
            <atom:updated>2025-05-22T08:26:25.247Z</atom:updated>
            <content:encoded><![CDATA[<ol><li>I noticed that I save dozens of posts weekly across different platforms, but only return to about 10% of them.</li><li>I developed a smart solution powered by artificial intelligence to help me retrieve this forgotten content at appropriate times.</li><li>I created a system consisting of a browser extension for computers and an Android app for mobile phones.</li><li>I designed the system to analyze saved content types, monitor my free time, and learn from my interaction statistics.</li><li>I added features like smart notifications, automatic classification, priority analysis, and cross-device synchronization.</li><li>I faced technical challenges regarding data privacy and overcame them by processing data locally and using advanced encryption techniques.</li><li>I plan to develop the system by adding support for more platforms and improving machine learning algorithms.</li><li>I will add social features allowing users to share useful content with friends and analytical reports about content consumption habits.</li><li>My goal isn’t just a technical tool, but redefining our relationship with digital information and transforming “saved lists” from digital graveyards into organized personal libraries.</li><li>I invite you to try the extension and application through the provided link and welcome your feedback and suggestions to improve this tool.</li></ol><p>Try it : <a href="https://bit.ly/42ZDvlA">https://bit.ly/42ZDvlA</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZxBAoXNpLlU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZxBAoXNpLlU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZxBAoXNpLlU%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/04bf7cacba1bf062683ffd4448b8b841/href">https://medium.com/media/04bf7cacba1bf062683ffd4448b8b841/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c46c0a45f233" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing Smart Solutions for Forgotten Saved Content: The Journey of Creating an AI-Powered…]]></title>
            <link>https://medium.com/@saadmoooooha2000/developing-smart-solutions-for-forgotten-saved-content-the-journey-of-creating-an-ai-powered-d5f2e464fa46?source=rss-d8240f0f2bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5f2e464fa46</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[محمد ساعد]]></dc:creator>
            <pubDate>Thu, 15 May 2025 10:38:20 GMT</pubDate>
            <atom:updated>2025-05-15T10:39:44.543Z</atom:updated>
            <content:encoded><![CDATA[<h3>Developing Smart Solutions for Forgotten Saved Content: The Journey of Creating an AI-Powered Reminder Tool</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/98/1*MHR21piAI5_v1ci7w00Lzg.png" /></figure><p>In our contemporary digital world, we all face a common problem: we save articles, videos, and posts that interest us, promising ourselves to return to them later, but most often, these contents get buried deep in our saved lists and we never return to them. This problem pushed me to create an innovative solution that relies on artificial intelligence to help us retrieve these forgotten treasures at the right times.</p><h3>The Problem: Endless and Useless Saved Lists</h3><p>I began my journey with this project when I noticed that I save dozens of posts weekly on different platforms — scientific articles on tech news sites, educational videos on YouTube, useful posts on LinkedIn and Twitter — but the percentage of what I actually return to from these saved items doesn’t exceed 10%. The problem isn’t a lack of interest, but rather the absence of a smart system that reminds me of this content at the appropriate time, when I’m free and ready to check it out.</p><h3>The Solution: Browser Extension and Android App Powered by AI</h3><p>I decided to develop a smart solution consisting of two parts:</p><ol><li><strong>Browser Extension</strong>: Works on computers and integrates with popular browsers like Chrome, Firefox, and Edge.</li><li><strong>Android App</strong>: Provides the same functionality on mobile phones, ensuring a seamless experience across different devices.</li></ol><h3>How Does the System Work?</h3><p>The system relies on advanced artificial intelligence algorithms to analyze three main elements:</p><h3>1. Analysis of Saved Content Type</h3><p>When a user saves a post, article, or video, the system analyzes:</p><ul><li>The nature of the content (educational, entertainment, news, professional)</li><li>Its degree of importance and relevance to the user’s interests</li></ul><h3>2. Monitoring Free Time</h3><p>The system gradually learns:</p><ul><li>The user’s daily patterns</li><li>Periods when they are active online</li><li>Their preferred times for consuming certain types of content (for example, morning articles, evening videos)</li></ul><h3>3. Analysis of User Interaction Statistics</h3><p>The system collects data about:</p><ul><li>Types of content the user tends to actually return to</li><li>Times when they respond better to notifications</li><li>Their preferences in how they consume different content</li></ul><h3>Main Features of the System</h3><ol><li><strong>Smart Notifications</strong>: Arrive at appropriate times and suggest suitable content for the user’s current circumstances.</li><li><strong>Automatic Classification</strong>: Categorizes saved content into logical categories that make it easier to access later.</li><li><strong>Priority Analysis</strong>: Recognizes the most important content and prioritizes it in notifications.</li><li><strong>Cross-Device Synchronization</strong>: Ensures the user can access their saved items from any device at any time.</li></ol><h3>Technical Challenges and How to Overcome Them</h3><p>I faced several challenges while developing this system:</p><ol><li><strong>Integration with Various Platforms</strong>: I designed application programming interfaces (APIs) that allow integration with most social media platforms and news sites.</li></ol><h3>Future of the Project</h3><p>I plan to develop the system by adding:</p><ol><li><strong>Support for More Platforms</strong>: Expanding the system’s scope to include additional applications and services.</li><li><strong>Improving Machine Learning Algorithms</strong>: Using larger datasets to train more accurate models.</li><li><strong>Social Features</strong>: Allowing users to share useful content with their friends and follow others’ recommendations.</li><li><strong>Analytical Reports</strong>: Providing users with statistics about their content consumption habits and helping them improve their time management.</li></ol><h3>Conclusion</h3><p>In the information age, the problem isn’t a lack of content, but rather our ability to consume it effectively. This project isn’t just a technical tool, but an attempt to redefine our relationship with digital information, and transform “saved lists” from digital content graveyards into organized and useful personal libraries.</p><p>I invite you to try the extension and application through the link: <a href="https://lnkd.in/eyzxgrbE"><strong>https://lnkd.in/eyzxgrbE</strong></a> and welcome your feedback and suggestions to develop this tool and make it more useful for everyone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5f2e464fa46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing a Chrome extension to enhance Claude.ai using PDF contextual memory]]></title>
            <link>https://medium.com/@saadmoooooha2000/developing-a-chrome-extension-to-enhance-claude-ai-using-pdf-contextual-memory-54b5184c7aeb?source=rss-d8240f0f2bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/54b5184c7aeb</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech-innovation]]></category>
            <dc:creator><![CDATA[محمد ساعد]]></dc:creator>
            <pubDate>Sat, 02 Nov 2024 23:52:41 GMT</pubDate>
            <atom:updated>2024-11-12T08:34:42.919Z</atom:updated>
            <content:encoded><![CDATA[<h3>Developing a RAG Chrome extension for feeding Claude.ai with large PDFs</h3><p>في عالم الذكاء الاصطناعي المتسارع، تظل قدرة النماذج اللغوية على فهم السياق محدودة بحجم نافذة السياق المتاحة لها.</p><p>في هذا المقال، سأشارككم تجربة عملية في تطوير إضافة لمتصفح</p><p>Chrome تهدف إلى تعزيز قدرات Claude.ai من خلال منحه ذاكرة سياقية ديناميكية.</p><h3>المشكلة والحل</h3><p>تتمثل المشكلة الرئيسية في أن نماذج الذكاء الاصطناعي مثل Claude لا تمتلك القدرة على الاحتفاظ بسياق طويل المدى من المحادثات السابقة أو الوثائق المرجعية. لحل هذه المشكلة، قمت بتطوير إضافة تقوم بإنشاء “ذاكرة خارجية” باستخدام تقنيات معالجة اللغة الطبيعية المتقدمة.</p><h4>الدليل التفصيلي لإنشاء إضافة Chrome للذاكرة السياقية</h4><p>في هذا الدليل، سنتعلم كيفية إنشاء إضافة Chrome تقوم بتعزيز قدرات نماذج الذكاء الاصطناعي من خلال إضافة ذاكرة سياقية. سنشرح كل جزء من الكود بالتفصيل مع توضيح كيفية عمله.</p><h3>1. هيكل المشروع</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*vdsyCUfWawq0nxlozF6edg.png" /></figure><p>أولاً، نحتاج إلى إنشاء الملفات الأساسية للإضافة:</p><pre>extension/<br>├── manifest.json<br>├── background.js<br>├── content.js<br>├── popup.html<br>├── popup.js<br>└── pdf.worker.min.js</pre><pre>### manifest.json<br>{<br> &quot;manifest_version&quot;: 3,<br> &quot;name&quot;: &quot;Context Memory Extension&quot;,<br> &quot;version&quot;: &quot;1.0&quot;,<br> &quot;permissions&quot;: [<br> &quot;storage&quot;,<br> &quot;activeTab&quot;<br> ],<br> &quot;host_permissions&quot;: [<br> &quot;https://api.openai.com/*&quot;,<br> &quot;https://*.pinecone.io/*&quot;,<br> &quot;https://claude.ai/*&quot;<br> ],<br> &quot;background&quot;: {<br> &quot;service_worker&quot;: &quot;background.js&quot;<br> },<br> &quot;content_scripts&quot;: [{<br> &quot;matches&quot;: [&quot;https://claude.ai/*&quot;],<br> &quot;js&quot;: [&quot;content.js&quot;]<br> }],<br> &quot;action&quot;: {<br> &quot;default_popup&quot;: &quot;popup.html&quot;<br> }<br>}</pre><h3>2. معالجة وتخزين البيانات</h3><h4>Embeddings المكون الأول: تحويل النص إلى</h4><p>`background.js`في ،OpenAI API نقوم بإنشاء دالة للتواصل مع :</p><pre>async function getEmbeddings(text) {<br> const response = await fetch(&#39;https://api.openai.com/v1/embeddings&#39;, {<br> method: &#39;POST&#39;,<br> headers: {<br> &#39;Authorization&#39;: `Bearer ${openAIApiKey}`,<br> &#39;Content-Type&#39;: &#39;application/json&#39;<br> },<br> body: JSON.stringify({<br> input: text,<br> model: &quot;text-embedding-ada-002&quot;<br> })<br> });<br>const data = await response.json();<br> return data.data[0].embedding;<br>}</pre><h4>المكون الثاني: تقسيم النصوص</h4><p>نحتاج إلى تقسيم النصوص الطويلة إلى أجزاء صغيرة لمعالجتها بشكل أفضل:</p><pre>function splitText(text, chunkSize = 1000) {<br> const chunks = [];<br> const sentences = text.match(/[^.!?]+[.!?]+/g) || [text];<br> let currentChunk = &#39;&#39;;<br>for (const sentence of sentences) {<br> if ((currentChunk + sentence).length &lt;= chunkSize) {<br> currentChunk += sentence;<br> } else {<br> if (currentChunk) chunks.push(currentChunk.trim());<br> currentChunk = sentence;<br> }<br> }<br> if (currentChunk) chunks.push(currentChunk.trim());<br> return chunks;<br>}</pre><h4>Pinecone المكون الثالث: التخزين في</h4><p>نقوم بإنشاء دوال للتعامل مع Pinecone:</p><pre>async function upsertVectors(vectors, namespace) {<br> const response = await fetch(`https://${pineconeIndexName}.svc.${pineconeEnvironment}.pinecone.io/vectors/upsert`, {<br> method: &#39;POST&#39;,<br> headers: {<br> &#39;Api-Key&#39;: pineconeApiKey,<br> &#39;Content-Type&#39;: &#39;application/json&#39;<br> },<br> body: JSON.stringify({<br> vectors: vectors,<br> namespace: namespace<br> })<br> });<br> return await response.json();<br>}<br>async function queryVectors(vector, namespace, topK = 5) {<br> const response = await fetch(`https://${pineconeIndexName}.svc.${pineconeEnvironment}.pinecone.io/query`, {<br> method: &#39;POST&#39;,<br> headers: {<br> &#39;Api-Key&#39;: pineconeApiKey,<br> &#39;Content-Type&#39;: &#39;application/json&#39;<br> },<br> body: JSON.stringify({<br> vector: vector,<br> namespace: namespace,<br> topK: topK,<br> includeMetadata: true<br> })<br> });<br> return await response.json();<br>}</pre><h3>3. معالجة الأسئلة وإضافة السياق</h3><h4>المكون الأول: تحليل الأسئلة</h4><p>نقوم بإنشاء صيغ مختلفة للسؤال لتحسين البحث:</p><pre>async function analyzeAndGenerateQuestions(question) {<br> const messages = [<br> { role: &quot;system&quot;, content: &quot;You are a helpful assistant.&quot; },<br> { role: &quot;user&quot;, content: `<br> generate 3 different versions of this question that capture the same intent: ${question}<br> Return the result in the following format: [&quot;version1&quot;, &quot;version2&quot;, &quot;version3&quot;]<br> `}<br> ];<br> <br> const response = await getChatCompletion(messages);<br> try {<br> const cleanResponse = response.replace(/\s+/g, &#39; &#39;).trim();<br> return JSON.parse(cleanResponse);<br> } catch (error) {<br> console.error(&#39;Error parsing response:&#39;, error);<br> return [question];<br> }<br>}</pre><h4>المكون الثاني: استرجاع السياق المناسب</h4><p>نقوم بالبحث عن أفضل سياق مناسب للسؤال:</p><pre>async function interceptQuestion(question, sessionId) {<br> const questionVersions = await analyzeAndGenerateQuestions(question);<br> let allResults = [];<br> <br> for (const version of questionVersions) {<br> const embedding = await getEmbeddings(version);<br> const results = await queryVectors(embedding, sessionId);<br> allResults = […allResults, …results.matches];<br> }<br>// إزالة التكرارات وترتيب النتائج حسب الصلة<br> const uniqueResults = Array.from(new Set(allResults.map(r =&gt; r.metadata.text)))<br> .map(text =&gt; allResults.find(r =&gt; r.metadata.text === text))<br> .sort((a, b) =&gt; b.score - a.score)<br> .slice(0, 5);<br>const contextualInfo = uniqueResults.map(r =&gt; r.metadata.text).join(&#39;\n&#39;);<br> return `Context: ${contextualInfo}\n\nQuestion: ${question}`;<br>}</pre><h3>4. التكامل مع واجهة المستخدم</h3><h4>content.js في</h4><p>نقوم بإنشاء آلية لاعتراض الأسئلة وتعديلها:</p><pre>async function handleEnterKey(event) {<br> if (event.key === &#39;Enter&#39; &amp;&amp; !event.isSimulated) {<br> event.stopPropagation();<br> event.preventDefault();<br> <br> const inputElement = document.querySelector(&#39;.ProseMirror.break-words&#39;);<br> if (inputElement) {<br> const originalText = inputElement.textContent;<br> const modifiedText = await modifyText(originalText);<br> <br> setInputText(inputElement, modifiedText);<br> simulateEnterKeydown(inputElement);<br> }<br> }<br>}<br>function setInputText(element, newText) {<br> element.innerHTML = `&lt;p&gt;${newText}&lt;/p&gt;`;<br> element.dispatchEvent(new Event(&#39;input&#39;, { bubbles: true }));<br>}</pre><h3>5. إدارة الجلسات</h3><h4>popup.js في</h4><p>نقوم بإدارة الجلسات وتحميل الملفات:</p><pre><br>function createNewSession() {<br> const sessionId = Date.now().toString();<br> chrome.storage.local.get({ sessions: [] }, (result) =&gt; {<br> const sessions = result.sessions;<br> sessions.push(sessionId);<br> chrome.storage.local.set({ sessions: sessions }, () =&gt; {<br> loadSessions();<br> setActiveSession(sessionId);<br> });<br> });<br>}<br>async function handlePDFUpload(event) {<br> if (!currentSession) {<br> updateStatus(&#39;الرجاء اختيار جلسة أولاً&#39;);<br> return;<br> }<br>const files = event.target.files;<br> for (let file of files) {<br> const pdfContent = await readFileAsArrayBuffer(file);<br> const text = await extractTextFromPDF(pdfContent);<br> await sendMessageToBackground({<br> action: &#39;processPDF&#39;,<br> text: text,<br> sessionId: currentSession<br> });<br> }<br>}<br></pre><h3>الخطوات النهائية للتنفيذ</h3><p>1. الحصول على المفاتيح المطلوبة:<br> — مفتاح API من OpenAI<br> — مفتاح API وإعدادات من Pinecone</p><p>2. تحميل الإضافة في Chrome:<br> — فتح chrome://extensions/<br> — تفعيل وضع المطور<br> — اختيار “Load unpacked” وتحديد مجلد الإضافة</p><p>3. إعداد Pinecone:<br> — إنشاء فهرس جديد بأبعاد 1536 (مناسب لنموذج OpenAI)<br> — تعيين البيئة والفهرس في الكود</p><h4>ملاحظات هامة للتطوير</h4><p>1. **الأمان**: <br> — احفظ المفاتيح بشكل آمن<br> — استخدم CORS بشكل صحيح<br> — تحقق من صحة المدخلات</p><p>2. **الأداء**:<br> — استخدم التخزين المؤقت للنتائج المتكررة<br> — قم بتحسين حجم الأجزاء النصية<br> — استخدم العمليات غير المتزامنة بحكمة</p><p>3. **قابلية التوسع**:<br> — نظم الكود في وحدات<br> — استخدم أنماط التصميم المناسبة<br> — وثق الكود بشكل جيد</p><h4>التحديات المحتملة وحلولها</h4><p>1. **حدود API**:<br> — تنفيذ آلية التحكم في المعدل<br> — التعامل مع الأخطاء بشكل مناسب<br> — تخزين النتائج مؤقتاً</p><p>2. **حجم البيانات**:<br> — تنفيذ التحميل التدريجي<br> — ضغط البيانات عند الحاجة<br> — إدارة الذاكرة بكفاءة</p><p>3. **توافق المتصفح**:<br> — اختبار على إصدارات مختلفة من Chrome<br> — التعامل مع الأخطاء المحددة للمتصفح<br> — توفير تجربة متسقة</p><h3>الخاتمة</h3><p>هذا الدليل يوفر الأساس لإنشاء إضافة قوية للذاكرة السياقية. يمكن تحسين الأداء والوظائف من خلال:<br>- إضافة المزيد من أنواع الملفات<br>- تحسين خوارزميات اختيار السياق<br>- إضافة واجهة مستخدم أكثر تقدماً<br>- تنفيذ المزيد من ميزات التخصيص</p><p>تذكر دائماً اختبار الإضافة بشكل شامل قبل الاستخدام في بيئة الإنتاج.</p><h3>المكونات التقنية</h3><h4>1. واجهة المستخدم (Popup)</h4><p>- إدارة الجلسات لتنظيم المراجع حسب المواضيع<br>- واجهة سهلة لتحميل وإدارة الملفات المرجعية<br>- عرض حالة المعالجة والتحديثات</p><h4>2. معالج الخلفية (Background)</h4><p>- التواصل مع APIs الخارجية (OpenAI وPinecone)<br>- معالجة النصوص وإنشاء المتجهات<br>- إدارة عمليات البحث والاسترجاع</p><h4>3. Content Script</h4><p>- مراقبة واجهة Claude.ai<br>- اعتراض وتعديل الأسئلة بشكل شفاف<br>- إعادة تقديم الأسئلة المعززة</p><h3>التقنيات المستخدمة</h3><p>- **واجهة برمجة OpenAI**: لإنشاء متجهات النصوص باستخدام نموذج text-embedding-ada-002<br>- **Pinecone**: قاعدة بيانات متخصصة في تخزين واسترجاع المتجهات<br>- **PDF.js**: لاستخراج النصوص من ملفات PDF<br>- **Chrome Extensions API**: لبناء الإضافة وإدارة التفاعلات مع المتصفح</p><h3>فوائد الإضافة</h3><p>1. تحسين دقة إجابات Claude من خلال توفير سياق أكثر صلة<br>2. إمكانية الاستفادة من مصادر معرفية خارجية في المحادثات<br>3. تنظيم المراجع في جلسات منفصلة حسب المواضيع<br>4. تجربة مستخدم سلسة لا تتطلب تدخلاً يدوياً</p><h4>الاستخدامات المحتملة</h4><p>- البحث العلمي والأكاديمي<br>- التوثيق التقني<br>- خدمة العملاء المعتمدة على الوثائق<br>- التعليم والتدريب</p><h4>الخطوات القادمة</h4><p>1. تحسين خوارزميات اختيار السياق المناسب<br>2. دعم المزيد من أنواع الملفات<br>3. إضافة خيارات تخصيص متقدمة<br>4. تحسين أداء معالجة الملفات الكبيرة</p><h3>الختام</h3><p>هذا المشروع يمثل خطوة في اتجاه تحسين قدرات نماذج الذكاء الاصطناعي من خلال منحها “ذاكرة خارجية” قابلة للتخصيص. مع تطور تقنيات الذكاء الاصطناعي، ستصبح مثل هذه الأدوات أكثر أهمية في تجسير الفجوة بين القدرات النظرية والاحتياجات العملية.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54b5184c7aeb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel , Filament php  Roles and Permissions with Teams  without Packages]]></title>
            <link>https://medium.com/@saadmoooooha2000/laravel-filament-php-roles-and-permissions-with-teams-without-packages-e6b789f1caff?source=rss-d8240f0f2bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6b789f1caff</guid>
            <category><![CDATA[php-developers]]></category>
            <category><![CDATA[filament]]></category>
            <category><![CDATA[roles-and-permissions]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php-8]]></category>
            <dc:creator><![CDATA[محمد ساعد]]></dc:creator>
            <pubDate>Sat, 04 Feb 2023 11:27:51 GMT</pubDate>
            <atom:updated>2023-07-02T17:45:47.786Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel , Filamentphp Roles and Permissions with Teams without Packages</h3><blockquote>بسم الله الرحمن الرحيم</blockquote><p>في هذا المقال سأشرح باستفاضة كيفية إنشاء نظام للأدوار و الصلاحيات في إطار الفرق بدون استعمال أي حزمة , و سأستخدم لوحة تحكم غاية في البساطة</p><h4>شرح مختصر</h4><p>تجزئة إدارة النظام إلى فرق بشكل أفقي يعني فصل إدارة النظام إلى فروع متطابقة مستقل عن بعضها بعض و جعل كل فريق يدير واحدا من هاته الفروع أو أكثر , و هذا يعني تشارك الفرق نفس مسميات الأدوار ثم يوكل توزيعها على الأعضاء إلى الإدارة العامة , و هكذا فالصلاحيات ﻻ ترتبط مباشرة بالأفراد بل بأدوارهم داخل الفرق , و يمكن بهذا الخصوص أن يمتلك أحد الأعضاء أكثرمن دور في فرق واحد و أن ينتسب إلى عدة فرق أيضا ما يعني اختلاف الصلاحيات الموكلة إليه باختلاف الفريق , و هكذا فإن المستخدم لا يحمل دورا إلا باعتباره عضوا في أحد الفرق</p><p>و لهذا فسنربط الفرق بالمستخدمين بأن ننشئ عنصرا جديدا اسمه العضو , يعمل معرفي المستخدم و الفريق المنتسب إليه , ثم نربط العضو مع الأدوار بعلاقة ( كثير إلى كثير ) لتمكينه من حمل أكثر من دور داخل الفريق ثم نربط الأدوار و الصلاحيات بعلاقة ( كثير إلى كثير ) لتمكين كل منهما من أن ينتسب إلى أكثر من واحد</p><h4><strong>خطة العمل</strong></h4><ul><li>ننشئ الجداول</li><li>نربط بين المستخدمين و الفرق</li><li>نربط بين عنصري الدور والصلاحية</li><li>إنشاء دوال مساعدة</li></ul><h4>إنشاء الجداول اللازمة</h4><p>يحوي كل من جدولي الأدوار و الصلاحيات عناصر أساسية ثابثة و هي الرقم المعرف و الاسم لكل منهما</p><blockquote>جدول الأدوار</blockquote><pre> Schema::create(&#39;roles&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;name&#39;);<br>            $table-&gt;timestamps();<br>        });</pre><blockquote>جدول الصلاحيات</blockquote><pre>    Schema::create(&#39;permissions&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;name&#39;);<br>            $table-&gt;timestamps();<br>        });</pre><blockquote>جدول الفرق</blockquote><pre>Schema::create(&#39;teams&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;name&#39;);<br>            //$table-&gt;unsignedBigInteger(&#39;level_id&#39;);<br>            //$table-&gt;foreign(&#39;level_id&#39;)-&gt;references(&#39;id&#39;)-&gt;on(&#39;levels&#39;);<br>            $table-&gt;timestamps();<br>        });</pre><blockquote>جدول المستخدمين</blockquote><pre> Schema::create(&#39;users&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;name&#39;);<br>            $table-&gt;string(&#39;email&#39;)-&gt;unique();<br>            $table-&gt;timestamp(&#39;email_verified_at&#39;)-&gt;nullable();<br>            $table-&gt;string(&#39;password&#39;);<br>            $table-&gt;rememberToken();<br>            $table-&gt;timestamps();<br>        });<br></pre><blockquote>جدول الأعضاء</blockquote><pre> php artisan make:model TeamUser        </pre><pre>Schema::create(&#39;team_users&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;unsignedBigInteger(&#39;user_id&#39;);<br>            $table-&gt;unsignedBigInteger(&#39;team_id&#39;);<br><br>            $table-&gt;foreign(&#39;user_id&#39;)-&gt;references(&#39;id&#39;)-&gt;on(&#39;users&#39;)-&gt;onDelete(&#39;cascade&#39;);<br>            $table-&gt;foreign(&#39;team_id&#39;)-&gt;references(&#39;id&#39;)-&gt;on(&#39;teams&#39;)-&gt;onDelete(&#39;cascade&#39;);<br><br>            $table-&gt;timestamps();<br>        });</pre><blockquote>جدول إعدادات المستخدم</blockquote><pre> Schema::create(&#39;user_settings&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;name&#39;);<br>            $table-&gt;string(&#39;content&#39;);<br>            $table-&gt;unsignedBigInteger(&#39;user_id&#39;);<br>            $table-&gt;foreign(&#39;user_id&#39;)-&gt;references(&#39;id&#39;)-&gt;on(&#39;users&#39;)-&gt;onDelete(&#39;cascade&#39;);<br>            $table-&gt;timestamps();<br>        });</pre><h4>ربط ما بين عنصري المستخدمين و الفرق</h4><p>بعد هذا يتبقى ربط كل عضو بالمستخدم و الفريق المشار إليهما ثم إطاؤه أدوارا</p><pre>class TeamUser extends Model<br>{<br>    use HasFactory;<br>   protected $fillable = [&#39;team_id&#39;,&#39;user_id&#39;];<br><br>/**<br>    * Get the user associated with the TeamUser<br>    *<br>    * @return \Illuminate\Database\Eloquent\Relations\HasOne<br>    */<br>   public function user()<br>   {<br>       return $this-&gt;hasOne(User::class, &#39;id&#39;, &#39;user_id&#39;);<br>   }<br><br>   /**<br>    * Get the team that owns the TeamUser<br>    *<br>    * @return \Illuminate\Database\Eloquent\Relations\BelongsTo<br>    */<br>   public function team()<br>   {<br>       return $this-&gt;belongsTo(Team::class);<br>   }<br>/**<br>    * The roles that belong to the TeamUser<br>    *<br>    * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany<br>    */<br>  public function roles()<br>   {<br>       return $this-&gt;belongsToMany(Role::class , &#39;role_team_user&#39;,&#39;team_user_id&#39;,&#39;role_id&#39;);<br>   }</pre><p>ثم ربط الأعضاء بالفرق</p><pre>class Team extends Model<br>{<br>    use HasFactory;<br>    protected $fillable = [&#39;name&#39;];<br><br>     /**<br>          * Get all of the membres for the Team<br>          *<br>          * @return \Illuminate\Database\Eloquent\Relations\HasMany<br>          */<br>          public function members()<br>          {<br>              return $this-&gt;hasMany(TeamUser::class);<br>          }</pre><h4>ربط ما بين عنصري الدور والصلاحية</h4><p>يحمل الدور الواحد عدة صلاحيات و تنتسب الصلاحيات إلى أكثرمن دور وهكذا فالعلاقة بينهما هي علاقة ( كثير إلى كثير )</p><pre>class Role extends Model<br>{<br>    use HasFactory,RolePermissionsTrait;<br><br>    /**<br>     * The permissions that belong to the Role<br>     *<br>     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany<br>     */<br>    public function permissions()<br>    {<br>        return $this-&gt;belongsToMany(Permission::class, &#39;permission_role&#39;, &#39;role_id&#39;, &#39;permission_id&#39;);<br>    }</pre><p>و ﻻ طائل من تعريف العلاقة المعاكسة من جهة الصلاحية</p><p>لتعريف الصلاحيات داخل النظام بأكمله فإننا سنستخدم حاصية البوابات</p><p>Gates</p><p>و هي تمكننا من التحكم بقدرات المستخدمين داخل النظام , و إذ أننا سنحتاج لإنشاء صلاحيات كثيرة فبدل تعرف كل منها على حدة فسننشئ ملف صلاحيات خاصا لكل عنصر</p><pre>php artisan make:policy TeamPolicy</pre><pre><br>class TeamPolicy<br>{<br>    use HandlesAuthorization;<br><br>    /**<br>     * Determine whether the user can view any models.<br>     *<br>     * @param  \App\Models\User  $user<br>     * @return \Illuminate\Auth\Access\Response|bool<br>     */<br>    public function viewAny(User $user)<br>    {<br>        return $user-&gt;hasPermission(&#39;viewAny-team&#39;);<br>    }<br><br>    /**<br>     * Determine whether the user can view the model.<br>     *<br>     * @param  \App\Models\User  $user<br>     * @param  \App\Models\Team  $team<br>     * @return \Illuminate\Auth\Access\Response|bool<br>     */<br>    public function view(User $user, Team $team)<br>    {<br>        return $user-&gt;hasPermission(&#39;view-team&#39;)  ;<br>    }<br><br>    /**<br>     * Determine whether the user can create models.<br>     *<br>     * @param  \App\Models\User  $user<br>     * @return \Illuminate\Auth\Access\Response|bool<br>     */<br>    public function create(User $user)<br>    {<br>        return $user-&gt;hasPermission(&#39;create-team&#39;);<br>    }<br><br>    /**<br>     * Determine whether the user can update the model.<br>     *<br>     * @param  \App\Models\User  $user<br>     * @param  \App\Models\Team  $team<br>     * @return \Illuminate\Auth\Access\Response|bool<br>     */<br>    public function update(User $user, Team $team)<br>    {<br>        return $user-&gt;hasPermission(&#39;edit-team&#39;);<br>    }<br><br>    /**<br>     * Determine whether the user can delete the model.<br>     *<br>     * @param  \App\Models\User  $user<br>     * @param  \App\Models\Team  $team<br>     * @return \Illuminate\Auth\Access\Response|bool<br>     */<br>    public function delete(User $user, Team $team)<br>    {<br>        return $user-&gt;hasPermission(&#39;delete-team&#39;);<br>    }</pre><p>و كما ترى فمن السهل قراءة ملف الصلاحيات حال استعملنا دالة مساعدة تتحقق من وجود الصلاحية دون كتابة هيكلها أكثر من مرة و كل ما عليها هو إرجاع القيمة 0 أو 1</p><h4>إنشاء دوال مساعدة</h4><p>لغرض إسناد الأدوار إلى أعضاء الفرق علينا كتابة بعض الدوال المساعدة في ملف خاص و ضمه إلى دوال المستخدم الأصلية لتجنب تكرار الأوامر الطويلة</p><pre><br>trait UserPermissionsTrait {</pre><pre>class User extends Authenticatable<br>{<br>    use UserPermissionsTrait;</pre><blockquote><strong>لم لم يتم ضم هاته الدوال إلى عنصر العضو ما دام هو من يحمل الصلاحيات؟</strong></blockquote><p>هذا ﻷن أهم ما سنحتاجه داخل نظامنا هو التحقق من قدرة المستخدم الداخل إلى لوحة التحكم من رؤية أو تعديل أجزاء النظام حسب الصلاحيات الموكلة إليه في فريقه , حتى إذا غير الفريق تغيرت الصلاحيات التي يحملها , و لذا علينا تعريف المستخدم بادئ الأمر ثم تعريف الفريق الذي يتصرف باسمه كي نعرف الدور الذي يحمله داخله و الصلاحيات الموكلة إلى ذلك الدور , و من هذا كله فعنصر العضو هو صفة تبنى بعد الحصول على المستخدم و الفريق</p><blockquote>دالة التحقق من امتلاك الصلاحية</blockquote><pre>public function hasPermission(...$perm)<br>        {<br>// البحث عن أفراد العناصر<br>            $premis = $this-&gt;getAllPermissions($perm);<br>  // إيجاد العضوية التي يحملها المستخدم <br>            $team_user = $this-&gt;team_user();<br>            if ($team_user == null){return false;}<br>            $perms =  $team_user-&gt;roles()-&gt;get()-&gt;map(function($role){<br>                return $role-&gt;permissions()-&gt;get()-&gt;pluck(&#39;name&#39;);<br>            }<br>            ($perms = $perms-&gt;collapse()-&gt;all());<br>           // dd($premis-&gt;all()[0],$perms);<br>            if($perms == null ){return false;}<br>           return(in_array($premis-&gt;all()[0],$perms));<br>        }</pre><p>بداية فإننا نمرر إلى الدالة عددا غير معرف من العناصر , صلاحية واحدة أو أكثر للتحقق من وجودها و نستخدم النقاط الثلاث … لغرض تحويل المدخل إلى مصفوفة من العناصر مفصولا بينها بفاصلة (,) و يمكنك القراءة عن هذا و طرق غيره بالمقال التالي</p><p><a href="https://www.php.net/manual/en/functions.arguments.php">PHP: Function arguments - Manual</a></p><p>ثم نستخد دالة للبحث أفراد تلك الصلاحيات من قاعدة البيانات حسب أسمائها</p><pre>protected function getAllPermissions(array $permissions) {<br><br>        $perms = Permission::whereIn(&#39;name&#39;,$permissions)-&gt;get()-&gt;pluck(&#39;name&#39;);<br>        return $perms;<br><br>      }</pre><p>ثم علينا إيجاد العضوية التي يحملها المستخدم باستخدام معرفه و المعرف الفريق الذي ينتسب إليه , و لكن لما كان بوسع المستخدم الانتساب إلى أكثر من فريق و التنقل بينها في قائمة بلوحة التحكم كان علينا تعريف صلاحياته حسب كل فريق , و لذا فسنجعل المستخدم يسجل معرف الفريق الحالي في جدول الإعدادات , و كلما غير فريقه تغير هذا المعرف , ما يمكننا من استعماله لتعريف صلاحياته في كل حالة</p><pre>class UserSetting extends Model<br>{<br>    use HasFactory;<br>    <br>}</pre><pre>class User extends Authenticatable<br>{<br>   public function settings()<br>    {<br>        return $this-&gt;hasMany(UserSetting::class);<br>    }<br>}</pre><p>و بهذا أمكنا إنشاء خاصية تدعى</p><p>current_team</p><p>تحمل معرف الفريق الحالي لكل مستخدم</p><pre>UserSetting::create([&#39;name&#39;=&gt;&#39;c_team&#39;,&#39;content&#39;=&gt;$team-&gt;id,&#39;user_id&#39;=&gt;$user-&gt;id]);</pre><p>نستدعي هاته المعلومة في ملف الصلاحيات السابق لنستعملها في تحديد عضوية المستخدم الحالية</p><pre>public function C_team(){<br>// البحث عن الفريق الحالي<br>        return $this-&gt;settings()-&gt;where(&#39;name&#39;,&#39;c_team&#39;)-&gt;first();<br>    }<br><br>    public function team_user(){<br>//الحصول على معرف الفريق الحالي <br>        $current_team_id = $this-&gt;C_team()-&gt;content;<br>        // استخدام معرفالمستخدم و فريقه الحالي لإيجاد عضويته الحالية <br>        $team_user = \App\Models\TeamUser::where(&#39;team_id&#39;,$current_team_id)-&gt;where(&#39;user_id&#39;,auth()-&gt;id())-&gt;first();<br>      <br>        return $team_user;<br>    }</pre><p>ثم نبحث عن الأدوار المسندة إلى المستخدم على ضوء هاته العضوية</p><pre>public function hasPermission(...$perm)<br>        {<br>            $premis = $this-&gt;getAllPermissions($perm);<br>            //$team = Team::find($this-&gt;c_team);<br>            $team_user = $this-&gt;team_user();<br>            if ($team_user == null){return false;}<br>// إيجاد الأدوار المسندة إلى العضوية , ثم استخراج صلاحيات كل دور و<br>            $perms =  $team_user-&gt;roles()-&gt;get()-&gt;map(function($role){<br>                return $role-&gt;permissions()-&gt;get()-&gt;pluck(&#39;name&#39;);<br>            });<br>            $perms = $perms-&gt;collapse()-&gt;all();<br>           // التحقق من وجود الصلاحية  المدلة بين الصلاحيات التي يملكها المستخدم <br>            if($perms == null ){return false;}<br>           return(in_array($premis-&gt;all()[0],$perms));<br>        }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6b789f1caff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel + Livewire إنشاء تطبيق محادثة نصية بداية العمل]]></title>
            <link>https://medium.com/@saadmoooooha2000/laravel-livewire-%D8%A5%D9%86%D8%B4%D8%A7%D8%A1-%D8%AA%D8%B7%D8%A8%D9%8A%D9%82-%D9%85%D8%AD%D8%A7%D8%AF%D8%AB%D8%A9-%D9%86%D8%B5%D9%8A%D8%A9-%D8%A8%D8%AF%D8%A7%D9%8A%D8%A9-%D8%A7%D9%84%D8%B9%D9%85%D9%84-bd9d3b71cabd?source=rss-d8240f0f2bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd9d3b71cabd</guid>
            <category><![CDATA[livewire]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[محمد ساعد]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 08:19:34 GMT</pubDate>
            <atom:updated>2020-06-20T10:18:14.489Z</atom:updated>
            <content:encoded><![CDATA[<p>بسم الله و الصلاة و السلام على رسول الله و على اله و صحبه و من والاه</p><p>سنقوم بتعريف المتغيرات</p><pre>public $message, $chat_id, $unreadedMessages,$paginate_var=10;</pre><p>ثم نعرف الملتقطات</p><pre>protected $listeners =[&#39;selected_users&#39;, &#39;loadMore&#39;];</pre><p>أولا نريد أن نظهر آخر المحادثات الي قمنا بها , و لهذا بدينا خانة آخر رسالة مرسلة في جدول المحادثات و لهذا فسنتبع طريقة بسيطة لإظهارها على النحو المطلوب</p><pre>// Controller</pre><pre>\App\Conversation::where(&#39;first_user&#39;,Auth::user()-&gt;id)<br>                  -&gt;orWhere(&#39;second_user&#39;,Auth::user()-&gt;id)<br>                  -&gt;orderBy(&#39;last_message_time&#39;,&#39;desc&#39;)<br>                  -&gt;get();</pre><p>و في الواجهة نظهرها على النحو التالي</p><pre>&lt;div class=&quot;list-group users rounded-0&quot; &gt;<br>            <a href="http://twitter.com/foreach">@foreach</a>($conversations as $conversation)</pre><pre>// إذا كنت أنا أول من بدء بالمحادثة فسيظهر صورة الاخر<br>           <a href="http://twitter.com/if">@if</a>(Auth::user()-&gt;id == $conversation-&gt;first_user)<br> &lt;a class=&quot;list-group-item  list-group-item-action   text-white rounded-0&quot; <strong>wire:click=&quot;$emit(&#39;selected_users&#39;,{{$conversation-&gt;second_user}})&quot;</strong> &gt;<br>          &lt;div class=&quot;media &quot;&gt;<br>              &lt;img src=&quot;{{Voyager::image($conversation-&gt;       seecond_user-&gt;avatar)}}&quot;  alt=&quot;user&quot; width=&quot;50&quot; class=&quot;rounded-circle&quot;&gt;<br>          &lt;div class=&quot;media-body ml-4 user&quot; &gt;<br>         &lt;div class=&quot;d-flex align-items-center justify-       content-between mb-1&quot;&gt;<br>         &lt;h6 class=&quot;mb-0&quot; style=&quot;color: black&quot;&gt;{{$conversation-&gt;seecond_user-&gt;name}}&lt;/h6&gt;&lt;small class=&quot;small font-weight-bold&quot; style=&quot;color: black&quot;&gt;&lt;/small&gt;<br>         &lt;/div&gt;<br>            &lt;p class=&quot;badge badge-danger {{$conversation-&gt;second_user}}&quot; style=&quot;color: black&quot; id=&quot;{{&#39;user&#39;.$conversation-&gt;first_user}}&quot; &gt;<br>{{\App\Message::where(&#39;statu&#39;,&#39;unreaded&#39;)-&gt;where(&#39;to_user&#39;,Auth::user()-&gt;id)-&gt;where(&#39;from_user&#39;,$conversation-&gt;seecond_user-&gt;id)-&gt;count()}}<br>                  &lt;/p&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/a&gt;</pre><pre><a href="http://twitter.com/else">@else</a></pre><pre>// إذا كنت  لم أنا أول من بدء بالمحادثة فسيظهر صورة من بدء</pre><pre>            &lt;div class=&quot;list-group-item list-group-item-action  text-white rounded-0  user3&quot; <strong>wire:click=&quot;$emit(&#39;selected_users&#39;,{{$conversation-&gt;first_user}})&quot;</strong> &gt;</pre><pre>              &lt;div class=&quot;media &quot; &gt;<br>                &lt;img src=&quot;{{Voyager::image($conversation-&gt;fiirst_user-&gt;avatar)}}&quot;  alt=&quot;user&quot; width=&quot;50&quot; class=&quot;rounded-circle&quot;&gt;<br>                &lt;div class=&quot;media-body ml-4 user&quot;&gt;<br>                  &lt;div class=&quot;d-flex align-items-center justify-content-between mb-1&quot; &gt;<br>                    &lt;h6 class=&quot;mb-0&quot; style=&quot;color: black&quot;&gt;{{$conversation-&gt;fiirst_user-&gt;name}}&lt;/h6&gt;&lt;small class=&quot;small font-weight-bold&quot; style=&quot;color: black&quot;&gt;&lt;/small&gt;<br>                  &lt;/div&gt;<br>                  &lt;p class=&quot;badge badge-danger {{$conversation-&gt;first_user}}&quot; style=&quot;color: black&quot;  id=&quot;{{&#39;user.&#39;.$conversation-&gt;first_user}}&quot;&gt;<br>                    {{\App\Message::where(&#39;statu&#39;,&#39;unreaded&#39;)-&gt;where(&#39;to_user&#39;,Auth::user()-&gt;id)-&gt;where(&#39;from_user&#39;,$conversation-&gt;fiirst_user-&gt;id)-&gt;count()}}&lt;/p&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>              &lt;p&gt;&lt;/p&gt;<br>            &lt;/div&gt;<br>              <a href="http://twitter.com/endif">@endif</a><br>            <a href="http://twitter.com/endforeach">@endforeach</a><br>          &lt;/div&gt;</pre><p>عند الضغط على أي محادثة سيشتغل الكود</p><pre><strong>wire:click=&quot;$emit(&#39;selected_users&#39;,{{$conversation-&gt;second_user}})&quot;</strong></pre><p>حيث سيتم إرسال إيفنت مع معرف المستخدم إلى ال</p><p>Controller</p><p>‘ listener = select_users‘ يتم التقاطه بواسطة ال</p><p>و الذي يقوم بتشغيل الدالة المسماة بنفس الاسم و تمرير المتغيرإليها</p><pre>public function selected_users($id)<br>          {<br> //--------تحديد المستخدم----------------        <br>         $this-&gt;chat_id = $id;<br>//---------جعل الرسائل التي أرسلت إلي من طرفه مقروءة-----<br>         Message::where(&#39;statu&#39;,&#39;unreaded&#39;)                                                where(&#39;to_user&#39;,Auth::user()-&gt;id)-&gt;where(&#39;from_user&#39;,$id)<br>-&gt;update(array(&#39;statu&#39;=&gt;&#39;readed&#39;));</pre><pre>// الامر بالسحب إلى أسفل المحادثة<br> $this-&gt;emit(&#39;scroll&#39;);<br>          <br>}</pre><pre>// Blade - js </pre><pre>    &lt;script type=&quot;text/javascript&quot;&gt;</pre><pre>window.livewire.on(&#39;scroll&#39;, function()  {<br>      $(&#39;#messages&#39;).animate({<br>          scrollTop: $(&#39;#messages&#39;)[0].scrollHeight}, &quot;slow&quot;);<br>})</pre><pre>&lt;/script&gt;</pre><p>و هكذا و قد حدد المستخدم الذي سنحادثه فسنجلب الرسائل التي أرسلت بيننا و بينه</p><pre>$user_id = Auth::user()-&gt;id;<br>$messages_count = Message::where(&#39;from_user&#39;,$user_id)<br>                         -&gt;where(  &#39;to_user&#39;,$id)<br>                         -&gt;orWhere(&#39;from_user&#39;,$id)<br>                         -&gt;where(&#39;to_user&#39;,$user_id)<br>                         -&gt;count();</pre><pre>// سأقوم بحساب عدد الرسائل بيننا ثم أظهر عددا محددا بطريقة القفز على العدد الذي لا أريده</pre><pre>$messages = Message::where(&#39;from_user&#39;,$user_id)<br>                 -&gt;where(&#39;to_user&#39;,$id)<br>                 -&gt;orWhere(&#39;from_user&#39;,$id)<br>                 -&gt;skip($messages_count - $this-&gt;paginate_var)<br>                 -&gt;take($this-&gt;paginate_var)                                 -&gt;where(&#39;to_user&#39;,$user_id)<br>                         -&gt;get();</pre><p>و نعرضها هكذا</p><pre>&lt;div class=&quot;messages-boxx&quot; id=&quot;messages-boxx&quot;  &gt;<br>        <a href="http://twitter.com/foreach">@foreach</a>($messages as $message)        <br>// اذا كنت أنا المرسل فستظهر الرسالة على اليمين          <br>          <a href="http://twitter.com/if">@if</a>(Auth::user()-&gt;id == $message-&gt;from_user)<br>                 &lt;!-- Sender Message--&gt;        <br>        &lt;div class=&quot;media w-50 ml-auto mb-3&quot;&gt;<br>          &lt;div class=&quot;media-body&quot;&gt;<br>            &lt;div class=&quot;bg-primary rounded py-2 px-3 mb-2&quot;&gt;<br>              &lt;p class=&quot;text-small mb-0 text-white&quot;&gt;{{$message-&gt;body}}&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;p class=&quot;small text-muted&quot;&gt;{{$message-&gt;created_at}}&lt;/p&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        <br>          <a href="http://twitter.com/else">@else</a>  //اذا كنت أنا المستقبل للرسالة<br>       &lt;!-- Reciever Message--&gt;<br>        &lt;div class=&quot;media w-50 mb-3&quot;&gt;<br>          &lt;img src=&quot;{{Voyager::image($message-&gt;froom_user-&gt;avatar)}}&quot; alt=&quot;user&quot; width=&quot;50&quot; class=&quot;rounded-circle&quot;&gt;<br>          &lt;div class=&quot;media-body ml-3&quot;&gt;<br>            &lt;div class=&quot;bg-light rounded py-2 px-3 mb-2&quot;&gt;<br>              &lt;p class=&quot;text-small mb-0 text-muted&quot;&gt;{{$message-&gt;body}}&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;p class=&quot;small text-muted&quot;&gt;{{$message-&gt;created_at}}&lt;/p&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>         <a href="http://twitter.com/endif">@endif</a><br>           <br>       <a href="http://twitter.com/endforeach">@endforeach</a><br>      &lt;/div&gt;</pre><p>و لتجربة أفضل فسنود إظهار عدد محدد من الرسائل , و بمجرد أن نسحب إلى أعلى فستظهر الرسائل السابقة و لهذا سنكتب كود جافا سكريبت</p><pre>&lt;script type=&quot;text/javascript&quot;&gt;<br>  $(&#39;#messages&#39;).scroll(function() {<br>   var top =$(&#39;#messages&#39;).scrollTop();<br>       if ( top == 0) {<br>        <strong>window.livewire.emit(&#39;loadMore&#39;)</strong><br>                       }<br>});<br>&lt;/script&gt;</pre><p>سيتم التقاط</p><p>loadmore event</p><p>من طرف الملتقطات و يتم على إثر هذا تشغيل الدالة المسماة بنفس الاسم</p><pre>public function loadMore()<br>       {<br>          $this-&gt;paginate_var = $this-&gt;paginate_var + 10;<br>       }</pre><p>فيزيد عدد الرسائل الظاهرة عشرة بعشرة</p><p><strong>2- إرسال الرسائل</strong></p><p>لدينا في الواجهة</p><pre>&lt;div class=&quot;input-group&quot;&gt;<br>          &lt;input type=&quot;text&quot; placeholder=&quot;Type a message&quot; aria-       describedby=&quot;button-addon2&quot; class=&quot;form-control rounded-0 border-0 py-4 bg-light&quot; <strong>wire:model=&#39;message&#39;</strong>&gt;<br>          &lt;div class=&quot;input-group-append&quot;&gt;<br>             &lt;button id=&quot;button-addon2&quot; type=&quot;submit&quot; class=&quot;btn btn-link&quot; <strong>wire:click=&#39;send&#39;</strong>&gt; &lt;i class=&quot;fa fa-paper-plane&quot; &gt;&lt;/i&gt;&lt;/button&gt;<br>          &lt;/div&gt;<br>      &lt;/div&gt;</pre><p>عند الضغط على الزر تستغل دالة الإرسال التالية</p><pre>public function send($id)<br>    {</pre><pre>//ان كانت محادثة سابقة بيننا أضيفت إليها الرسالة فقط و تم تسجيل تاريخ آخر رسالة في المحادثة , و إلا فسيتم انشاء محادثة جديدة و الارسال فيها<br>// <br>     $message = new Message;<br>        $message-&gt;body = $this-&gt;message;<br>        $message-&gt;from_user = Auth::user()-&gt;id;<br>        $message-&gt;to_user = $this-&gt;chat_id;<br>        $message-&gt;save();<br>        $this-&gt;render();<br>        $conv_old = \App\Conversation::where(&#39;first_user&#39;,$message-&gt;from_user)<br>                          -&gt;where(&#39;second_user&#39;,$message-&gt;to_user)<br>                          -&gt;orWhere(&#39;first_user&#39;,$message-&gt;to_user)<br>                          -&gt;where(&#39;second_user&#39;,$message-&gt;from_user)<br>                          -&gt;get()-&gt;first();<br>      if($conv_old)<br>{<br>   $conversation = \App\Conversation::find($conv_old-&gt;id);<br>   $conversation-&gt;last_message_time = $message-&gt;created_at;<br>   $conversation-&gt;save();<br>   $message-&gt;conversation_id = $conv_old-&gt;id;<br>   $message-&gt;save();</pre><pre>}</pre><pre>else<br>{<br> $conversation = new \App\Conversation;<br> $conversation-&gt;first_user = $message-&gt;from_user;<br> $conversation-&gt;second_user =$message-&gt;to_user;<br> $conversation-&gt;last_message_time = $message-&gt;created_at;<br>  $conversation-&gt;save();<br>  $message-&gt;conversation_id = $conversation-&gt;id;<br>  $message-&gt;save();<br>}<br>        $recivedUnreadedMessages =Message::where(&#39;statu&#39;,&#39;unreaded&#39;)<br>                                         -&gt;where(&#39;from_user&#39;,Auth::user()-&gt;id)<br>                                         -&gt;where(&#39;to_user&#39;, $this-&gt;chat_id)<br>                                         -&gt;count();<br>     $this-&gt;message = &#39;&#39;;<br>        $chat_user = User::find($this-&gt;chat_id);<br>        event(new \App\Events\Chat($this-&gt;chat_id,$message,$recivedUnreadedMessages,$chat_user));<br>    }</pre><p><strong>3- وصول و عرض الرسائل</strong></p><p>عند وصول الرسائل الى المستخدم المرسلة إليه سيتم التقاطها ثم عرضها بطريقة بسيطة</p><pre>&lt;script type=&quot;text/javascript&quot;&gt; <br>// storing my id<br> localStorage.setItem(&#39;uID&#39;,{{Auth::user()-&gt;id}});<br> <br> console.log (localStorage.getItem(&#39;uID&#39;)) ; <br>// الانصات الى الايفنت على القناة الموسومة بالمعرف الخاص بي</pre><pre>//lestening to the channel </pre><pre>&#39;chat&#39;.myIdwindow.Echo.private(&#39;Chat.&#39;+localStorage.getItem(&#39;uID&#39;))               .listen(&#39;.Chat&#39;, (e) =&gt; {<br>     // النزول الى أسفل مع قدوم أي رسالة جديدة       <br>     //--scrolling to bottom to see the new message<br>$(&#39;#messages&#39;).animate({   <br>       scrollTop: $(&#39;#messages&#39;)[0].scrollHeight}, &quot;slow&quot;);                  var id = @this.get(&#39;chat_id&#39;)   <br>                       //إذا كنت فاتح واجهة المحادثة مع الشخص الذي أرسل الرسالة ستظهر مباشرة .. و إلا  فسيزيد رقمن الرسائل غير المقروءة منه فقط          <br>//    <br>// If the conversation betwwen my and the sender is open now ....                               //-- appending the message tp messages box </pre><pre>  $(&quot;.&quot;+ e.message.from_user).html(`${e.recivedUnreadedMessages}`);                   </pre><pre>if( e.message.from_user == id){    </pre><pre>// عرض الرسالة </pre><pre>$(&#39;#messages-boxx&#39;).append(` &lt;div class=&quot;media w-50 mb-3&quot;&gt;                  &lt;div class=&quot;media-body ml-3&quot;&gt;            &lt;div class=&quot;bg-light rounded py-2 px-3 mb-2&quot;&gt;              &lt;p class=&quot;text-small mb-0 text-muted&quot;&gt;${e.message.body}&lt;/p&gt;            &lt;/div&gt;            &lt;p class=&quot;small text-muted&quot;&gt;${e.message.created_at}&lt;/p&gt;          &lt;/div&gt;        &lt;/div&gt;      `);               }               //---- else increment the num of the enreded messages between us               else               {                console.log(&quot;#user.&quot;+e.chat_user.id);                console.log(e.recivedUnreadedMessages);                }          });                 &lt;/script&gt;</pre><p><strong>الكود كاملا على </strong><a href="https://gist.github.com/saadmoooooha2000/dfca78f31a408e52806f11cbda2dc587"><strong>github</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd9d3b71cabd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>