summaryrefslogtreecommitdiffstats
path: root/src/tweetwriter.py
blob: ca68580cf4f324324b19af80ff7ef74abb99cbf2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
#!/usr/bin/python
# vim: set fileencoding=utf-8 ts=4 sts=4 sw=4 tw=80 expandtab :

# This file is part of schreimaschine.
#
# schreimaschine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# schreimaschine is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with schreimaschine.  If not, see <http://www.gnu.org/licenses/>.

import lxml.html
import json
import urllib.request
import urllib.parse
import re
import serial
import unicodedata
import logging
import argparse
import glob

from time import sleep
from html.entities import name2codepoint
from unidecode import unidecode


# FIXME nectarine needs more emoticons! :D

def htmldecode(s):
    """ Decode html entities like &quot; """
    logging.debug("Decoding HTML")
    # Ugly hack copied from somewhere to decode &foo;-sequences
    return re.sub('&(%s);' % '|'.join(name2codepoint),
        lambda m: chr(name2codepoint[m.group(1)]), s)

def fetch(service):
    """ Fetch oneliners from HTML """
    global config
    encoding = None
    reply = {
        "users": [],
        "texts": [],
        "raw": [],
    }

    logging.debug("<fetch> initial variables:")
    logging.debug("config: %r" % config)
    logging.debug("service: %r" % service)

    sconf = config["services"][service]

    # If it's a microblogging service (either tags or users defined), call
    # fetch_microblog to handle it, and don't care about the rest.
    if ("microblog_tags" in sconf or
        "microblog_users" in sconf):
        logging.debug("%s is a microblogging-service, calling fetch_microblog"
                      % service)
        results = fetch_microblog(service)
        return results

    logging.debug("Getting and parsing HTML...")
    url = sconf["url"]

    # If encoding is specified in the config, force the lxml parser to use that
    # one instead of auto-detect, because it seems to be flaky sometimes
    if "encoding" in sconf:
        try:
            parser = lxml.html.HTMLParser(encoding=sconf["encoding"])
        except LookupError: # invalid parser
            parser = None
    else:
        # Default parser
        parser = None

    # Get and parse the HTML
    try:
        u = urllib.request.urlopen(url)
    except IOError:
        logging.exception("IOError while trying to get %s!" % service)
        return None
    tree = lxml.html.parse(u, parser=parser, base_url=url)


    # Fetch users/texts/raw depending on the dicts where the service is in
    for target in "users", "texts", "raw":
        if target in sconf["xpath"]:
            logging.debug("%s has xpath[%s], fetching %s" % (service, target,
                                                            target))
            xpath = sconf["xpath"][target]
            logging.debug("XPath: %s" % xpath)
            try:
                reply[target] = tree.xpath(xpath)
            except AssertionError:
                logging.exception("AssertionError while trying to get %s for "
                                  "%s" % (target, service))
            except UnicodeDecodeError:
                logging.exception("UnicodeDecodeError while trying to get %s "
                                  "for %s" % (target, service))
            logging.debug("%s: %r" % (target, reply[target]))

    data = []

    if service == 'bitfellas':
        logging.debug("Doing bitfellas-magic")
        # Split users and texts and assign them to "users" and "texts",
        # because bitfellas is ugly
        for e in reply["raw"]:
            data.append(e.text_content()[2:].split(' \xa0 '))

        logging.debug("data: %r" % data)
        reply["users"], reply["texts"] = zip(*data)

    # Some services don't need text_content, or only need it for the texts or
    # users

    for target in "users", "texts":
        if "text_content" in sconf:
            if reply[target] and (target in sconf["text_content"]):
                logging.debug("Applying text_content() to %s" % target)
                reply[target] = [e.text_content() for e in reply[target]]
                logging.debug("%s: %r" % (target, reply[target]))
        reply[target] = [e.strip() for e in reply[target]]

    # Remove empty fields
    if "stripempty" in sconf:
        if sconf["stripempty"] == True:
            [ reply[target].remove(e) for e in reply["texts"] if e == '' ]

    # Cut timestamps and other foo
    if service == 'brainstorm':
        logging.debug("Cutting random foo for brainstorm")
        logging.debug("Users before cutting: %r" % reply['users'])
        reply["users"] = [user[:-6] for user in reply["users"]]
        logging.debug("Users after cutting: %s" % reply['users'])
    if service == 'amp':
        logging.debug("Cutting random foo for amp")
        logging.debug("Texts before cutting: %r" % reply['texts'])
        reply["texts"] = [text[8:] for text in reply["texts"]]
        logging.debug("Texts after cutting: %s" % reply['texts'])

    logging.debug("Generating data out of users and texts")
    if reply["users"] and reply["texts"]:
        # [ (user,text), (user,text) ... ]
        data = zip(reply["users"], reply["texts"])
    else:
        # [ ('-', text), ('-', text) ... ]
        data = [('-', text) for text in reply["texts"]]

    # Because tuples suck
    data = list(data)
    logging.debug("Data: %r" % data)

    # Because everyone except pouet does top-post :(
    if "reverse" in sconf:
        if sconf["reverse"] == True:
            logging.debug("Reversing data")
            data.reverse()

    # If there is new data, save the last element, and delete the older ones
    if len(data) > 0:
        logging.debug("There is new data")
        tmp = data[-1]
        logging.debug("Last element from this run: %r %r" % tmp)
        lastelem = sconf["last"]
        if lastelem is not None:
            try:
                # Behaves like "i = data.index(lastelem)" except it gets the
                # last occurence, not the first one
                i = len(data) - 1 - data[::-1].index(lastelem)
            except ValueError:
                # Something went wrong for sure.
                logging.exception("[E] ValueError / data: %s / last[%s]: %s" %
                                  (data, service, lastelem))
                data = []
            else:
                logging.debug("Deleting from data until index %r" % i)
                if i >= 0:
                    logging.debug("Deleting %r from data" % data[:i+1])
                    del data[:i+1]
        sconf["last"] = tmp

    logging.debug("Finished fetching, returning %r" % data)
    return data


