From 60d197c472077b20e8ca08633a586b6c8c137845 Mon Sep 17 00:00:00 2001
From: Someone <someone@somenet.org>
Date: Tue, 3 Jun 2014 04:08:19 +0200
Subject: [PATCH] submitbot nearly ready

---
 index.php    | 58 +++++++++++++++++++++++++++++++++++++
 styles.css   | 35 ++++++++++++++++++++++
 submit.php   | 50 ++++++++++++++++++++++++++++++++
 submitbot.py | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 225 insertions(+)
 create mode 100644 index.php
 create mode 100644 styles.css
 create mode 100644 submit.php
 create mode 100755 submitbot.py

diff --git a/index.php b/index.php
new file mode 100644
index 0000000..2fcd25f
--- /dev/null
+++ b/index.php
@@ -0,0 +1,58 @@
+<?php
+/** board script
+* Displayes the submitted flowIDs of the 
+* last X time with meta information 
+* If the submission to gameserver was successfull (submitsuccess)
+* and we got points for it (scoresuccess) it should be green bg
+*
+* 2014 by Jan "Someone" Vales <someone@somenet.org>
+* do not publish!
+*/
+
+$GLOBALS['db'] = new PDO('pgsql:host=localhost;port=5432;dbname=postgres;user=postgres;password=dba');                                                                                                              
+$GLOBALS['db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);                                                                                            
+$query = "SELECT * FROM flags WHERE (received + INTERVAL '90 minute') > now() ORDER BY received DESC";
+
+?>
+<!DOCTYPE html>
+  <html>
+  <head>
+    <link rel="stylesheet" type="text/css" href="styles.css"></link>
+  </head>
+  <body>
+    <h1>Submission Board</h1>
+    <p>Shows all submissions of the last 90 min<br>
+    NUM ROWS: <?php echo sizeof($GLOBALS['db']->query($query)->fetchAll()); ?></p>
+    <table style="width: 100%">
+      <thead>
+        <tr>
+            <th>fid</th>
+            <th>flag</th>
+            <th>service</th>
+            <th>received</th>
+            <th>submitted</th>
+            <th>status</th>
+            <th>srvresponse</th>
+          </tr>
+        </thead>
+        <tbody>
+          <?php
+          $stmt = $GLOBALS['db']->query($query);
+          while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+          ?>
+            <tr class="score-<?php echo $row['status']; ?>">
+              <td><?php echo $row['fid']; ?></td>
+              <td><?php echo $row['flag']; ?></td>
+              <td><?php echo $row['service']; ?>&nbsp;</td>
+              <td><?php echo $row['received']; ?></td>
+              <td><?php echo $row['submitted']; ?>&nbsp;</td>
+              <td><?php echo $row['status']; ?></td>
+              <td><?php echo htmlentities($row['srvresponse']); ?>&nbsp;</td>
+            </tr>
+            <?php
+          }
+          ?>
+        </tbody>
+      </table>
+    </body>
+    </html>
diff --git a/styles.css b/styles.css
new file mode 100644
index 0000000..8e8b0a6
--- /dev/null
+++ b/styles.css
@@ -0,0 +1,35 @@
+/*
+* 2014 by Jan "Someone" Vales <someone@somenet.org>
+* do not publish!
+*/
+body{
+	font-family: Tahoma;
+	font-size: 0.8em;
+}
+
+table, tr, td{
+	border-collapse: collapse;
+}
+thead th{
+	text-align: center;
+	background: #666;
+	color: #fff;
+	font-weight: normal;
+	padding: 3px;
+	border-left: 1px dashed #000;
+	border-bottom: 4px solid #000;
+}
+td{
+	padding: 5px;
+	border-left: 1px dashed #000;
+}
+
+.score-0{}
+
+.score-1{
+  background-color: #aee8a7;
+}
+
+.score-2{
+  background-color: #ff7c77;
+}
diff --git a/submit.php b/submit.php
new file mode 100644
index 0000000..f5ab2a6
--- /dev/null
+++ b/submit.php
@@ -0,0 +1,50 @@
+<?php
+/**
+* insert flowIDs and info to submit into log_db.log_t.
+* log_db.log_t gets periodically checked by 
+* script whichs tries to submit flowids to gameserver.
+* Information about this status can be found in board.php
+*
+* 2014 by Jan "Someone" Vales <someone@somenet.org>
+* do not publish!
+*/
+
+$GLOBALS['db'] = new PDO('pgsql:host=localhost;port=5432;dbname=postgres;user=postgres;password=dba');                                                                                                              
+$GLOBALS['db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);                                                                                            
+
+if (strcmp($_SERVER['REQUEST_METHOD'],"GET") === 0 || strcmp($_SERVER['REQUEST_METHOD'],"POST") === 0 ) {
+  handleRequest();
+} else {
+  http_response_code(405); //Method not implemented
+  exit("<p><b>what?</b> try GET or POST</p>");
+}
+
+function handleRequest() {
+  if (isset($_REQUEST['flag']) && isset($_REQUEST['service'])) {
+     insertData($_REQUEST['flag'],$_REQUEST['service']);
+  } else {
+     echo "<p><b>usage:</b><br>";
+     echo "GET /submit.php?flag=<i>STRING</i>&service=<i>STRING</i> <br>";
+     echo "POST<br> flag=<i>STRING</i>&service=<i>STRING</i></p>";
+  }
+}
+
+function insertData($flag, $service) {
+  echo "<p><b>inserting data...</b></p>";
+  echo "flag=".htmlentities($flag)."<br>";
+  echo "service=".htmlentities($service)."</p>";
+  $success = 0;
+  try {
+    $GLOBALS['db']->beginTransaction();
+    $stmt = $GLOBALS['db']->prepare("INSERT INTO flags (flag, service) VALUES(?, ?)");
+    $stmt->execute(array($flag, $service));
+    $GLOBALS['db']->commit();
+    $success = 1;
+  }catch(PDOException $ex) {
+    echo "<p><b>INSERT FAIL</b></p><p>".$ex->getMessage()."</p>";
+    $GLOBALS['db']->rollBack();
+  }
+
+  if ($success == 1) echo "<p><b>OK</b></p>";
+}
+
diff --git a/submitbot.py b/submitbot.py
new file mode 100755
index 0000000..1c92dd4
--- /dev/null
+++ b/submitbot.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python
+
+# 2014 by Jan "Someone" Vales <someone@somenet.org>
+# do not publish!
+
+import psycopg2
+import psycopg2.extras
+import sys
+import time
+import signal
+import mechanize
+
+def submit(flag):
+    print "submitting flag: "+flag
+    # TODO!!!!
+
+    # RETURN (success?, srvresponse)
+    return (2, 'FAIL')
+  
+def main():
+    sleeptime = 3
+    dbconn = None
+    while True:
+        try:
+            print "*** sleeping "+str(sleeptime)+" sec..."
+            time.sleep(sleeptime)
+            dbconn = psycopg2.connect("host=127.0.0.1 dbname=postgres user=postgres password=dba")
+            cur = dbconn.cursor()
+            cur.execute("CREATE TABLE IF NOT EXISTS flags ("
+                "fid serial NOT NULL PRIMARY KEY,"
+                "flag character varying(32) NOT NULL UNIQUE,"
+                "service character varying(32),"
+                "received timestamp without time zone NOT NULL DEFAULT date_trunc('second', NOW()),"
+                "submitted timestamp without time zone,"
+                "status integer NOT NULL DEFAULT 0,"
+                "srvresponse character varying(128)"
+                ")")
+            dbconn.commit()
+            cur.close()
+            print "Connected to DB + table created"
+
+            cur = None
+            while True:
+                print "*** sleeping another "+str(sleeptime)+" sec..."
+                time.sleep(sleeptime)
+                try:
+                    cur = dbconn.cursor(cursor_factory=psycopg2.extras.DictCursor)
+                    cur.execute("SELECT * from flags where status = 0")
+                    print "Fetched " + str(cur.rowcount) + " rows"
+    #                rows = cur.fetchall()
+                    for row in cur.fetchall():
+                        (success, resp) = submit(row['flag'])
+                        if success != 0:
+                            cur.execute("UPDATE flags SET submitted = date_trunc('second', NOW()), "
+                                "status = %s, srvresponse = %s WHERE fid = %s",
+                                (success, resp, row['fid']))
+                            dbconn.commit()
+                except psycopg2.DatabaseError as e:
+                    print 'Error %s' % e
+                try:
+                    cur.close()
+                    dbconn.rollback()
+                except psycopg2.DatabaseError as e:
+                    print 'Error %s' % e
+                cur = None
+                dbconn.rollback()
+            
+        except psycopg2.DatabaseError as e:
+            print 'Error %s' % e
+        try:
+            dbconn.close()
+        except psycopg2.DatabaseError as e:
+            print 'Error %s' % e
+        dbconn = None
+    print "should never be reached"
+
+if __name__ == "__main__":
+    def signal_handler(signal, frame):
+        print 'SIG received. exitting!'
+        sys.exit(0)
+    signal.signal(signal.SIGINT, signal_handler)
+    main()
-- 
2.43.0