File: savesmspercontact.py

package info (click to toggle)
python-gammu 3.2.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,024 kB
  • sloc: ansic: 11,446; python: 3,323; sql: 527; makefile: 6
file content (178 lines) | stat: -rwxr-xr-x 4,872 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python
# vim: expandtab sw=4 ts=4 sts=4:
#
# Copyright © 2003 - 2018 Michal Čihař <michal@cihar.com>
#
# This file is part of python-gammu <https://wammu.eu/python-gammu/>
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#


import errno
import os
import re

import gammu


def createFolderIfNotExist(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise


def getInternationalizedNumber(number):
    if not number:
        return "Unknown"

    if number.startswith("0"):
        return number.replace("0", "+49", 1)
    else:
        return number


def getFilename(mydir, mysms):
    if mysms[0]["DateTime"]:
        return mysms[0]["DateTime"].strftime("%Y-%m-%d-%Hh%Mm%Ss")

    # no date available so calculate unknown number
    myfiles = os.listdir(mydir)

    nextitem = 0
    for i in myfiles:
        match = re.match("^Unknown-([0-9]*)", i)
        if match and int(match.group(1)) > nextitem:
            nextitem = int(match.group(1))

    return "Unknown-" + str(nextitem + 1)


def saveSMS(mysms, all_contacts):
    my_number = getInternationalizedNumber(mysms[0]["Number"])

    try:
        mydir = all_contacts[my_number]
    except KeyError:
        mydir = my_number

    createFolderIfNotExist(mydir)

    myfile = getFilename(mydir, mysms)

    with open(os.path.join(mydir, myfile), "a") as handle:
        for i in mysms:
            handle.write(i["Text"].encode("UTF-8"))
        handle.write(b"\n")


def getContacts(state_machine):

    # Get all contacts
    remaining = state_machine.GetMemoryStatus(Type="SM")["Used"]
    contacts = dict()

    start = True

    try:
        while remaining > 0:
            if start:
                entry = state_machine.GetNextMemory(Start=True, Type="SM")
                start = False
            else:
                entry = state_machine.GetNextMemory(
                    Location=entry["Location"], Type="SM"
                )
                remaining = remaining - 1

            numbers = list()
            for entry in entry["Entries"]:
                if entry["Type"] == "Text_FirstName":
                    name = entry["Value"]
                else:
                    numbers.append(getInternationalizedNumber(entry["Value"]))

            for number in numbers:
                contacts[number] = name

    except gammu.ERR_EMPTY:
        # error is raised if memory is empty (this induces wrong reported
        # memory status)
        print("Failed to read contacts!")

    return contacts


def getAndDeleteAllSMS(state_machine):
    # Read SMS memory status ...
    memory = state_machine.GetSMSStatus()
    # ... and calculate number of messages
    remaining = memory["SIMUsed"] + memory["PhoneUsed"]

    # Get all sms
    start = True
    entries = list()

    try:
        while remaining > 0:
            if start:
                entry = state_machine.GetNextSMS(Folder=0, Start=True)
                start = False
            else:
                entry = state_machine.GetNextSMS(
                    Folder=0, Location=entry[0]["Location"]
                )

            remaining = remaining - 1
            entries.append(entry)

            # delete retrieved sms
            state_machine.DeleteSMS(Folder=0, Location=entry[0]["Location"])

    except gammu.ERR_EMPTY:
        # error is raised if memory is empty (this induces wrong reported
        # memory status)
        print("Failed to read messages!")

    # Link all SMS when there are concatenated messages
    entries = gammu.LinkSMS(entries)

    return entries


def main():
    # Get all contacts
    state_machine = gammu.StateMachine()
    state_machine.ReadConfig()
    state_machine.Init()
    contacts = getContacts(state_machine)
    state_machine.Terminate()

    # Get all sms
    # why in two steps? ERR_TIMOUT is raised without closing the connection
    state_machine = gammu.StateMachine()
    state_machine.ReadConfig()
    state_machine.Init()
    messages = getAndDeleteAllSMS(state_machine)
    state_machine.Terminate()

    for message in messages:
        saveSMS(message, contacts)


if __name__ == "__main__":
    main()