def fetch_microblog(service):
    """ Fetch microblogging-stuff """
    global config
    logging.debug("<fetch_microblog> Initial variables:")
    logging.debug("config: %r" % config)
    results = []
    ask = []

    sconf = config["services"][service]

    # Form the query out of the users and/or tags
    if "microblog_tags" in sconf:
        microblog_tags=sconf["microblog_tags"]
        logging.debug("service %r has microblog_tags: %s", service,
                        microblog_tags)
        ask += microblog_tags
    if "microblog_users" in sconf:
        microblog_users=sconf["microblog_users"]
        logging.debug("service %r is in microblog_users: %s", service,
                      microblog_users)
        users = ['from:' + user for user in microblog_users]
        logging.debug("Users: %s" % users)
        ask += users
    # ask: [ 'foo', 'from:bar', ... ]
    # q:   "foo OR from"bar OR ..."
    logging.debug("ask: %s" % ask)
    q = ' OR '.join(ask)
    logging.debug("q: %s" % ask)

    # form the POST-data
    # Identica doesn't support since_id yet, so we use it for twitter only
    rpp = sconf["microblog_maxresults"]
    if service == 'twitter':
        lastelem = sconf["last"]
        if lastelem is None:
            lastelem = 0
        post = {'q': q, 'rpp': rpp, 'since_id': lastelem,
                'result_type': 'recent'}
    else:
        post = {'q': q, 'rpp': rpp}
    logging.debug("POST-data: %s" % post)
    post = urllib.parse.urlencode(post)
    logging.debug("POST-data urlencoded: %s" % post)


    logging.debug("Fetching data")
    url = sconf["url"]
    # Fetch it!
    try:
        f = urllib.request.urlopen('%s?%s' % (url, post))
    except urllib.error.URLError:
        logging.exception("URLError while trying to get %s!" % service)
        return None
    except BadStatusLine:
        logging.exception("BadStatusLine while trying to get %s!" % service)
        return None
    except socket.error:
        logging.exception("socket.error while trying to get %s" % service)
        return None
        
    logging.debug("Got back: %r" % f)
    html = f.read().decode('utf-8')
    logging.debug("Text we got: %s" % html)

    if not html:
        logging.warning("Got no data back from %s" % service)
        return None
    try:
        data = json.loads(html)
    except ValueError:
        logging.exception("ValueError while trying to parse %s json: \n%s",
                          service, html)
        return None
    logging.debug("Parsed JSON: %s" % data)

    if len(data["results"]) > 0:
        # Get the since_id for twitter
        if service == 'twitter':
            sconf["last"] = data["results"][0]["id"]
            logging.debug("Last-ID for %r: %r" %
                          (service,sconf["last"]))

        logging.debug("reversing data")
        data["results"].reverse()

        # Extract the relevant information from the JSON
        logging.debug("Parsing results")
        for r in data["results"]:
            user = htmldecode(r["from_user"])
            text = htmldecode(r["text"])
            logging.debug("Appending to results: (%r, %r)" % (user, text))
            results.append((user,text))

        # Save last tweet for identica, because it doesn't have since_id
        if service == 'identica':
            logging.debug("Saving last post for %r", service)
            tmp = results[-1]
            lastelem = sconf["last"]
            if lastelem is not None:
                try:
                    i = results.index(lastelem)
                except ValueError:
                    logging.exception("[E] ValueError / results: %s / " \
                                 "last[%s]: %s" % (results, service, lastelem))
                    results = []
                else:
                    logging.debug("Deleting from results until index %r" % i)
                    if i >= 0:
                        logging.debug("Deleting %r from results" %
                                      results[:i+1])
                        del results[:i+1]
            sconf["last"] = tmp

    logging.debug("Finished fetching, returning %r" % results)
    return results

def encode(string):
    """ Encode string to pass it to the typewriter """
    global config
    nomod = config["other"]["nomod"]
    logging.debug("Encoding string %r" % string)
    newstring = ''

    asciireplace = {
        199: '\\cedi',    # ç (cedi)
        231: '\\cedi',    # Ç (cedi)
        163: '\\pounds',  # £ (pounds-sign)
        176: '\\degrees', # ° (degree-sign)
        167: '\\section', # § (section-sign)
        339: '\\oe',      # œ (oe lignature)
        338: '\\OE',      # Π(OE lignature)
        230: '\\ae',      # æ (ae lignature)
        198: '\\AE',      # Æ (AE lignature)
        776: '\\uml ',    #   (Umlaut-dots)     (deadkey)
        768: '\\grave ',  # ` (Grave-Sign)      (deadkey)
        769: '\\acute ',  # ' (Acute-Sign/Aigu) (deadkey)
    }

    #### First, try to convert Unicode to ASCII ####
    for c in string:
        a = ord(c)
        logging.debug("Char %r / %r" % (c,a))
        # Unprintable ascii (8: backspace / 9: tab / 10: newline/ 177: DEL)
        # gets replaced by '\unknown'
        if (a < 32 and a != 8 and a != 9 and a != 10) or (a == 177):
            logging.debug("Unprintable ASCII!")
            newc = '\\unknown'
        elif a < 127: # Normal ASCII, not treated specially
            logging.debug("Normal ASCII")
            newc = c
        elif a in asciireplace: # In asciireplace, gets replaced
            logging.debug("In asciireplace")
            newc = asciireplace[a]
        else: # Unicode-foo
            logging.debug("Unicode-Char!")
            dec = unicodedata.normalize('NFKD', c)
            logging.debug("Normalized: %r", [ (ord(c),c) for c in list(dec) ])
            trans = unidecode(c).strip()
            logging.debug("Transliterated: %r", trans)
            if len(dec) == 2:
                logging.debug("Normalized char has exactly two values!")
                char1 = ord(dec[0])
                char2 = ord(dec[1])
                if char2 == 776: # Char with umlauts (ä)
                    logging.debug("It's an Umlaut!")
                    if char1 == ord('a'):
                        logging.debug("Combining to ä")
                        newc = '\\auml'
                    elif char1 == ord('o'):
                        logging.debug("Combining to ö")
                        newc = '\\ouml'
                    elif char1 == ord('u'):
                        logging.debug("Combining to ü")
                        newc = '\\uuml'
                    else:
                        logging.debug("It's some other umlaut")
                        newc = '\\uml' + dec[0]
                elif char2 == 768: # Char with accent grave (à)
                    logging.debug("It's a grave-sign!")
                    if char1 == ord('a'):
                        logging.debug("Combining to à")
                        newc = '\\agrave'
                    elif char1 == ord('e'):
                        logging.debug("Combining to è")
                        newc = '\\egrave'
                    else:
                        logging.debug("It's some other char with accent grave")
                        newc = '\\grave' + dec[0]
                elif char2 == 769: # Char with accent aigu/acute (é)
                    logging.debug("It's an aigu!")
                    if char1 == ord('e'):
                        logging.debug("Combining to é")
                        newc =  '\\eacute'
                    else:
                        logging.debug("It's some other char with accent aigu")
                        newc = '\\acute' + dec[0]
                elif char2 == 770: # Char with accent circumflex (ô)
                    logging.debug("It's an accent circumflex!")
                    newc = '^' + dec[0]
                else: # Some other foo
                    logging.debug("Something else, using transliteration")
                    newc = '(%s)' % trans
            else: # Either not normalizeable or more than 2 parts
                logging.debug("Not normalizeable, using transliteration")
                if not trans:
                    logging.debug("What a pity, there is no transliteration!")
                    trans = '-'
                newc = '(%s)' % trans
                logging.debug("New char: %r" % newc)

        # Everything should be ASCII now, so this should newer except, except
        # if I forgot some special case, but that would be exceptional.
        try:
            logging.debug("Encoding to ascii")
            newc.encode('ASCII')
        except UnicodeEncodeError:
            logging.exception('Could not convert "%r" to ascii, forcing!'
                              % newc)
            # FIXME ugly hack to strip non-ASCII?
            newc = newc.encode('ASCII', 'ignore').decode('ASCII')

        logging.debug("Final new char: %r" % newc)
        newstring += newc

    #### Now convert the ASCII to our typewriter-format ####
    logging.debug("Converting ASCII to typewriter")
    string = newstring
    newstring = ''

    twreplace = {
        # Chars which are formed using Shift + Key
        ':': 'S.', '[': '#w', ']': '#u', '+': 'S1', '"': 'S2', '*': 'S3',
        '%': 'S5', '&': 'S6', '/': 'S7', '(': 'S8', ')': 'S9', '=': 'S0',
        '?': "S'", '-': 'S_', ';': 'S,', '_': 'S-',
        '\\pounds': 'S$', '\\grave': 'S^', '\\eacute': 'SO', '\\agrave': 'SA',
        '\\egrave': 'SO', '\\acute': 'SM', '\\cedi'  : 'S4',
        # Chars which are formed using Code + Key
        '\\degrees': '#v' , '\\section': '#x' , '\\left'    : '#R',
        '\\rev'    : '#I' , '\\cr'     : '#\n', '\\up'      : '#o',
        '\\down'   : '#p' , '\\ctr'    : '#s' , '\\rmf'     : '#d',
        '\\lind'   : '#\t', '\\lineout': '#W' , '\\mandel'  : '#D',
        # Chars which are formed using Alt + Key
        '\\line1'  : 'L1' , '\\line15' : 'L2', '\\line2'    : 'L3',
        '\\pitch10': 'L4' , '\\pitch12': 'L5', '\\mardel'   : 'L6',
        '\\lmar'   : 'L7' , '\\rmar'   : 'L8', '\\tplus'    : 'L9',
        '\\tminus' : 'L0' , '\\auto'   : "L'", '\\underline': 'L^',
        '\\bold': 'LR'    ,
        # Special chars on the typewriter which aren't ASCII
        '\\uml'    : 'M'  , '\\auml'   : 'A' , '\\ouml'     : 'O' ,
        '\\uuml'   : 'U'  , '\\reloc'  : 'R' , '\\index'    : 'I' ,
        '\\back'   : 'B'  , '\\wordout': 'W' , '\\caps'     : 'C' ,
        '\\del'    : 'D'  ,
        # Special sequences for chars which are in ASCII/UTF8 but not on the
        # typewriter
        '\\unknown': 'S8?S9', # replacing unknown chars by (?)
        '\\oe': 'o#Re',       # o halfback e forms œ
        '\\OE': 'O#RE',       # O halfback E forms Œ
        '\\ae': 'a#Re',       # a halfback e forms æ
        '\\AE': 'A#RE',       # A halfback E forms Æ
        '<': '-S8',           # replacing < by -(
        '>': 'S9-',           # replacing > by )-
        '{': 'S0S8',          # replacing { by =(
        '}': 'S9S0',          # replacing } by =)
        '@': 'S8atS9',        # replacing @ by (at)
        '|': 'Si',            # replacing | by I
        '~': '-',             # replacing ~ by -
        '!': "'B.",           # ' backspace ., forms !
        '#': 'S7BS0'          # = backspace /, forms kinda #
    }

    twreplace_nomod = {
        '\\oe': 'oe',
        '\\OE': 'OE',
        '\\ae': 'ae',
        '\\AE': 'AE',
        '|': 'I',
        '@': '-at-',
        '\\uml': 'M',
        '\\auml': 'A',
        '\\ouml': 'O',
        '\\uuml': 'U',
    }

    # Change all chars in twreplace to a minus sign if we can't use modifiers
    # except the chars which are in twreplace_nomod
    if nomod:
        for e in twreplace:
            if e in twreplace_nomod:
                twreplace[e] = twreplace_nomod[e]
            else:
                twreplace[e] = '-'

    for (i,c) in enumerate(string):
        newc = ""
        logging.debug("Index %r: Char %r / %r" % (i, c,a))
        # Replace uppercase-chars with their lowercase-equivalents
        if (c.isalpha() and c.isupper()):
            if nomod:
                if (i == 0 or (string[i-1].islower() and
                               string[i-1].isalpha())):
                    newc = 'C'
                newc += c.lower()
                if (i == (len(string) - 1) or (string[i+1].islower() and
                   string[i+1].isalpha())):
                    newc += 'S'
            else:
                newc = 'S' + c.lower()
            logging.debug("%r is upper-case, converting to %r" % (c,newc))
        else:
            newc = c
        logging.debug("Newstring: %r / adding %r" % (newstring,newc))
        newstring += newc

    # Replace special chars according to the twreplace list
    for r in twreplace:
        logging.debug("String: %s / Replacing %s with %s" %
                      (newstring, r, twreplace[r]))
        newstring = newstring.replace(r, twreplace[r])
    newstring = newstring.replace('\\', '/')
    logging.debug("Done, newstring: %r" % newstring)

    return newstring

def output(data):
    """ Output the shouts to stdout and later to serial """
    global ser
    (lastservice, lastuser, lasttext) = (None, None, None)
    for (service, user, text) in data:
        if service == lastservice:
            service = '..' + (' ' * (len(lastservice) - 1))
        if user == lastuser:
            user = '..' + (' ' * (len(lastuser) - 1))
        if text == lasttext:
            text = '..' + (' ' * (len(lasttext) - 1))
        output = '%-12.12s | %-10.10s | %.200s' % (service, user, text)
        serout = '%.30s / %.30s / %.500s\n' % (encode(service),
                                             encode(user), encode(text))
        print("[SCR] " + output)
        printser(serout)
        ser.write("\n\n".encode('ASCII')) # empty line
        print()
        (lastservice, lastuser, lasttext) = (service, user, text)
    #print('------------------')

def printser(line):
    """ Output the data to the serial port """
    global ser, config
    if not config["serial"]["active"]:
        # We don't have an open serial connection
        if config["serial"]["debug"]:
            print("[SER] " + line)
    else:
        i=0
        for c in line:
            # ready = 0
            # # This simply blocks until we get an 1 over the serial connection
            # while not ready:
            #     logging.debug("<serout> Trying to read from serialport")
            #     r = ser.read()
            #     logging.debug("<serout> Read %s over serialport" % r)
            #     if r == '1':
            #         logging.debug("<serout> We're ready to go")
            #         ready = 1
            #     else:
            #         logging.warn("<serout> WTF, got %r back instead of 1"
            #                      % r)
            # logging.debug("<serout> Sending %s over serialport" % c)

            # FIXME timing okay?
            ser.write(c.encode('ASCII'))
            if (c != 'S' and c != 'C'):
                i+=1
            if (i == 65):
                ser.write("\n".encode('ASCII'))
                sleep(config["other"]["newlinedelay_long"])
                ser.write("  ".encode('ASCII'))
                i = 2
            if (c == ' '):
                sleep(config["other"]["chardelay"]*0.5)
            elif (c != 'S' and c != 'C'):
                sleep(config["other"]["chardelay"])



def parseopts():
    """ Parse command-line options """
    # assuming loglevel is bound to the string value obtained from the
    # command line argument. Convert to upper case to allow the user to
    # specify --log=DEBUG or --log=debug
    parser = argparse.ArgumentParser("usage: %(prog)s [options]")
    parser.add_argument('-l', '--log', dest='loglevel', help='Set loglevel',
                        default=0)
    parser.add_argument('-s', '--services', dest='services',
                        help='Choose services', default=None)
    parser.add_argument('-r', '--serial', dest='serial',
                        help='Turn on/off serial port', default=None)
    parser.add_argument('-c', '--config', dest='config',
                       help='Change config file location',
                        default = 'settings.json')
    args = parser.parse_args()
    return args

def initlog(args):
    """ Initialisation of the log """
    if (args.loglevel):
        loglevel = args.loglevel
    else:
        loglevel = 'info'
    numeric_level = getattr(logging, loglevel.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % loglevel)
    logging.basicConfig(level=numeric_level,
                        format='%(asctime)s [%(levelname)s] %(message)s',
                        datefmt='%m/%d/%Y %H:%M:%S')

    logging.info('Initialized.')

def probeserial():
    """
    Scans for serial ports, returns the first serial port
    we are able to connect to.
    TODO: send identify-char to Schreimaschine
    """
    while True:
        logging.debug("Probing for serial ports")
        ports = (glob.glob('/dev/ttyUSB*'))
        logging.debug("Ports: %r" % ports)

        for port in ports:
            logging.debug("Trying to connect to port %r" % port) 
            try:
                ser = serial.Serial(port)
            except serial.serialutil.SerialException:
                logging.debug("got SerialException on %r - continuing to "
                              "probe" % port)
            else:
                logging.debug("Could connect to %r - checking if it's open"
                              % port)
                if ser.isOpen():
                    logging.debug("Yay, %r is open - returning" % port)
                    return port
                else:
                    logging.debug("Could connect to %r but it's not open"
                                  % port)
            finally:
                ser.close()
        # No ports found
        logging.error("Couldn't find any serial ports! :(")
        sleep(2)

def parseconfig(args):
    """ Parse the configfile """
    global config, ser

    logging.debug('Loading config')
    with open(args.config) as f:
        config = json.load(f)

    if args.serial == "off":
        config["serial"]["active"] = False
        config["serial"]["debug"] = False
    elif args.serial == "debug":
        config["serial"]["active"] = False
        config["serial"]["debug"] = True
    elif args.serial is not None:
        config["serial"]["active"] = True
        config["serial"]["debug"] = False
        config["serial"]["port"] = args.serial
    else:
        config["serial"]["active"] = True
        config["serial"]["debug"] = False

    if config["serial"]["port"] == "auto":
        config["serial"]["port"] = probeserial()
    if config["serial"]["active"]:
        logging.debug("Opening serial port")
        args = {}
        for item in ['bytesize','parity','stopbits','xonxoff','rtscts',
                 'dsrdtr','baudrate','port']:
            args[item] = config['serial'][item]

        ser = serial.Serial(**args)

    logging.debug('Loading services')
    if 'services' in args and args['services'] is not None:
        config["other"]["services"] = args['services'].split(',')
        logging.debug('Loaded services from commandline: %r' %
                        config["other"]["services"])
        logging.debug('args["services"] was %s' % args['services'])
    else:
        config["other"]["services"] = config["services"]
        logging.debug('No services on commandline, using all services'
                      ' in config')

def initservices():
    """ Initialisation of the services """
    global config

    services = config["other"]["services"]

    for service in services:
        sconf = config["services"][service]
        logging.debug('Setting firstrun and last for %s' % service)
        sconf["firstrun"] = 1
        sconf["last"] = None

def init():
    global ser
    ser = None
    """ Initialisation of everything """
    args = parseopts()
    initlog(args)
    parseconfig(args)
    initservices()

def title():
    printser("\n")
    filename = config["other"]["title"]

    if filename is None:
        return

    try:
        f = open(filename)
    except IOError:
        logging.exception("Could not find title-file %r" % titlefile)
        f.close()
        return

    for line in f:
        printser(encode(line))
    f.close()
    printser("\n\n\n\n")

def main():
    global config

    init()
    title()

    services = config["other"]["services"]

    while True:
        data = []

        # FIXME empty users at pouet?!?
        logging.debug('Services: %s' % services)

        for service in services:
            sconf = config["services"][service]
            logging.info('Getting shouts from %s' % service)
            result = fetch(service)
            if (result):
                for (user,text) in result:
                    data.append((service, user, text))

                # Don't output the data on the first run
                if sconf["firstrun"] == 1:
                    logging.info("It's the first run of %s" % service)
                    sconf["firstrun"] = 0
                    if config["other"]["printfirstrun"] == True:
                        output(data)
                else:
                    output(data)
        logging.info("Sleeping...")
        sleep(3) # These seconds are left blank intentionally

if __name__ == '__main__':
    status = main()
    sys.exit(status)